@zuplo/graphql 5.1852.0 → 5.1854.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.minified.js CHANGED
@@ -32,7 +32,7 @@
32
32
  `))):c=t.stylize("[Circular]","special")),Zh(a)){if(s&&i.match(/^\d+$/))return c;a=JSON.stringify(""+i),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=t.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=t.stylize(a,"string"))}return a+": "+c}o(ul,"formatProperty");function pT(t,e){if(Zh(e))return t.stylize("undefined","undefined");if(Xh(e)){let r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}if(uT(e))return t.stylize(""+e,"number");if(aT(e))return t.stylize(""+e,"boolean");if(em(e))return t.stylize("null","null")}o(pT,"formatPrimitive");function fT(t,e,r){let n=0;return t.reduce(function(s,a){return n++,a.indexOf(`
33
33
  `)>=0&&n++,s+a.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?r[0]+(e===""?"":e+`
34
34
  `)+" "+t.join(`,
35
- `)+" "+r[1]:r[0]+e+" "+t.join(", ")+" "+r[1]}o(fT,"reduceToSingleString")});var nm=_($o=>{"use strict";Object.defineProperty($o,"__esModule",{value:!0});$o.format=void 0;var hT=Qh(),mT=rm(),yT=o((t,...e)=>(0,hT.format)(mT.inspect,t,e),"format");$o.format=yT});var or=_(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});ir.debug=ir.withoutEnv=ir.Debugger=void 0;var gT=Wh(),bT=nm(),jo=class{static{o(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,r){this.manager=e,this.ns=r,this.color=(0,gT.generateColor)(r),this.last=0,this.enabled=e.enabled.some(n=>n.test(r))}log(...e){if(!this.enabled)return;let r,n=e[0];typeof n=="function"?r=n():r=String(n);let i=Date.now()-(this.last||Date.now());r=(0,bT.format)(r,...e);let s=`${this.color(this.ns)} ${r} ${this.color(`+${i}ms`)}`;console.log(s),this.last=Date.now()}};ir.Debugger=jo;var Vo=class{static{o(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function im(t){return!t||t.length===0?[]:(t=t.replace(/\s/g,"").replace(/\*/g,".+"),t.split(",").map(e=>new RegExp(`^${e}$`)))}o(im,"extract");var Oi;function _T(t){t||(t=[]),typeof t=="string"&&(t=im(t)),Oi=new Vo(t)}o(_T,"withoutEnv");ir.withoutEnv=_T;function ET(t){let e=globalThis.DEBUG;Oi||(Oi=new Vo(im(e)));let r=new jo(Oi,t);return Oi.debuggers.set(t,r),Object.assign(r.log.bind(r),{self:r})}o(ET,"debug");ir.debug=ET});var Go=_(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.ProblemResponseFormatter=hn.InternalProblemResponseFormatter=void 0;var wT=k(),Bo=class t{static{o(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let r=e.problem,n=JSON.stringify(r,null,2);return new Response(n,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(t.problemResponseFormat=(r,n,i)=>{try{return e(r,n,i)}catch(s){throw new wT.RuntimeError("Error in custom 'problemResponseFormat'",{cause:s})}})}};hn.InternalProblemResponseFormatter=Bo;var pl=class{static{o(this,"ProblemResponseFormatter")}static async format(e,r,n){return await Bo.problemResponseFormat(e,r,n)}};hn.ProblemResponseFormatter=pl});var sm=_(Ko=>{"use strict";Object.defineProperty(Ko,"__esModule",{value:!0});Ko.deepFreeze=void 0;function om(t){for(let e in t){let r=t[e];r&&typeof r=="object"&&om(r)}return Object.freeze(t)}o(om,"deepFreeze");Ko.deepFreeze=om});var Ke=_(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});Jo.ZuploRequest=void 0;var am=sm(),fl=class t extends Request{static{o(this,"ZuploRequest")}#e=void 0;#t;constructor(e,r){super(e,r);let n=r?.params;n?this.#t=n:e instanceof t?this.#t=e.#t:this.#t={};let i=r?.user;i?this.user=i:e instanceof t&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},r=new URL(this.url).searchParams;for(let[n,i]of r.entries())e[n]=i;this.#e=e}return(0,am.deepFreeze)(this.#e)}get params(){return(0,am.deepFreeze)(this.#t)}user};Jo.ZuploRequest=fl});var Ot=_(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.initializeRuntime=Ie.invokeOnResponseSendingFinalExtensions=Ie.invokeOnResponseSendingExtensions=Ie.invokeOnRequestExtensions=Ie.plugins=Ie.runtimeExtensions=Ie.SystemRuntimePlugin=Ie.RuntimePlugin=void 0;var cm=k(),vT=Go(),TT=Ke(),Wo=class{static{o(this,"RuntimePlugin")}};Ie.RuntimePlugin=Wo;var Qo=class extends Wo{static{o(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,r){}};Ie.SystemRuntimePlugin=Qo;Ie.runtimeExtensions={};var hl=[];Ie.plugins=hl;var um=[],lm=[],dm=[],zo={addPlugin(t){hl.push(t)},addRequestHook(t){um.push(t)},addResponseSendingHook(t){lm.push(t)},addResponseSendingFinalHook(t){dm.push(t)}},ST=o(async(t,e)=>{let r=t;for(let n of um){let i=await n(r,e);if(i instanceof TT.ZuploRequest)r=i;else{if(i instanceof Response)return i;throw new cm.ConfigurationError(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof r}.`)}}return r},"invokeOnRequestExtensions");Ie.invokeOnRequestExtensions=ST;var IT=o(async(t,e,r)=>{let n=t;for(let i of lm){let s=await i(t,e,r);if(s instanceof Response)n=s;else throw new cm.ConfigurationError(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof n}.`)}return n},"invokeOnResponseSendingExtensions");Ie.invokeOnResponseSendingExtensions=IT;var PT=o(async(t,e,r)=>{for(let n of dm)await n(t,e,r)},"invokeOnResponseSendingFinalExtensions");Ie.invokeOnResponseSendingFinalExtensions=PT;async function AT(t=()=>Promise.resolve()){await t(zo),Ie.runtimeExtensions.value=zo;for(let e of hl)e instanceof Qo&&await e.initialize(zo);vT.InternalProblemResponseFormatter.setProblemResponseFormat(zo.problemResponseFormat)}o(AT,"initializeRuntime");Ie.initializeRuntime=AT});var ml=_(sr=>{"use strict";Object.defineProperty(sr,"__esModule",{value:!0});sr.serialize=sr.ContentTypes=void 0;sr.ContentTypes={Json:"application/json",Form:"application/x-www-form-urlencoded"};function RT(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(sr.ContentTypes.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(sr.ContentTypes.Json)||!e?JSON.stringify(t):t}o(RT,"serialize");sr.serialize=RT});var yl=_(Yo=>{"use strict";Object.defineProperty(Yo,"__esModule",{value:!0});Yo.isSystemRoute=void 0;var pm=qr();function OT(t){return pm.Gateway.instance.runtimeSettings.developerPortal.enabled&&t.pathname.startsWith(pm.Gateway.instance.runtimeSettings.developerPortal.sitePathname)||t.pathname.startsWith("/__zuplo/")}o(OT,"isSystemRoute");Yo.isSystemRoute=OT});var Gt=_(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});Zo.Pipeline=void 0;var gl=$r(),fm=Ot(),NT=ml(),CT=ie(),xT=yl(),bl=class{static{o(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,r)=>async(n,i)=>{try{return await e(n,i)}catch(s){return i.log.error("Error executing request handler.",s),r.errorHandler(n,i,s)}};#t=({processors:e,gateway:r,handler:n})=>async(i,s)=>{let a=[...e],c=o(async b=>{let I=a.pop();return I?I(i,s,r,c):await this.#e(async g=>{let v=await n(g,s);return LT(v)},r)(b,s)},"nextPipe"),l=await c(i),d=new URL(i.url);if((0,xT.isSystemRoute)(d)&&CT.Environment.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new gl.ResponseSendingEvent(i,l);s.dispatchEvent(p);let f=gl.ZuploContextExtensions.getContextExtensions(s),h=f.latestRequest,y;try{y=await p.mutableResponse}catch(b){return s.log.error(b),r.errorHandler(i,s,b)}try{y=await f.onResponseSending(y,h,s)}catch(b){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),r.errorHandler(i,s,b)}try{y=await(0,fm.invokeOnResponseSendingExtensions)(y,h,s)}catch(b){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),r.errorHandler(i,s,b)}s.dispatchEvent(new gl.ResponseSentEvent(i,y));try{await f.onResponseSendingFinal(l,h,s)}catch(b){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}try{await(0,fm.invokeOnResponseSendingFinalExtensions)(l,h,s)}catch(b){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}return y}};Zo.Pipeline=bl;function LT(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response((0,NT.serialize)(t),{headers:{"content-type":"application/json"}})}o(LT,"resultToResponse")});var es=_(Xo=>{"use strict";Object.defineProperty(Xo,"__esModule",{value:!0});Xo.MetricsPlugin=void 0;var DT=Ot(),_l=class extends DT.RuntimePlugin{static{o(this,"MetricsPlugin")}};Xo.MetricsPlugin=_l});var Je=_(ts=>{"use strict";Object.defineProperty(ts,"__esModule",{value:!0});ts.SystemLogMap=void 0;var MT=k(),El=class t{static{o(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let r=t.#e.get(e);if(!r){let n=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(n),new MT.SystemError(n)}return r}static addLogger(e,r){t.#e.set(e,r)}};ts.SystemLogMap=El});var Re=_(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});rs.BatchDispatch=void 0;var wl=class{static{o(this,"BatchDispatch")}constructor(e,r,n,i){this.#t=e,this.#o=r,this.#n=n,this.#r=i??console}#e=void 0;#t;#r;#n;#i=[];#o;enqueue=e=>{this.#i.push(e),this.#e||(this.#e=new Promise(r=>{setTimeout(()=>{if(this.#i.length>0){let n=[...this.#i];this.#i.length=0,this.#e=void 0,this.#n(n).catch(i=>{this.#r.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,i.message,i.stack)}).finally(()=>{r()})}},this.#o)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};rs.BatchDispatch=wl});var mm=_(is=>{"use strict";Object.defineProperty(is,"__esModule",{value:!0});is.EllieMetricsTransport=void 0;var hm=Je(),UT=Re(),ns=ie(),vl=class{static{o(this,"EllieMetricsTransport")}#e;#t;#r;constructor(e){this.#r=ns.Environment.instance.loggingId,this.#e=e,this.#t=new UT.BatchDispatch("ellie-metrics-transport",10,this.dispatchFunction,hm.SystemLogMap.getLogger(e))}pushMetrics(e,r){this.#r!==void 0&&(this.#t.enqueue(e),r.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let r,{loggingId:n,remoteLogURL:i,deploymentName:s}=ns.Environment.instance,a=e.map(c=>{let u=Object.assign({},c);return delete u.requestContentLength,delete u.responseContentLength,u});if(n&&s&&(r=`${i}/v1-alpha/metrics?loggingId=${encodeURI(n)}&deploymentName=${encodeURI(s)}`),r){let c=await fetch(r,{method:"POST",body:JSON.stringify(a),headers:{"content-type":"application/json","zp-dn":ns.Environment.instance.deploymentName??"unknown","user-agent":ns.Environment.instance.systemUserAgent}});if(!c.ok){let u=await c.text();hm.SystemLogMap.getLogger(this.#e).error(`Metrics POST responded ${c.status}: ${c.statusText}`,u)}}}};is.EllieMetricsTransport=vl});var gt=_(jr=>{"use strict";Object.defineProperty(jr,"__esModule",{value:!0});jr.systemNoVersion=jr.SystemRouteConfiguration=void 0;var Tl=class{static{o(this,"SystemRouteConfiguration")}constructor({label:e,path:r,methods:n,systemRouteName:i,corsPolicy:s="none"}){this.label=e,this.path=r,this.methods=n,this.corsPolicy=s,this.version=jr.systemNoVersion.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=i}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}};jr.SystemRouteConfiguration=Tl;jr.systemNoVersion={name:"__system-no-version",pathPrefix:""}});var ar=_(os=>{"use strict";Object.defineProperty(os,"__esModule",{value:!0});os.metricsProcessor=void 0;var ym=Fr(),kT=$r(),FT=Ot(),HT=es(),qT=mm(),$T=gt(),jT=o(async(t,e,r,n)=>{let i=new Date,s=Date.now(),a=await n(t),c=t.headers.get(ym.RAY_ID_HEADER)??void 0,u=t.headers.get(ym.TRUE_CLIENT_IP)??void 0,l=e.incomingRequestProperties,d;e.route instanceof $T.SystemRouteConfiguration&&(d=e.route.systemRouteName);let p=kT.ZuploContextExtensions.getContextExtensions(e).latestRequest,f={timestamp:i,statusCode:a.status,durationMs:Date.now()-s,requestContentLength:t.headers.get("content-length")?Number(t.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:t.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:c,instanceId:r.instanceId,userSub:p.user?.sub,clientIp:u},h=[];return h.push(new qT.EllieMetricsTransport(e)),FT.plugins.forEach(y=>{if(y instanceof HT.MetricsPlugin){let b=y.getTransport();h.push(b)}}),h.forEach(y=>{y.pushMetrics(f,e)}),a},"metricsProcessor");os.metricsProcessor=jT});var Sl=_(ss=>{"use strict";Object.defineProperty(ss,"__esModule",{value:!0});ss.SystemRouteName=void 0;var gm;(function(t){t.Build="build-data",t.CorsPreflight="cors-preflight",t.DeveloperPortal="developer-portal",t.DeveloperPortalLegacy="developer-portal-legacy",t.StripePlugin="stripe-plugin",t.EmptyGatewayCatchall="empty-gateway-catchall",t.Ping="ping",t.UnmatchedPath="unmatched-path"})(gm||(ss.SystemRouteName=gm={}))});var _m=_(bm=>{"use strict";Object.defineProperty(bm,"__esModule",{value:!0})});var Vr=_(cr=>{"use strict";var VT=cr&&cr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Em=cr&&cr.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&VT(e,t,r)};Object.defineProperty(cr,"__esModule",{value:!0});Em(Sl(),cr);Em(_m(),cr)});var wm=_(as=>{"use strict";Object.defineProperty(as,"__esModule",{value:!0});as.registerBuildRoute=void 0;var BT=Kt(),GT=Gt(),KT=ar(),JT=Vr(),zT=gt(),WT=Je(),QT=ie(),YT=o((t,e)=>{let r=o(async(s,a)=>{let u=new URL(s.url).hostname.toLowerCase();if(!u.endsWith(".zuplo.app")&&!u.endsWith(".zuplo.dev")&&!u.endsWith(".fly.dev")&&!u.endsWith("zuplotest.com")&&u!=="localhost")return BT.HttpProblems.notFound(s,a);let l=QT.Environment.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.IS_PRODUCTION},p=s.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&WT.SystemLogMap.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),n=new GT.Pipeline({processors:[KT.metricsProcessor],handler:r,gateway:e}),i=new zT.SystemRouteConfiguration({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:JT.SystemRouteName.Build});t.addRoute(i,n.execute)},"registerBuildRoute");as.registerBuildRoute=YT});var Il=_(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.HTTP_STATUS_TITLES=mn.HttpStatusCode=void 0;var vm;(function(t){t[t.CONTINUE=100]="CONTINUE",t[t.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",t[t.PROCESSING=102]="PROCESSING",t[t.EARLY_HINTS=103]="EARLY_HINTS",t[t.OK=200]="OK",t[t.CREATED=201]="CREATED",t[t.ACCEPTED=202]="ACCEPTED",t[t.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",t[t.NO_CONTENT=204]="NO_CONTENT",t[t.RESET_CONTENT=205]="RESET_CONTENT",t[t.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",t[t.MULTI_STATUS=207]="MULTI_STATUS",t[t.ALREADY_REPORTED=208]="ALREADY_REPORTED",t[t.IM_USED=226]="IM_USED",t[t.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",t[t.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",t[t.FOUND=302]="FOUND",t[t.SEE_OTHER=303]="SEE_OTHER",t[t.NOT_MODIFIED=304]="NOT_MODIFIED",t[t.USE_PROXY=305]="USE_PROXY",t[t.SWITCH_PROXY=306]="SWITCH_PROXY",t[t.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",t[t.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",t[t.BAD_REQUEST=400]="BAD_REQUEST",t[t.UNAUTHORIZED=401]="UNAUTHORIZED",t[t.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",t[t.FORBIDDEN=403]="FORBIDDEN",t[t.NOT_FOUND=404]="NOT_FOUND",t[t.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",t[t.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",t[t.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",t[t.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",t[t.CONFLICT=409]="CONFLICT",t[t.GONE=410]="GONE",t[t.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",t[t.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",t[t.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",t[t.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",t[t.URI_TOO_LONG=414]="URI_TOO_LONG",t[t.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",t[t.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",t[t.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",t[t.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",t[t.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",t[t.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",t[t.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",t[t.LOCKED=423]="LOCKED",t[t.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",t[t.TOO_EARLY=425]="TOO_EARLY",t[t.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",t[t.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",t[t.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",t[t.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",t[t.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",t[t.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",t[t.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",t[t.BAD_GATEWAY=502]="BAD_GATEWAY",t[t.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",t[t.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",t[t.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",t[t.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",t[t.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",t[t.LOOP_DETECTED=508]="LOOP_DETECTED",t[t.NOT_EXTENDED=510]="NOT_EXTENDED",t[t.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED"})(vm||(mn.HttpStatusCode=vm={}));mn.HTTP_STATUS_TITLES={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 Al=_(Pl=>{"use strict";Object.defineProperty(Pl,"__esModule",{value:!0});var ZT={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"};Pl.default=ZT});var de=_(yn=>{"use strict";var XT=yn&&yn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(yn,"__esModule",{value:!0});yn.HttpProblems=void 0;var eS=Fr(),H=Il(),tS=XT(Al()),rS=ie(),Rl=Go();function nS(t){return`${new URL(t.url).pathname}`}o(nS,"instance");function iS(t,e){let r={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:rS.Environment.instance.build.BUILD_ID},n=t.headers.get(eS.RAY_ID_HEADER);return n&&(r.rayId=n),r}o(iS,"trace");var oS=o((t,e,r,n,i)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:nS(e),trace:iS(e,r),...n},additionalHeaders:i,statusText:tS.default[t.status]}),"merge"),Ol=class{static{o(this,"HttpProblemsBase")}static format=(e,r,n)=>"problem"in e?Rl.ProblemResponseFormatter.format(e,r,n):Rl.ProblemResponseFormatter.format({problem:e},r,n);static getProblemFromStatus(e,r){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:H.HTTP_STATUS_TITLES[e],...r}}},Nl=class extends Ol{static{o(this,"HttpProblems")}static#e(e,r,n,i,s){let a=oS(this.getProblemFromStatus(e),r,n,i,s);return Rl.ProblemResponseFormatter.format(a,r,n)}static continue=(e,r,n,i)=>this.#e(H.HttpStatusCode.OK,e,r,n,i);static switchingProtocols=(e,r,n,i)=>this.#e(H.HttpStatusCode.SWITCHING_PROTOCOLS,e,r,n,i);static processing=(e,r,n,i)=>this.#e(H.HttpStatusCode.PROCESSING,e,r,n,i);static earlyHints=(e,r,n,i)=>this.#e(H.HttpStatusCode.EARLY_HINTS,e,r,n,i);static ok=(e,r,n,i)=>this.#e(H.HttpStatusCode.OK,e,r,n,i);static created=(e,r,n,i)=>this.#e(H.HttpStatusCode.CREATED,e,r,n,i);static accepted=(e,r,n,i)=>this.#e(H.HttpStatusCode.ACCEPTED,e,r,n,i);static nonAuthoritativeInformation=(e,r,n,i)=>this.#e(H.HttpStatusCode.NON_AUTHORITATIVE_INFORMATION,e,r,n,i);static noContent=(e,r,n,i)=>this.#e(H.HttpStatusCode.NO_CONTENT,e,r,n,i);static resetContent=(e,r,n,i)=>this.#e(H.HttpStatusCode.RESET_CONTENT,e,r,n,i);static partialContent=(e,r,n,i)=>this.#e(H.HttpStatusCode.PARTIAL_CONTENT,e,r,n,i);static multiStatus=(e,r,n,i)=>this.#e(H.HttpStatusCode.MULTI_STATUS,e,r,n,i);static alreadyReported=(e,r,n,i)=>this.#e(H.HttpStatusCode.ALREADY_REPORTED,e,r,n,i);static imUsed=(e,r,n,i)=>this.#e(H.HttpStatusCode.IM_USED,e,r,n,i);static multipleChoices=(e,r,n,i)=>this.#e(H.HttpStatusCode.MULTIPLE_CHOICES,e,r,n,i);static movedPermanently=(e,r,n,i)=>this.#e(H.HttpStatusCode.MOVED_PERMANENTLY,e,r,n,i);static found=(e,r,n,i)=>this.#e(H.HttpStatusCode.FOUND,e,r,n,i);static seeOther=(e,r,n,i)=>this.#e(H.HttpStatusCode.SEE_OTHER,e,r,n,i);static notModified=(e,r,n,i)=>this.#e(H.HttpStatusCode.NOT_MODIFIED,e,r,n,i);static useProxy=(e,r,n,i)=>this.#e(H.HttpStatusCode.USE_PROXY,e,r,n,i);static switchProxy=(e,r,n,i)=>this.#e(H.HttpStatusCode.SWITCH_PROXY,e,r,n,i);static temporaryRedirect=(e,r,n,i)=>this.#e(H.HttpStatusCode.TEMPORARY_REDIRECT,e,r,n,i);static permanentRedirect=(e,r,n,i)=>this.#e(H.HttpStatusCode.PERMANENT_REDIRECT,e,r,n,i);static badRequest=(e,r,n,i)=>this.#e(H.HttpStatusCode.BAD_REQUEST,e,r,n,i);static unauthorized=(e,r,n,i)=>this.#e(H.HttpStatusCode.UNAUTHORIZED,e,r,n,i);static paymentRequired=(e,r,n,i)=>this.#e(H.HttpStatusCode.PAYMENT_REQUIRED,e,r,n,i);static forbidden=(e,r,n,i)=>this.#e(H.HttpStatusCode.FORBIDDEN,e,r,n,i);static notFound=(e,r,n,i)=>this.#e(H.HttpStatusCode.NOT_FOUND,e,r,n,i);static methodNotAllowed=(e,r,n,i)=>this.#e(H.HttpStatusCode.METHOD_NOT_ALLOWED,e,r,n,i);static notAcceptable=(e,r,n,i)=>this.#e(H.HttpStatusCode.NOT_ACCEPTABLE,e,r,n,i);static proxyAuthenticationRequired=(e,r,n,i)=>this.#e(H.HttpStatusCode.PROXY_AUTHENTICATION_REQUIRED,e,r,n,i);static requestTimeout=(e,r,n,i)=>this.#e(H.HttpStatusCode.REQUEST_TIMEOUT,e,r,n,i);static conflict=(e,r,n,i)=>this.#e(H.HttpStatusCode.CONFLICT,e,r,n,i);static gone=(e,r,n,i)=>this.#e(H.HttpStatusCode.GONE,e,r,n,i);static lengthRequired=(e,r,n,i)=>this.#e(H.HttpStatusCode.LENGTH_REQUIRED,e,r,n,i);static preconditionFailed=(e,r,n,i)=>this.#e(H.HttpStatusCode.PRECONDITION_FAILED,e,r,n,i);static contentTooLarge=(e,r,n,i)=>this.#e(H.HttpStatusCode.CONTENT_TOO_LARGE,e,r,n,i);static uriTooLong=(e,r,n,i)=>this.#e(H.HttpStatusCode.URI_TOO_LONG,e,r,n,i);static unsupportedMediaType=(e,r,n,i)=>this.#e(H.HttpStatusCode.UNSUPPORTED_MEDIA_TYPE,e,r,n,i);static rangeNotSatisfiable=(e,r,n,i)=>this.#e(H.HttpStatusCode.RANGE_NOT_SATISFIABLE,e,r,n,i);static expectationFailed=(e,r,n,i)=>this.#e(H.HttpStatusCode.EXPECTATION_FAILED,e,r,n,i);static imATeapot=(e,r,n,i)=>this.#e(H.HttpStatusCode.I_AM_A_TEAPOT,e,r,n,i);static misdirectedRequest=(e,r,n,i)=>this.#e(H.HttpStatusCode.MISDIRECTED_REQUEST,e,r,n,i);static unprocessableContent=(e,r,n,i)=>this.#e(H.HttpStatusCode.UNPROCESSABLE_CONTENT,e,r,n,i);static locked=(e,r,n,i)=>this.#e(H.HttpStatusCode.LOCKED,e,r,n,i);static failedDependency=(e,r,n,i)=>this.#e(H.HttpStatusCode.FAILED_DEPENDENCY,e,r,n,i);static tooEarly=(e,r,n,i)=>this.#e(H.HttpStatusCode.TOO_EARLY,e,r,n,i);static upgradeRequired=(e,r,n,i)=>this.#e(H.HttpStatusCode.UPGRADE_REQUIRED,e,r,n,i);static preconditionRequired=(e,r,n,i)=>this.#e(H.HttpStatusCode.PRECONDITION_REQUIRED,e,r,n,i);static tooManyRequests=(e,r,n,i)=>this.#e(H.HttpStatusCode.TOO_MANY_REQUESTS,e,r,n,i);static requestHeaderFieldsTooLarge=(e,r,n,i)=>this.#e(H.HttpStatusCode.REQUEST_HEADER_FIELDS_TOO_LARGE,e,r,n,i);static unavailableForLegalReasons=(e,r,n,i)=>this.#e(H.HttpStatusCode.UNAVAILABLE_FOR_LEGAL_REASONS,e,r,n,i);static internalServerError=(e,r,n,i)=>this.#e(H.HttpStatusCode.INTERNAL_SERVER_ERROR,e,r,n,i);static notImplemented=(e,r,n,i)=>this.#e(H.HttpStatusCode.NOT_IMPLEMENTED,e,r,n,i);static badGateway=(e,r,n,i)=>this.#e(H.HttpStatusCode.BAD_GATEWAY,e,r,n,i);static serviceUnavailable=(e,r,n,i)=>this.#e(H.HttpStatusCode.SERVICE_UNAVAILABLE,e,r,n,i);static gatewayTimeout=(e,r,n,i)=>this.#e(H.HttpStatusCode.GATEWAY_TIMEOUT,e,r,n,i);static httpVersionNotSupported=(e,r,n,i)=>this.#e(H.HttpStatusCode.HTTP_VERSION_NOT_SUPPORTED,e,r,n,i);static variantAlsoNegotiates=(e,r,n,i)=>this.#e(H.HttpStatusCode.VARIANT_ALSO_NEGOTIATES,e,r,n,i);static insufficientStorage=(e,r,n,i)=>this.#e(H.HttpStatusCode.INSUFFICIENT_STORAGE,e,r,n,i);static loopDetected=(e,r,n,i)=>this.#e(H.HttpStatusCode.LOOP_DETECTED,e,r,n,i);static notExtended=(e,r,n,i)=>this.#e(H.HttpStatusCode.NOT_EXTENDED,e,r,n,i);static networkAuthenticationRequired=(e,r,n,i)=>this.#e(H.HttpStatusCode.NETWORK_AUTHENTICATION_REQUIRED,e,r,n,i)};yn.HttpProblems=Nl});var at=_(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.isErrorLike=K.withUndefinedAsNull=K.withNullAsUndefined=K.validateConstraint=K.validateConstraints=K.areFunctions=K.isFunction=K.isEmptyObject=K.assertAllDefined=K.assertIsDefined=K.assertType=K.isUndefinedOrNull=K.isDefined=K.isUndefined=K.isBoolean=K.isIterable=K.isNumber=K.isTypedArray=K.isArray=K.isObject=K.getOwnEnumerableKeys=K.isRegexp=K.isStringArray=K.isNonEmptyString=K.isString=K.toString=void 0;var{toString:sS}=Object.prototype,{propertyIsEnumerable:aS}=Object.prototype;function Tm(t){return sS.call(t)}o(Tm,"toString");K.toString=Tm;function cs(t){return typeof t=="string"}o(cs,"isString");K.isString=cs;function cS(t){return cs(t)&&t!==""}o(cS,"isNonEmptyString");K.isNonEmptyString=cS;function uS(t){return Array.isArray(t)&&t.every(e=>cs(e))}o(uS,"isStringArray");K.isStringArray=uS;function lS(t){return Tm(t)==="[object RegExp]"}o(lS,"isRegexp");K.isRegexp=lS;function dS(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>aS.call(t,e))]}o(dS,"getOwnEnumerableKeys");K.getOwnEnumerableKeys=dS;function Cl(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof RegExp)&&!(t instanceof Date)}o(Cl,"isObject");K.isObject=Cl;function pS(t){return Cl(t)&&Array.isArray(t)}o(pS,"isArray");K.isArray=pS;function fS(t){let e=Object.getPrototypeOf(Uint8Array);return typeof t=="object"&&t instanceof e}o(fS,"isTypedArray");K.isTypedArray=fS;function hS(t){return typeof t=="number"&&!isNaN(t)}o(hS,"isNumber");K.isNumber=hS;function mS(t){return!!t&&typeof t[Symbol.iterator]=="function"}o(mS,"isIterable");K.isIterable=mS;function yS(t){return t===!0||t===!1}o(yS,"isBoolean");K.isBoolean=yS;function Sm(t){return typeof t>"u"}o(Sm,"isUndefined");K.isUndefined=Sm;function gS(t){return!Ni(t)}o(gS,"isDefined");K.isDefined=gS;function Ni(t){return Sm(t)||t===null}o(Ni,"isUndefinedOrNull");K.isUndefinedOrNull=Ni;function bS(t,e){if(!t)throw new Error(e?`Unexpected type, expected '${e}'`:"Unexpected type")}o(bS,"assertType");K.assertType=bS;function _S(t){if(Ni(t))throw new Error("Assertion Failed: argument is undefined or null");return t}o(_S,"assertIsDefined");K.assertIsDefined=_S;function ES(...t){let e=[];for(let r=0;r<t.length;r++){let n=t[r];if(Ni(n))throw new Error(`Assertion Failed: argument at index ${r} is undefined or null`);e.push(n)}return e}o(ES,"assertAllDefined");K.assertAllDefined=ES;var wS=Object.prototype.hasOwnProperty;function vS(t){if(!Cl(t))return!1;for(let e in t)if(wS.call(t,e))return!1;return!0}o(vS,"isEmptyObject");K.isEmptyObject=vS;function xl(t){return typeof t=="function"}o(xl,"isFunction");K.isFunction=xl;function TS(...t){return t.length>0&&t.every(xl)}o(TS,"areFunctions");K.areFunctions=TS;function SS(t,e){let r=Math.min(t.length,e.length);for(let n=0;n<r;n++)Im(t[n],e[n])}o(SS,"validateConstraints");K.validateConstraints=SS;function Im(t,e){if(cs(e)){if(typeof t!==e)throw new Error(`argument does not match constraint: typeof ${e}`)}else if(xl(e)){try{if(t instanceof e)return}catch{}if(!Ni(t)&&t.constructor===e||e.length===1&&e.call(void 0,t)===!0)return;throw new Error("argument does not match one of these constraints: arg instanceof constraint, arg.constructor === constraint, nor constraint(arg) === true")}}o(Im,"validateConstraint");K.validateConstraint=Im;function IS(t){return t===null?void 0:t}o(IS,"withNullAsUndefined");K.withNullAsUndefined=IS;function PS(t){return typeof t>"u"?null:t}o(PS,"withUndefinedAsNull");K.withUndefinedAsNull=PS;function AS(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}o(AS,"isErrorLike");K.isErrorLike=AS});var Jt=_(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.parseValueToBoolean=Nt.parseValueToStringArray=Nt.getValueFromRequestUser=Nt.statusCodesStringToNumberArray=void 0;var gn=k(),Ll=at(),Pm=new Map;function RS(t){if(Array.isArray(t)&&!t.some(i=>typeof i!="number"))return t;if(typeof t!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(t))throw new Error("Malformed input string");let e=Pm.get(t);if(e)return e;let r=t.split(","),n=[];for(let i of r){let s=i.split("-");if(s.length===2){let a=parseInt(s[0],10),c=parseInt(s[1],10);for(let u=a;u<=c;u++)n.push(u)}else n.push(parseInt(i,10))}return Pm.set(t,n),n}o(RS,"statusCodesStringToNumberArray");Nt.statusCodesStringToNumberArray=RS;function OS(t,e,r){if(!e.startsWith("."))throw new gn.ConfigurationError(`Invalid ${r} - must start with '.' - '${e}' does not`);let n=e.split(".").splice(1),i=t;return n.forEach(s=>{if(i===void 0)throw new gn.RuntimeError(`Error applying ${r} '${e}', reading '${s}'`);i=i[s]}),`${i}`}o(OS,"getValueFromRequestUser");Nt.getValueFromRequestUser=OS;function NS(t){if(Array.isArray(t)){if(t.includes(r=>typeof r!="string"))throw new gn.ConfigurationError("Received an array that contains non-string values.");return t}if((0,Ll.isString)(t))return t.includes(",")?t.split(",").map(r=>r.trim()).filter(r=>r!==","&&r!==""):[t];throw new gn.ConfigurationError(`Expected type of string, received type '${typeof t}'`)}o(NS,"parseValueToStringArray");Nt.parseValueToStringArray=NS;function CS(t){if((0,Ll.isBoolean)(t))return t;if((0,Ll.isString)(t)){if(t.toLowerCase()==="true")return!0;if(t.toLowerCase()==="false")return!1;throw new gn.ConfigurationError(`Attempted to parse string to boolean, but received ${t} which cannot be parsed.`)}throw new gn.ConfigurationError(`Expected type of boolean, received type '${typeof t}'`)}o(CS,"parseValueToBoolean");Nt.parseValueToBoolean=CS});var ls=_(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.generateCorsHeaders=ur.findMatchingOrigin=ur.parseCorsPolicies=void 0;var Br=k(),Am=Jt(),us=at();function xS(t){if(t==null)return[];if(!Array.isArray(t))throw new Br.ConfigurationError(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof t}'`);return t.map(r=>{if(!(0,us.isObject)(r))throw new Br.ConfigurationError(`Invalid custom cors policy is set. Expected an object, received '${typeof r}'`);if(!(0,us.isNonEmptyString)(r.name))throw new Br.ConfigurationError("Value of 'name' on custom cors policies must be a non-empty string.");if(r.maxAge!==void 0&&!(0,us.isNumber)(r.maxAge))throw new Br.ConfigurationError(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof r.maxAge}'`);if(r.allowCredentials!==void 0&&!(0,us.isBoolean)(r.allowCredentials))throw new Br.ConfigurationError("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=Dl(r,"allowedHeaders"),i=Dl(r,"allowedMethods"),s=Dl(r,"exposeHeaders"),a;try{a=(0,Am.parseValueToStringArray)(r.allowedOrigins)}catch(u){throw new Br.ConfigurationError(`Value of 'allowedOrigins' on custom cors policies is invalid. ${u.message} If using an environment variable, check that it is set correctly.`)}return{name:r.name,allowCredentials:typeof r.allowCredentials=="boolean"?String(r.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:n?n.join(", "):void 0,allowedMethods:i?i.join(", "):void 0,exposeHeaders:s?s.join(", "):void 0,maxAge:typeof r.maxAge=="number"?r.maxAge.toString():void 0}})}o(xS,"parseCorsPolicies");ur.parseCorsPolicies=xS;function Dl(t,e){let r;if(t[e]!==void 0)try{r=(0,Am.parseValueToStringArray)(t[e])}catch(n){throw new Br.ConfigurationError(`Value of '${e}' on custom cors policies is invalid. ${n.message} If using an environment variable, check that it is set correctly.`)}return r}o(Dl,"parseOptionalProperty");var LS=o((t,e)=>{if(e===null)return;if(t.find(a=>a==="*"))return e;let n=t.map(a=>a.trim().toLowerCase()),i=e.toLowerCase();return n.find(a=>a===i)},"findMatchingOrigin");ur.findMatchingOrigin=LS;var DS=o((t,e)=>{let r={"access-control-allow-origin":e};t.allowedHeaders&&(r["access-control-allow-headers"]=t.allowedHeaders),t.allowedMethods&&(r["access-control-allow-methods"]=t.allowedMethods),t.exposeHeaders&&(r["access-control-expose-headers"]=t.exposeHeaders);let n=t.allowCredentials;n&&(r["access-control-allow-credentials"]=n);let i=t.maxAge?.toString()??void 0;return i&&(r["access-control-max-age"]=i),r},"generateCorsHeaders");ur.generateCorsHeaders=DS});var Om=_(ds=>{"use strict";Object.defineProperty(ds,"__esModule",{value:!0});ds.registerCorsRoute=void 0;var MS=k(),US=Gt(),Ml=de(),kS=ar(),FS=Vr(),HS=gt(),Rm=ls(),qS=o((t,e)=>{let r=e.routeData.corsPolicies,n=o(async(a,c)=>{let u=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 Ml.HttpProblems.badRequest(a,c,{detail:"Expect headers origin and access-control-request-method"});let f=t.lookup(l,u);if(!f)return Ml.HttpProblems.notFound(a,c);let h=f.routeConfiguration,y=$S(l,d,p,h,r);return y.isValid?new Response(void 0,{status:200,statusText:"OK",headers:y.headers}):(y.error&&c.log.warn(y.error),Ml.HttpProblems.notFound(a,c))},"optionsHandler"),i=new US.Pipeline({processors:[kS.metricsProcessor],handler:n,gateway:e}),s=new HS.SystemRouteConfiguration({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:FS.SystemRouteName.CorsPreflight});t.addRoute(s,i.execute)},"registerCorsRoute");ds.registerCorsRoute=qS;var $S=o((t,e,r,n,i)=>{let s={isValid:!1,headers:{}};if(n.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":r,"access-control-allow-methods":t,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(n.corsPolicy==="none")return{...s,error:`No CORS policy set for the route '${n.pathPattern}'`};let a=i?.find(l=>l.name===n.corsPolicy);if(!a)throw new MS.ConfigurationError(`Invalid Configuration - corsPolicy '${n.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let c=(0,Rm.findMatchingOrigin)(a.allowedOrigins,r);return c?{isValid:!0,headers:(0,Rm.generateCorsHeaders)(a,c)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${r}'`}},"validateAndBuildResponseHeaders")});var Nm=_(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});ps.registerNoRoutes=void 0;var jS=Gt(),VS=ar(),BS=Vr(),GS=gt(),KS=o((t,e)=>{let r=o(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),n=new jS.Pipeline({processors:[VS.metricsProcessor],handler:r,gateway:e}),i=new GS.SystemRouteConfiguration({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:BS.SystemRouteName.EmptyGatewayCatchall});t.addRoute(i,n.execute)},"registerNoRoutes");ps.registerNoRoutes=KS});var Cm=_(Gr=>{"use strict";Object.defineProperty(Gr,"__esModule",{value:!0});Gr.registerNotMatchedHandler=Gr.notFoundRouteConfiguration=void 0;var JS=$r(),zS=Ot(),WS=Gt(),QS=de(),YS=ar(),ZS=Vr(),XS=gt();Gr.notFoundRouteConfiguration=new XS.SystemRouteConfiguration({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:ZS.SystemRouteName.UnmatchedPath});var eI=o((t,e)=>{let r=o(async(i,s)=>{let a=zS.runtimeExtensions.value?.notFoundHandler;if(a){let c=JS.ZuploContextExtensions.getContextExtensions(s);return a(i,s,{routesMatchedByPathOnly:c.pathOnlyMatches??[]})}return QS.HttpProblems.notFound(i,s)},"notFoundHandler"),n=new WS.Pipeline({processors:[YS.metricsProcessor],handler:r,gateway:e});t.addRoute(Gr.notFoundRouteConfiguration,n.execute)},"registerNotMatchedHandler");Gr.registerNotMatchedHandler=eI});var Ul=_(fs=>{"use strict";Object.defineProperty(fs,"__esModule",{value:!0});fs.corsProcessor=void 0;var Dm=k(),xm=ls(),tI=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Lm=o(t=>{tI.forEach(e=>t.delete(e))},"stripCorsHeaders"),rI=o(async(t,e,r,n)=>{let i=e.route;if(!i.corsPolicy||i.corsPolicy==="none"){let d=await n(t),p=new Headers(d.headers);return Lm(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await n(t);if(!(s instanceof Response))throw new Dm.SystemError(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=nI(i,r.routeData.corsPolicies),c=iI(t,a),u=new Headers(s.headers);return Lm(u),Object.entries(c).forEach(([d,p])=>{u.set(d,p)}),new Response(s.body,{status:s.status,statusText:s.statusText,headers:u,webSocket:s.webSocket})},"corsProcessor");fs.corsProcessor=rI;var nI=o((t,e)=>{if(t.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:t.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let r=e?.find(n=>n.name===t.corsPolicy);if(r===void 0)throw new Dm.ConfigurationError(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return r},"getCorsPolicy"),iI=o((t,e)=>{let r=(0,xm.findMatchingOrigin)(e.allowedOrigins,t.headers.get("origin"));return r?(0,xm.generateCorsHeaders)(e,r):{}},"getCorsHeaders")});var Mm=_(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});hs.registerPingRoute=void 0;var oI=Gt(),sI=Ul(),aI=Vr(),cI=gt(),uI=o((t,e)=>{let r=o(async()=>new Response(null,{status:200}),"pingRouteHandler"),n=new oI.Pipeline({processors:[sI.corsProcessor],handler:r,gateway:e}),i=new cI.SystemRouteConfiguration({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:aI.SystemRouteName.Ping});t.addRoute(i,n.execute)},"registerPingRoute");hs.registerPingRoute=uI});var _n=_(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.OutboundPolicy=bn.InboundPolicy=void 0;var lI=k(),dI=at(),ms=class{static{o(this,"PolicyBase")}options;policyName;constructor(e,r){if(!(0,dI.isString)(r))throw new lI.RuntimeError(`The name of a policy must be a string. Received '${r}' of type '${typeof r}'`);this.options=e,this.policyName=r}},kl=class extends ms{static{o(this,"InboundPolicy")}};bn.InboundPolicy=kl;var Fl=class extends ms{static{o(this,"OutboundPolicy")}};bn.OutboundPolicy=Fl});var En=_(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.createInternalPolicyProcessor=bt.policyProcessor=bt.toStackedInboundHandler=bt.getInboundPolicyInstances=void 0;var pI=$r(),$e=k(),ys=_n(),Um=Ke(),fI=ie(),$l=class extends ys.InboundPolicy{static{o(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,r,n){super(r,n),this.#e=e}handler(e,r){return this.#e(e,r,this.options,this.policyName)}},jl=class extends ys.OutboundPolicy{static{o(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,r,n){super(r,n),this.#e=e}handler(e,r,n){return this.#e(e,r,n,this.options,this.policyName)}},Hl=new Map;function km(t,e){let r,n;return Array.isArray(t)?r=t:(r=t.policies?.inbound??[],n=t.path),r.filter(s=>!Hl.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new $e.ConfigurationError(`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 $e.ConfigurationError(`Invalid state - invalid policy '${s}' on route '${n}' (typeof policy '${typeof a.handler?.module}')`);let c=a.handler?.module[a.handler.export];if(typeof c!="function")throw new $e.ConfigurationError(`Invalid state - invalid policy '${s}' on route '${n}' (typeof module '${typeof c}')`);let u;if(typeof c!="function")throw new $e.ConfigurationError(`Invalid state - invalid policy '${s}' on route '${n}' (typeof module '${typeof c}')`);if(c.prototype instanceof ys.InboundPolicy)u=new c(a.handler.options,a.name);else if(typeof c=="function")u=new $l(c,a.handler.options,a.name);else throw new $e.ConfigurationError(`Invalid state - invalid policy '${s}' on route '${n}' (typeof policy '${typeof c}')`);if(typeof u.handler!="function")throw new $e.ConfigurationError(`Invalid state - invalid handler on policy '${s}' on route '${n}' (typeof handler '${typeof u.handler}')`);Hl.set(a.name,u)}),r.map(s=>{let a=Hl.get(s);if(a===void 0)throw new $e.RuntimeError("Internal error. Policy not found in cache.");return a})}o(km,"getInboundPolicyInstances");bt.getInboundPolicyInstances=km;var ql=new Map;function hI(t,e){let r=t.policies?.outbound??[];return r.filter(i=>!ql.has(i)).forEach(i=>{let s=e?.find(u=>u.name===i);if(!s)throw new $e.ConfigurationError(`Invalid state - no Policy with the name '${i}' on route '${t.path}' was found in the policies configuration (check case).`);if(typeof s.handler?.module!="object")throw new $e.ConfigurationError(`Invalid state - invalid policy '${i}' on route '${t.path}' (typeof policy '${typeof s.handler?.module}')`);let a=s.handler?.module[s.handler.export],c;if(typeof a!="function")throw new $e.ConfigurationError(`Invalid state - invalid policy '${i}' on route '${t.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof ys.OutboundPolicy)c=new a(s.handler.options??{},s.name);else if(typeof a=="function")c=new jl(a,s.handler.options??{},s.name);else throw new $e.ConfigurationError(`Invalid state - invalid policy '${i}' on route '${t.path}' (typeof policy '${typeof a}')`);if(typeof c.handler!="function")throw new $e.ConfigurationError(`Invalid state - invalid handler on policy '${i}' on route '${t.path}'`);ql.set(s.name,c)}),r.map(i=>{let s=ql.get(i);if(s===void 0)throw new $e.RuntimeError("Internal error. Policy not found in cache.");return s})}o(hI,"getOutboundPolicyInstances");var mI=o(t=>async(e,r)=>{let n=pI.ZuploContextExtensions.getContextExtensions(r),i=[...t],s=e;for(;i.length>0;){let a=i.shift();if(!a)return s;let c=await a.handler(s,r);if(c instanceof Um.ZuploRequest)s=c;else if(c instanceof Request)s=new Um.ZuploRequest(c);else{if(c instanceof Response)return c;throw new $e.ConfigurationError(`Invalid state - invalid handler on policy '${a.policyName}' on route '${r.route.path}. The result of an inbound policy must be a Response or Request.`)}n.latestRequest=s}return s},"toStackedInboundHandler");bt.toStackedInboundHandler=mI;var yI=o(t=>async(e,r,n)=>{let i=[...t],s=e;for(;i.length>0;){let a=i.shift();if(!a)return s;let c=await a.handler(s,r,n);if(!(c instanceof Response))throw new $e.ConfigurationError(`Invalid state - invalid handler on policy '${a.policyName}' on route '${n.route.path}. The result of an outbound policy must be a Response.`);s=c}return s},"toStackedOutboundHandler"),gI=o(async(t,e,r,n)=>{let i=km(e.route,r.routeData.policies),s=hI(e.route,r.routeData.policies);return Fm({request:t,context:e,inboundPolicies:i,outboundPolicies:s,gateway:r,next:n})},"policyProcessor");bt.policyProcessor=gI;function bI({inboundPolicies:t=[],outboundPolicies:e=[]}){return o(async(n,i,s,a)=>Fm({request:n,context:i,inboundPolicies:t,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}o(bI,"createInternalPolicyProcessor");bt.createInternalPolicyProcessor=bI;async function Fm({request:t,context:e,inboundPolicies:r,outboundPolicies:n,gateway:i,next:s}){let a=(0,bt.toStackedInboundHandler)(r);try{let c=await a(t,e);if(c instanceof Response)return c;let u=await s(c),l=yI(n),d;return fI.Environment.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(u,t,e):d=u.ok?l(u,t,e):u,d}catch(c){return e.log.error(c),i.errorHandler(t,e,c)}}o(Fm,"executePolicyProcessor")});var Hm=_(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.serialize=wn.parse=void 0;var _I=Object.prototype.toString,gs=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function EI(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");let r={},i=(e||{}).decode||vI,s=0;for(;s<t.length;){let a=t.indexOf("=",s);if(a===-1)break;let c=t.indexOf(";",s);if(c===-1)c=t.length;else if(c<a){s=t.lastIndexOf(";",a-1)+1;continue}let u=t.slice(s,a).trim();if(r[u]===void 0){let l=t.slice(a+1,c).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),r[u]=II(l,i)}s=c+1}return r}o(EI,"parse");wn.parse=EI;function wI(t,e,r){let n=r||{},i=n.encode||TI;if(typeof i!="function")throw new TypeError("option encode is invalid");if(!gs.test(t))throw new TypeError("argument name is invalid");let s=i(e);if(s&&!gs.test(s))throw new TypeError("argument val is invalid");let a=t+"="+s;if(n.maxAge!=null){let c=n.maxAge-0;if(isNaN(c)||!isFinite(c))throw new TypeError("option maxAge is invalid");a+="; Max-Age="+Math.floor(c)}if(n.domain){if(!gs.test(n.domain))throw new TypeError("option domain is invalid");a+="; Domain="+n.domain}if(n.path){if(!gs.test(n.path))throw new TypeError("option path is invalid");a+="; Path="+n.path}if(n.expires){let c=n.expires;if(!SI(c)||isNaN(c.valueOf()))throw new TypeError("option expires is invalid");a+="; Expires="+c.toUTCString()}if(n.httpOnly&&(a+="; HttpOnly"),n.secure&&(a+="; Secure"),n.priority)switch(typeof n.priority=="string"?n.priority.toLowerCase():n.priority){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}if(n.sameSite)switch(typeof n.sameSite=="string"?n.sameSite.toLowerCase():n.sameSite){case!0:a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"strict":a+="; SameSite=Strict";break;case"none":a+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return a}o(wI,"serialize");wn.serialize=wI;function vI(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}o(vI,"decode");function TI(t){return encodeURIComponent(t)}o(TI,"encode");function SI(t){return _I.call(t)==="[object Date]"||t instanceof Date}o(SI,"isDate");function II(t,e){try{return e(t)}catch{return t}}o(II,"tryDecode")});var qm=_(bs=>{"use strict";Object.defineProperty(bs,"__esModule",{value:!0});bs.devPortalBaseURL=void 0;var PI=Hm();function AI(t,e){try{let r=/v\d+(-\d+)?/g,i=(0,PI.parse)(e.get("Cookie")||"")["zp-dev-portal"];return i!==null&&i&&r.test(i)?`https://dev-portal-${i}.zuplo.com`:t}catch{}return t}o(AI,"devPortalBaseURL");bs.devPortalBaseURL=AI});var Gm=_(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.registerDevPortalLegacyRedirectRoute=vn.registerDevPortalV3Route=void 0;var Vl=Kt(),jm=Gt(),Vm=ar(),RI=En(),Bm=gt(),OI=qm(),lr=ie(),$m="/__zuplo/dev-portal",NI="dev-portal-id",CI="dev-portal-host",xI="zp-account",LI="zp-project",DI="dev-portal-build",MI=`
35
+ `)+" "+r[1]:r[0]+e+" "+t.join(", ")+" "+r[1]}o(fT,"reduceToSingleString")});var nm=_($o=>{"use strict";Object.defineProperty($o,"__esModule",{value:!0});$o.format=void 0;var hT=Qh(),mT=rm(),yT=o((t,...e)=>(0,hT.format)(mT.inspect,t,e),"format");$o.format=yT});var or=_(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});ir.debug=ir.withoutEnv=ir.Debugger=void 0;var gT=Wh(),bT=nm(),jo=class{static{o(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,r){this.manager=e,this.ns=r,this.color=(0,gT.generateColor)(r),this.last=0,this.enabled=e.enabled.some(n=>n.test(r))}log(...e){if(!this.enabled)return;let r,n=e[0];typeof n=="function"?r=n():r=String(n);let i=Date.now()-(this.last||Date.now());r=(0,bT.format)(r,...e);let s=`${this.color(this.ns)} ${r} ${this.color(`+${i}ms`)}`;console.log(s),this.last=Date.now()}};ir.Debugger=jo;var Vo=class{static{o(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function im(t){return!t||t.length===0?[]:(t=t.replace(/\s/g,"").replace(/\*/g,".+"),t.split(",").map(e=>new RegExp(`^${e}$`)))}o(im,"extract");var Oi;function _T(t){t||(t=[]),typeof t=="string"&&(t=im(t)),Oi=new Vo(t)}o(_T,"withoutEnv");ir.withoutEnv=_T;function ET(t){let e=globalThis.DEBUG;Oi||(Oi=new Vo(im(e)));let r=new jo(Oi,t);return Oi.debuggers.set(t,r),Object.assign(r.log.bind(r),{self:r})}o(ET,"debug");ir.debug=ET});var Go=_(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.ProblemResponseFormatter=hn.InternalProblemResponseFormatter=void 0;var wT=k(),Bo=class t{static{o(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let r=e.problem,n=JSON.stringify(r,null,2);return new Response(n,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(t.problemResponseFormat=(r,n,i)=>{try{return e(r,n,i)}catch(s){throw new wT.RuntimeError("Error in custom 'problemResponseFormat'",{cause:s})}})}};hn.InternalProblemResponseFormatter=Bo;var pl=class{static{o(this,"ProblemResponseFormatter")}static async format(e,r,n){return await Bo.problemResponseFormat(e,r,n)}};hn.ProblemResponseFormatter=pl});var sm=_(Ko=>{"use strict";Object.defineProperty(Ko,"__esModule",{value:!0});Ko.deepFreeze=void 0;function om(t){for(let e in t){let r=t[e];r&&typeof r=="object"&&om(r)}return Object.freeze(t)}o(om,"deepFreeze");Ko.deepFreeze=om});var Ke=_(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});Jo.ZuploRequest=void 0;var am=sm(),fl=class t extends Request{static{o(this,"ZuploRequest")}#e=void 0;#t;constructor(e,r){super(e,r);let n=r?.params;n?this.#t=n:e instanceof t?this.#t=e.#t:this.#t={};let i=r?.user;i?this.user=i:e instanceof t&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},r=new URL(this.url).searchParams;for(let[n,i]of r.entries())e[n]=i;this.#e=e}return(0,am.deepFreeze)(this.#e)}get params(){return(0,am.deepFreeze)(this.#t)}user};Jo.ZuploRequest=fl});var Ot=_(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.initializeRuntime=Ie.invokeOnResponseSendingFinalExtensions=Ie.invokeOnResponseSendingExtensions=Ie.invokeOnRequestExtensions=Ie.plugins=Ie.runtimeExtensions=Ie.SystemRuntimePlugin=Ie.RuntimePlugin=void 0;var cm=k(),vT=Go(),TT=Ke(),Wo=class{static{o(this,"RuntimePlugin")}};Ie.RuntimePlugin=Wo;var Qo=class extends Wo{static{o(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,r){}};Ie.SystemRuntimePlugin=Qo;Ie.runtimeExtensions={};var hl=[];Ie.plugins=hl;var um=[],lm=[],dm=[],zo={addPlugin(t){hl.push(t)},addRequestHook(t){um.push(t)},addResponseSendingHook(t){lm.push(t)},addResponseSendingFinalHook(t){dm.push(t)}},ST=o(async(t,e)=>{let r=t;for(let n of um){let i=await n(r,e);if(i instanceof TT.ZuploRequest)r=i;else{if(i instanceof Response)return i;throw new cm.ConfigurationError(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof r}.`)}}return r},"invokeOnRequestExtensions");Ie.invokeOnRequestExtensions=ST;var IT=o(async(t,e,r)=>{let n=t;for(let i of lm){let s=await i(t,e,r);if(s instanceof Response)n=s;else throw new cm.ConfigurationError(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof n}.`)}return n},"invokeOnResponseSendingExtensions");Ie.invokeOnResponseSendingExtensions=IT;var PT=o(async(t,e,r)=>{for(let n of dm)await n(t,e,r)},"invokeOnResponseSendingFinalExtensions");Ie.invokeOnResponseSendingFinalExtensions=PT;async function AT(t=()=>Promise.resolve()){await t(zo),Ie.runtimeExtensions.value=zo;for(let e of hl)e instanceof Qo&&await e.initialize(zo);vT.InternalProblemResponseFormatter.setProblemResponseFormat(zo.problemResponseFormat)}o(AT,"initializeRuntime");Ie.initializeRuntime=AT});var ml=_(sr=>{"use strict";Object.defineProperty(sr,"__esModule",{value:!0});sr.serialize=sr.ContentTypes=void 0;sr.ContentTypes={Json:"application/json",Form:"application/x-www-form-urlencoded"};function RT(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(sr.ContentTypes.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(sr.ContentTypes.Json)||!e?JSON.stringify(t):t}o(RT,"serialize");sr.serialize=RT});var yl=_(Yo=>{"use strict";Object.defineProperty(Yo,"__esModule",{value:!0});Yo.isSystemRoute=void 0;var pm=qr();function OT(t){return pm.Gateway.instance.runtimeSettings.developerPortal.enabled&&t.pathname.startsWith(pm.Gateway.instance.runtimeSettings.developerPortal.sitePathname)||t.pathname.startsWith("/__zuplo/")||t.pathname.startsWith("/__/zuplo/")}o(OT,"isSystemRoute");Yo.isSystemRoute=OT});var Gt=_(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});Zo.Pipeline=void 0;var gl=$r(),fm=Ot(),NT=ml(),CT=ie(),xT=yl(),bl=class{static{o(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,r)=>async(n,i)=>{try{return await e(n,i)}catch(s){return i.log.error("Error executing request handler.",s),r.errorHandler(n,i,s)}};#t=({processors:e,gateway:r,handler:n})=>async(i,s)=>{let a=[...e],c=o(async b=>{let I=a.pop();return I?I(i,s,r,c):await this.#e(async g=>{let v=await n(g,s);return LT(v)},r)(b,s)},"nextPipe"),l=await c(i),d=new URL(i.url);if((0,xT.isSystemRoute)(d)&&CT.Environment.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new gl.ResponseSendingEvent(i,l);s.dispatchEvent(p);let f=gl.ZuploContextExtensions.getContextExtensions(s),h=f.latestRequest,y;try{y=await p.mutableResponse}catch(b){return s.log.error(b),r.errorHandler(i,s,b)}try{y=await f.onResponseSending(y,h,s)}catch(b){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),r.errorHandler(i,s,b)}try{y=await(0,fm.invokeOnResponseSendingExtensions)(y,h,s)}catch(b){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),r.errorHandler(i,s,b)}s.dispatchEvent(new gl.ResponseSentEvent(i,y));try{await f.onResponseSendingFinal(l,h,s)}catch(b){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}try{await(0,fm.invokeOnResponseSendingFinalExtensions)(l,h,s)}catch(b){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}return y}};Zo.Pipeline=bl;function LT(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response((0,NT.serialize)(t),{headers:{"content-type":"application/json"}})}o(LT,"resultToResponse")});var es=_(Xo=>{"use strict";Object.defineProperty(Xo,"__esModule",{value:!0});Xo.MetricsPlugin=void 0;var DT=Ot(),_l=class extends DT.RuntimePlugin{static{o(this,"MetricsPlugin")}};Xo.MetricsPlugin=_l});var Je=_(ts=>{"use strict";Object.defineProperty(ts,"__esModule",{value:!0});ts.SystemLogMap=void 0;var MT=k(),El=class t{static{o(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let r=t.#e.get(e);if(!r){let n=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(n),new MT.SystemError(n)}return r}static addLogger(e,r){t.#e.set(e,r)}};ts.SystemLogMap=El});var Re=_(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});rs.BatchDispatch=void 0;var wl=class{static{o(this,"BatchDispatch")}constructor(e,r,n,i){this.#t=e,this.#o=r,this.#n=n,this.#r=i??console}#e=void 0;#t;#r;#n;#i=[];#o;enqueue=e=>{this.#i.push(e),this.#e||(this.#e=new Promise(r=>{setTimeout(()=>{if(this.#i.length>0){let n=[...this.#i];this.#i.length=0,this.#e=void 0,this.#n(n).catch(i=>{this.#r.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,i.message,i.stack)}).finally(()=>{r()})}},this.#o)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};rs.BatchDispatch=wl});var mm=_(is=>{"use strict";Object.defineProperty(is,"__esModule",{value:!0});is.EllieMetricsTransport=void 0;var hm=Je(),UT=Re(),ns=ie(),vl=class{static{o(this,"EllieMetricsTransport")}#e;#t;#r;constructor(e){this.#r=ns.Environment.instance.loggingId,this.#e=e,this.#t=new UT.BatchDispatch("ellie-metrics-transport",10,this.dispatchFunction,hm.SystemLogMap.getLogger(e))}pushMetrics(e,r){this.#r!==void 0&&(this.#t.enqueue(e),r.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let r,{loggingId:n,remoteLogURL:i,deploymentName:s}=ns.Environment.instance,a=e.map(c=>{let u=Object.assign({},c);return delete u.requestContentLength,delete u.responseContentLength,u});if(n&&s&&(r=`${i}/v1-alpha/metrics?loggingId=${encodeURI(n)}&deploymentName=${encodeURI(s)}`),r){let c=await fetch(r,{method:"POST",body:JSON.stringify(a),headers:{"content-type":"application/json","zp-dn":ns.Environment.instance.deploymentName??"unknown","user-agent":ns.Environment.instance.systemUserAgent}});if(!c.ok){let u=await c.text();hm.SystemLogMap.getLogger(this.#e).error(`Metrics POST responded ${c.status}: ${c.statusText}`,u)}}}};is.EllieMetricsTransport=vl});var gt=_(jr=>{"use strict";Object.defineProperty(jr,"__esModule",{value:!0});jr.systemNoVersion=jr.SystemRouteConfiguration=void 0;var Tl=class{static{o(this,"SystemRouteConfiguration")}constructor({label:e,path:r,methods:n,systemRouteName:i,corsPolicy:s="none"}){this.label=e,this.path=r,this.methods=n,this.corsPolicy=s,this.version=jr.systemNoVersion.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=i}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}};jr.SystemRouteConfiguration=Tl;jr.systemNoVersion={name:"__system-no-version",pathPrefix:""}});var ar=_(os=>{"use strict";Object.defineProperty(os,"__esModule",{value:!0});os.metricsProcessor=void 0;var ym=Fr(),kT=$r(),FT=Ot(),HT=es(),qT=mm(),$T=gt(),jT=o(async(t,e,r,n)=>{let i=new Date,s=Date.now(),a=await n(t),c=t.headers.get(ym.RAY_ID_HEADER)??void 0,u=t.headers.get(ym.TRUE_CLIENT_IP)??void 0,l=e.incomingRequestProperties,d;e.route instanceof $T.SystemRouteConfiguration&&(d=e.route.systemRouteName);let p=kT.ZuploContextExtensions.getContextExtensions(e).latestRequest,f={timestamp:i,statusCode:a.status,durationMs:Date.now()-s,requestContentLength:t.headers.get("content-length")?Number(t.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:t.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:c,instanceId:r.instanceId,userSub:p.user?.sub,clientIp:u},h=[];return h.push(new qT.EllieMetricsTransport(e)),FT.plugins.forEach(y=>{if(y instanceof HT.MetricsPlugin){let b=y.getTransport();h.push(b)}}),h.forEach(y=>{y.pushMetrics(f,e)}),a},"metricsProcessor");os.metricsProcessor=jT});var Sl=_(ss=>{"use strict";Object.defineProperty(ss,"__esModule",{value:!0});ss.SystemRouteName=void 0;var gm;(function(t){t.Build="build-data",t.CorsPreflight="cors-preflight",t.DeveloperPortal="developer-portal",t.DeveloperPortalLegacy="developer-portal-legacy",t.StripePlugin="stripe-plugin",t.EmptyGatewayCatchall="empty-gateway-catchall",t.Ping="ping",t.UnmatchedPath="unmatched-path"})(gm||(ss.SystemRouteName=gm={}))});var _m=_(bm=>{"use strict";Object.defineProperty(bm,"__esModule",{value:!0})});var Vr=_(cr=>{"use strict";var VT=cr&&cr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Em=cr&&cr.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&VT(e,t,r)};Object.defineProperty(cr,"__esModule",{value:!0});Em(Sl(),cr);Em(_m(),cr)});var wm=_(as=>{"use strict";Object.defineProperty(as,"__esModule",{value:!0});as.registerBuildRoute=void 0;var BT=Kt(),GT=Gt(),KT=ar(),JT=Vr(),zT=gt(),WT=Je(),QT=ie(),YT=o((t,e)=>{let r=o(async(s,a)=>{let u=new URL(s.url).hostname.toLowerCase();if(!u.endsWith(".zuplo.app")&&!u.endsWith(".zuplo.dev")&&!u.endsWith(".fly.dev")&&!u.endsWith("zuplotest.com")&&u!=="localhost")return BT.HttpProblems.notFound(s,a);let l=QT.Environment.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.IS_PRODUCTION},p=s.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&WT.SystemLogMap.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),n=new GT.Pipeline({processors:[KT.metricsProcessor],handler:r,gateway:e}),i=new zT.SystemRouteConfiguration({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:JT.SystemRouteName.Build});t.addRoute(i,n.execute)},"registerBuildRoute");as.registerBuildRoute=YT});var Il=_(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.HTTP_STATUS_TITLES=mn.HttpStatusCode=void 0;var vm;(function(t){t[t.CONTINUE=100]="CONTINUE",t[t.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",t[t.PROCESSING=102]="PROCESSING",t[t.EARLY_HINTS=103]="EARLY_HINTS",t[t.OK=200]="OK",t[t.CREATED=201]="CREATED",t[t.ACCEPTED=202]="ACCEPTED",t[t.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",t[t.NO_CONTENT=204]="NO_CONTENT",t[t.RESET_CONTENT=205]="RESET_CONTENT",t[t.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",t[t.MULTI_STATUS=207]="MULTI_STATUS",t[t.ALREADY_REPORTED=208]="ALREADY_REPORTED",t[t.IM_USED=226]="IM_USED",t[t.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",t[t.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",t[t.FOUND=302]="FOUND",t[t.SEE_OTHER=303]="SEE_OTHER",t[t.NOT_MODIFIED=304]="NOT_MODIFIED",t[t.USE_PROXY=305]="USE_PROXY",t[t.SWITCH_PROXY=306]="SWITCH_PROXY",t[t.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",t[t.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",t[t.BAD_REQUEST=400]="BAD_REQUEST",t[t.UNAUTHORIZED=401]="UNAUTHORIZED",t[t.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",t[t.FORBIDDEN=403]="FORBIDDEN",t[t.NOT_FOUND=404]="NOT_FOUND",t[t.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",t[t.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",t[t.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",t[t.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",t[t.CONFLICT=409]="CONFLICT",t[t.GONE=410]="GONE",t[t.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",t[t.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",t[t.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",t[t.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",t[t.URI_TOO_LONG=414]="URI_TOO_LONG",t[t.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",t[t.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",t[t.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",t[t.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",t[t.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",t[t.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",t[t.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",t[t.LOCKED=423]="LOCKED",t[t.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",t[t.TOO_EARLY=425]="TOO_EARLY",t[t.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",t[t.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",t[t.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",t[t.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",t[t.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",t[t.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",t[t.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",t[t.BAD_GATEWAY=502]="BAD_GATEWAY",t[t.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",t[t.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",t[t.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",t[t.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",t[t.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",t[t.LOOP_DETECTED=508]="LOOP_DETECTED",t[t.NOT_EXTENDED=510]="NOT_EXTENDED",t[t.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED"})(vm||(mn.HttpStatusCode=vm={}));mn.HTTP_STATUS_TITLES={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 Al=_(Pl=>{"use strict";Object.defineProperty(Pl,"__esModule",{value:!0});var ZT={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"};Pl.default=ZT});var de=_(yn=>{"use strict";var XT=yn&&yn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(yn,"__esModule",{value:!0});yn.HttpProblems=void 0;var eS=Fr(),H=Il(),tS=XT(Al()),rS=ie(),Rl=Go();function nS(t){return`${new URL(t.url).pathname}`}o(nS,"instance");function iS(t,e){let r={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:rS.Environment.instance.build.BUILD_ID},n=t.headers.get(eS.RAY_ID_HEADER);return n&&(r.rayId=n),r}o(iS,"trace");var oS=o((t,e,r,n,i)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:nS(e),trace:iS(e,r),...n},additionalHeaders:i,statusText:tS.default[t.status]}),"merge"),Ol=class{static{o(this,"HttpProblemsBase")}static format=(e,r,n)=>"problem"in e?Rl.ProblemResponseFormatter.format(e,r,n):Rl.ProblemResponseFormatter.format({problem:e},r,n);static getProblemFromStatus(e,r){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:H.HTTP_STATUS_TITLES[e],...r}}},Nl=class extends Ol{static{o(this,"HttpProblems")}static#e(e,r,n,i,s){let a=oS(this.getProblemFromStatus(e),r,n,i,s);return Rl.ProblemResponseFormatter.format(a,r,n)}static continue=(e,r,n,i)=>this.#e(H.HttpStatusCode.OK,e,r,n,i);static switchingProtocols=(e,r,n,i)=>this.#e(H.HttpStatusCode.SWITCHING_PROTOCOLS,e,r,n,i);static processing=(e,r,n,i)=>this.#e(H.HttpStatusCode.PROCESSING,e,r,n,i);static earlyHints=(e,r,n,i)=>this.#e(H.HttpStatusCode.EARLY_HINTS,e,r,n,i);static ok=(e,r,n,i)=>this.#e(H.HttpStatusCode.OK,e,r,n,i);static created=(e,r,n,i)=>this.#e(H.HttpStatusCode.CREATED,e,r,n,i);static accepted=(e,r,n,i)=>this.#e(H.HttpStatusCode.ACCEPTED,e,r,n,i);static nonAuthoritativeInformation=(e,r,n,i)=>this.#e(H.HttpStatusCode.NON_AUTHORITATIVE_INFORMATION,e,r,n,i);static noContent=(e,r,n,i)=>this.#e(H.HttpStatusCode.NO_CONTENT,e,r,n,i);static resetContent=(e,r,n,i)=>this.#e(H.HttpStatusCode.RESET_CONTENT,e,r,n,i);static partialContent=(e,r,n,i)=>this.#e(H.HttpStatusCode.PARTIAL_CONTENT,e,r,n,i);static multiStatus=(e,r,n,i)=>this.#e(H.HttpStatusCode.MULTI_STATUS,e,r,n,i);static alreadyReported=(e,r,n,i)=>this.#e(H.HttpStatusCode.ALREADY_REPORTED,e,r,n,i);static imUsed=(e,r,n,i)=>this.#e(H.HttpStatusCode.IM_USED,e,r,n,i);static multipleChoices=(e,r,n,i)=>this.#e(H.HttpStatusCode.MULTIPLE_CHOICES,e,r,n,i);static movedPermanently=(e,r,n,i)=>this.#e(H.HttpStatusCode.MOVED_PERMANENTLY,e,r,n,i);static found=(e,r,n,i)=>this.#e(H.HttpStatusCode.FOUND,e,r,n,i);static seeOther=(e,r,n,i)=>this.#e(H.HttpStatusCode.SEE_OTHER,e,r,n,i);static notModified=(e,r,n,i)=>this.#e(H.HttpStatusCode.NOT_MODIFIED,e,r,n,i);static useProxy=(e,r,n,i)=>this.#e(H.HttpStatusCode.USE_PROXY,e,r,n,i);static switchProxy=(e,r,n,i)=>this.#e(H.HttpStatusCode.SWITCH_PROXY,e,r,n,i);static temporaryRedirect=(e,r,n,i)=>this.#e(H.HttpStatusCode.TEMPORARY_REDIRECT,e,r,n,i);static permanentRedirect=(e,r,n,i)=>this.#e(H.HttpStatusCode.PERMANENT_REDIRECT,e,r,n,i);static badRequest=(e,r,n,i)=>this.#e(H.HttpStatusCode.BAD_REQUEST,e,r,n,i);static unauthorized=(e,r,n,i)=>this.#e(H.HttpStatusCode.UNAUTHORIZED,e,r,n,i);static paymentRequired=(e,r,n,i)=>this.#e(H.HttpStatusCode.PAYMENT_REQUIRED,e,r,n,i);static forbidden=(e,r,n,i)=>this.#e(H.HttpStatusCode.FORBIDDEN,e,r,n,i);static notFound=(e,r,n,i)=>this.#e(H.HttpStatusCode.NOT_FOUND,e,r,n,i);static methodNotAllowed=(e,r,n,i)=>this.#e(H.HttpStatusCode.METHOD_NOT_ALLOWED,e,r,n,i);static notAcceptable=(e,r,n,i)=>this.#e(H.HttpStatusCode.NOT_ACCEPTABLE,e,r,n,i);static proxyAuthenticationRequired=(e,r,n,i)=>this.#e(H.HttpStatusCode.PROXY_AUTHENTICATION_REQUIRED,e,r,n,i);static requestTimeout=(e,r,n,i)=>this.#e(H.HttpStatusCode.REQUEST_TIMEOUT,e,r,n,i);static conflict=(e,r,n,i)=>this.#e(H.HttpStatusCode.CONFLICT,e,r,n,i);static gone=(e,r,n,i)=>this.#e(H.HttpStatusCode.GONE,e,r,n,i);static lengthRequired=(e,r,n,i)=>this.#e(H.HttpStatusCode.LENGTH_REQUIRED,e,r,n,i);static preconditionFailed=(e,r,n,i)=>this.#e(H.HttpStatusCode.PRECONDITION_FAILED,e,r,n,i);static contentTooLarge=(e,r,n,i)=>this.#e(H.HttpStatusCode.CONTENT_TOO_LARGE,e,r,n,i);static uriTooLong=(e,r,n,i)=>this.#e(H.HttpStatusCode.URI_TOO_LONG,e,r,n,i);static unsupportedMediaType=(e,r,n,i)=>this.#e(H.HttpStatusCode.UNSUPPORTED_MEDIA_TYPE,e,r,n,i);static rangeNotSatisfiable=(e,r,n,i)=>this.#e(H.HttpStatusCode.RANGE_NOT_SATISFIABLE,e,r,n,i);static expectationFailed=(e,r,n,i)=>this.#e(H.HttpStatusCode.EXPECTATION_FAILED,e,r,n,i);static imATeapot=(e,r,n,i)=>this.#e(H.HttpStatusCode.I_AM_A_TEAPOT,e,r,n,i);static misdirectedRequest=(e,r,n,i)=>this.#e(H.HttpStatusCode.MISDIRECTED_REQUEST,e,r,n,i);static unprocessableContent=(e,r,n,i)=>this.#e(H.HttpStatusCode.UNPROCESSABLE_CONTENT,e,r,n,i);static locked=(e,r,n,i)=>this.#e(H.HttpStatusCode.LOCKED,e,r,n,i);static failedDependency=(e,r,n,i)=>this.#e(H.HttpStatusCode.FAILED_DEPENDENCY,e,r,n,i);static tooEarly=(e,r,n,i)=>this.#e(H.HttpStatusCode.TOO_EARLY,e,r,n,i);static upgradeRequired=(e,r,n,i)=>this.#e(H.HttpStatusCode.UPGRADE_REQUIRED,e,r,n,i);static preconditionRequired=(e,r,n,i)=>this.#e(H.HttpStatusCode.PRECONDITION_REQUIRED,e,r,n,i);static tooManyRequests=(e,r,n,i)=>this.#e(H.HttpStatusCode.TOO_MANY_REQUESTS,e,r,n,i);static requestHeaderFieldsTooLarge=(e,r,n,i)=>this.#e(H.HttpStatusCode.REQUEST_HEADER_FIELDS_TOO_LARGE,e,r,n,i);static unavailableForLegalReasons=(e,r,n,i)=>this.#e(H.HttpStatusCode.UNAVAILABLE_FOR_LEGAL_REASONS,e,r,n,i);static internalServerError=(e,r,n,i)=>this.#e(H.HttpStatusCode.INTERNAL_SERVER_ERROR,e,r,n,i);static notImplemented=(e,r,n,i)=>this.#e(H.HttpStatusCode.NOT_IMPLEMENTED,e,r,n,i);static badGateway=(e,r,n,i)=>this.#e(H.HttpStatusCode.BAD_GATEWAY,e,r,n,i);static serviceUnavailable=(e,r,n,i)=>this.#e(H.HttpStatusCode.SERVICE_UNAVAILABLE,e,r,n,i);static gatewayTimeout=(e,r,n,i)=>this.#e(H.HttpStatusCode.GATEWAY_TIMEOUT,e,r,n,i);static httpVersionNotSupported=(e,r,n,i)=>this.#e(H.HttpStatusCode.HTTP_VERSION_NOT_SUPPORTED,e,r,n,i);static variantAlsoNegotiates=(e,r,n,i)=>this.#e(H.HttpStatusCode.VARIANT_ALSO_NEGOTIATES,e,r,n,i);static insufficientStorage=(e,r,n,i)=>this.#e(H.HttpStatusCode.INSUFFICIENT_STORAGE,e,r,n,i);static loopDetected=(e,r,n,i)=>this.#e(H.HttpStatusCode.LOOP_DETECTED,e,r,n,i);static notExtended=(e,r,n,i)=>this.#e(H.HttpStatusCode.NOT_EXTENDED,e,r,n,i);static networkAuthenticationRequired=(e,r,n,i)=>this.#e(H.HttpStatusCode.NETWORK_AUTHENTICATION_REQUIRED,e,r,n,i)};yn.HttpProblems=Nl});var at=_(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.isErrorLike=K.withUndefinedAsNull=K.withNullAsUndefined=K.validateConstraint=K.validateConstraints=K.areFunctions=K.isFunction=K.isEmptyObject=K.assertAllDefined=K.assertIsDefined=K.assertType=K.isUndefinedOrNull=K.isDefined=K.isUndefined=K.isBoolean=K.isIterable=K.isNumber=K.isTypedArray=K.isArray=K.isObject=K.getOwnEnumerableKeys=K.isRegexp=K.isStringArray=K.isNonEmptyString=K.isString=K.toString=void 0;var{toString:sS}=Object.prototype,{propertyIsEnumerable:aS}=Object.prototype;function Tm(t){return sS.call(t)}o(Tm,"toString");K.toString=Tm;function cs(t){return typeof t=="string"}o(cs,"isString");K.isString=cs;function cS(t){return cs(t)&&t!==""}o(cS,"isNonEmptyString");K.isNonEmptyString=cS;function uS(t){return Array.isArray(t)&&t.every(e=>cs(e))}o(uS,"isStringArray");K.isStringArray=uS;function lS(t){return Tm(t)==="[object RegExp]"}o(lS,"isRegexp");K.isRegexp=lS;function dS(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>aS.call(t,e))]}o(dS,"getOwnEnumerableKeys");K.getOwnEnumerableKeys=dS;function Cl(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof RegExp)&&!(t instanceof Date)}o(Cl,"isObject");K.isObject=Cl;function pS(t){return Cl(t)&&Array.isArray(t)}o(pS,"isArray");K.isArray=pS;function fS(t){let e=Object.getPrototypeOf(Uint8Array);return typeof t=="object"&&t instanceof e}o(fS,"isTypedArray");K.isTypedArray=fS;function hS(t){return typeof t=="number"&&!isNaN(t)}o(hS,"isNumber");K.isNumber=hS;function mS(t){return!!t&&typeof t[Symbol.iterator]=="function"}o(mS,"isIterable");K.isIterable=mS;function yS(t){return t===!0||t===!1}o(yS,"isBoolean");K.isBoolean=yS;function Sm(t){return typeof t>"u"}o(Sm,"isUndefined");K.isUndefined=Sm;function gS(t){return!Ni(t)}o(gS,"isDefined");K.isDefined=gS;function Ni(t){return Sm(t)||t===null}o(Ni,"isUndefinedOrNull");K.isUndefinedOrNull=Ni;function bS(t,e){if(!t)throw new Error(e?`Unexpected type, expected '${e}'`:"Unexpected type")}o(bS,"assertType");K.assertType=bS;function _S(t){if(Ni(t))throw new Error("Assertion Failed: argument is undefined or null");return t}o(_S,"assertIsDefined");K.assertIsDefined=_S;function ES(...t){let e=[];for(let r=0;r<t.length;r++){let n=t[r];if(Ni(n))throw new Error(`Assertion Failed: argument at index ${r} is undefined or null`);e.push(n)}return e}o(ES,"assertAllDefined");K.assertAllDefined=ES;var wS=Object.prototype.hasOwnProperty;function vS(t){if(!Cl(t))return!1;for(let e in t)if(wS.call(t,e))return!1;return!0}o(vS,"isEmptyObject");K.isEmptyObject=vS;function xl(t){return typeof t=="function"}o(xl,"isFunction");K.isFunction=xl;function TS(...t){return t.length>0&&t.every(xl)}o(TS,"areFunctions");K.areFunctions=TS;function SS(t,e){let r=Math.min(t.length,e.length);for(let n=0;n<r;n++)Im(t[n],e[n])}o(SS,"validateConstraints");K.validateConstraints=SS;function Im(t,e){if(cs(e)){if(typeof t!==e)throw new Error(`argument does not match constraint: typeof ${e}`)}else if(xl(e)){try{if(t instanceof e)return}catch{}if(!Ni(t)&&t.constructor===e||e.length===1&&e.call(void 0,t)===!0)return;throw new Error("argument does not match one of these constraints: arg instanceof constraint, arg.constructor === constraint, nor constraint(arg) === true")}}o(Im,"validateConstraint");K.validateConstraint=Im;function IS(t){return t===null?void 0:t}o(IS,"withNullAsUndefined");K.withNullAsUndefined=IS;function PS(t){return typeof t>"u"?null:t}o(PS,"withUndefinedAsNull");K.withUndefinedAsNull=PS;function AS(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}o(AS,"isErrorLike");K.isErrorLike=AS});var Jt=_(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.parseValueToBoolean=Nt.parseValueToStringArray=Nt.getValueFromRequestUser=Nt.statusCodesStringToNumberArray=void 0;var gn=k(),Ll=at(),Pm=new Map;function RS(t){if(Array.isArray(t)&&!t.some(i=>typeof i!="number"))return t;if(typeof t!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(t))throw new Error("Malformed input string");let e=Pm.get(t);if(e)return e;let r=t.split(","),n=[];for(let i of r){let s=i.split("-");if(s.length===2){let a=parseInt(s[0],10),c=parseInt(s[1],10);for(let u=a;u<=c;u++)n.push(u)}else n.push(parseInt(i,10))}return Pm.set(t,n),n}o(RS,"statusCodesStringToNumberArray");Nt.statusCodesStringToNumberArray=RS;function OS(t,e,r){if(!e.startsWith("."))throw new gn.ConfigurationError(`Invalid ${r} - must start with '.' - '${e}' does not`);let n=e.split(".").splice(1),i=t;return n.forEach(s=>{if(i===void 0)throw new gn.RuntimeError(`Error applying ${r} '${e}', reading '${s}'`);i=i[s]}),`${i}`}o(OS,"getValueFromRequestUser");Nt.getValueFromRequestUser=OS;function NS(t){if(Array.isArray(t)){if(t.includes(r=>typeof r!="string"))throw new gn.ConfigurationError("Received an array that contains non-string values.");return t}if((0,Ll.isString)(t))return t.includes(",")?t.split(",").map(r=>r.trim()).filter(r=>r!==","&&r!==""):[t];throw new gn.ConfigurationError(`Expected type of string, received type '${typeof t}'`)}o(NS,"parseValueToStringArray");Nt.parseValueToStringArray=NS;function CS(t){if((0,Ll.isBoolean)(t))return t;if((0,Ll.isString)(t)){if(t.toLowerCase()==="true")return!0;if(t.toLowerCase()==="false")return!1;throw new gn.ConfigurationError(`Attempted to parse string to boolean, but received ${t} which cannot be parsed.`)}throw new gn.ConfigurationError(`Expected type of boolean, received type '${typeof t}'`)}o(CS,"parseValueToBoolean");Nt.parseValueToBoolean=CS});var ls=_(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.generateCorsHeaders=ur.findMatchingOrigin=ur.parseCorsPolicies=void 0;var Br=k(),Am=Jt(),us=at();function xS(t){if(t==null)return[];if(!Array.isArray(t))throw new Br.ConfigurationError(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof t}'`);return t.map(r=>{if(!(0,us.isObject)(r))throw new Br.ConfigurationError(`Invalid custom cors policy is set. Expected an object, received '${typeof r}'`);if(!(0,us.isNonEmptyString)(r.name))throw new Br.ConfigurationError("Value of 'name' on custom cors policies must be a non-empty string.");if(r.maxAge!==void 0&&!(0,us.isNumber)(r.maxAge))throw new Br.ConfigurationError(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof r.maxAge}'`);if(r.allowCredentials!==void 0&&!(0,us.isBoolean)(r.allowCredentials))throw new Br.ConfigurationError("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=Dl(r,"allowedHeaders"),i=Dl(r,"allowedMethods"),s=Dl(r,"exposeHeaders"),a;try{a=(0,Am.parseValueToStringArray)(r.allowedOrigins)}catch(u){throw new Br.ConfigurationError(`Value of 'allowedOrigins' on custom cors policies is invalid. ${u.message} If using an environment variable, check that it is set correctly.`)}return{name:r.name,allowCredentials:typeof r.allowCredentials=="boolean"?String(r.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:n?n.join(", "):void 0,allowedMethods:i?i.join(", "):void 0,exposeHeaders:s?s.join(", "):void 0,maxAge:typeof r.maxAge=="number"?r.maxAge.toString():void 0}})}o(xS,"parseCorsPolicies");ur.parseCorsPolicies=xS;function Dl(t,e){let r;if(t[e]!==void 0)try{r=(0,Am.parseValueToStringArray)(t[e])}catch(n){throw new Br.ConfigurationError(`Value of '${e}' on custom cors policies is invalid. ${n.message} If using an environment variable, check that it is set correctly.`)}return r}o(Dl,"parseOptionalProperty");var LS=o((t,e)=>{if(e===null)return;if(t.find(a=>a==="*"))return e;let n=t.map(a=>a.trim().toLowerCase()),i=e.toLowerCase();return n.find(a=>a===i)},"findMatchingOrigin");ur.findMatchingOrigin=LS;var DS=o((t,e)=>{let r={"access-control-allow-origin":e};t.allowedHeaders&&(r["access-control-allow-headers"]=t.allowedHeaders),t.allowedMethods&&(r["access-control-allow-methods"]=t.allowedMethods),t.exposeHeaders&&(r["access-control-expose-headers"]=t.exposeHeaders);let n=t.allowCredentials;n&&(r["access-control-allow-credentials"]=n);let i=t.maxAge?.toString()??void 0;return i&&(r["access-control-max-age"]=i),r},"generateCorsHeaders");ur.generateCorsHeaders=DS});var Om=_(ds=>{"use strict";Object.defineProperty(ds,"__esModule",{value:!0});ds.registerCorsRoute=void 0;var MS=k(),US=Gt(),Ml=de(),kS=ar(),FS=Vr(),HS=gt(),Rm=ls(),qS=o((t,e)=>{let r=e.routeData.corsPolicies,n=o(async(a,c)=>{let u=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 Ml.HttpProblems.badRequest(a,c,{detail:"Expect headers origin and access-control-request-method"});let f=t.lookup(l,u);if(!f)return Ml.HttpProblems.notFound(a,c);let h=f.routeConfiguration,y=$S(l,d,p,h,r);return y.isValid?new Response(void 0,{status:200,statusText:"OK",headers:y.headers}):(y.error&&c.log.warn(y.error),Ml.HttpProblems.notFound(a,c))},"optionsHandler"),i=new US.Pipeline({processors:[kS.metricsProcessor],handler:n,gateway:e}),s=new HS.SystemRouteConfiguration({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:FS.SystemRouteName.CorsPreflight});t.addRoute(s,i.execute)},"registerCorsRoute");ds.registerCorsRoute=qS;var $S=o((t,e,r,n,i)=>{let s={isValid:!1,headers:{}};if(n.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":r,"access-control-allow-methods":t,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(n.corsPolicy==="none")return{...s,error:`No CORS policy set for the route '${n.pathPattern}'`};let a=i?.find(l=>l.name===n.corsPolicy);if(!a)throw new MS.ConfigurationError(`Invalid Configuration - corsPolicy '${n.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let c=(0,Rm.findMatchingOrigin)(a.allowedOrigins,r);return c?{isValid:!0,headers:(0,Rm.generateCorsHeaders)(a,c)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${r}'`}},"validateAndBuildResponseHeaders")});var Nm=_(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});ps.registerNoRoutes=void 0;var jS=Gt(),VS=ar(),BS=Vr(),GS=gt(),KS=o((t,e)=>{let r=o(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),n=new jS.Pipeline({processors:[VS.metricsProcessor],handler:r,gateway:e}),i=new GS.SystemRouteConfiguration({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:BS.SystemRouteName.EmptyGatewayCatchall});t.addRoute(i,n.execute)},"registerNoRoutes");ps.registerNoRoutes=KS});var Cm=_(Gr=>{"use strict";Object.defineProperty(Gr,"__esModule",{value:!0});Gr.registerNotMatchedHandler=Gr.notFoundRouteConfiguration=void 0;var JS=$r(),zS=Ot(),WS=Gt(),QS=de(),YS=ar(),ZS=Vr(),XS=gt();Gr.notFoundRouteConfiguration=new XS.SystemRouteConfiguration({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:ZS.SystemRouteName.UnmatchedPath});var eI=o((t,e)=>{let r=o(async(i,s)=>{let a=zS.runtimeExtensions.value?.notFoundHandler;if(a){let c=JS.ZuploContextExtensions.getContextExtensions(s);return a(i,s,{routesMatchedByPathOnly:c.pathOnlyMatches??[]})}return QS.HttpProblems.notFound(i,s)},"notFoundHandler"),n=new WS.Pipeline({processors:[YS.metricsProcessor],handler:r,gateway:e});t.addRoute(Gr.notFoundRouteConfiguration,n.execute)},"registerNotMatchedHandler");Gr.registerNotMatchedHandler=eI});var Ul=_(fs=>{"use strict";Object.defineProperty(fs,"__esModule",{value:!0});fs.corsProcessor=void 0;var Dm=k(),xm=ls(),tI=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Lm=o(t=>{tI.forEach(e=>t.delete(e))},"stripCorsHeaders"),rI=o(async(t,e,r,n)=>{let i=e.route;if(!i.corsPolicy||i.corsPolicy==="none"){let d=await n(t),p=new Headers(d.headers);return Lm(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await n(t);if(!(s instanceof Response))throw new Dm.SystemError(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=nI(i,r.routeData.corsPolicies),c=iI(t,a),u=new Headers(s.headers);return Lm(u),Object.entries(c).forEach(([d,p])=>{u.set(d,p)}),new Response(s.body,{status:s.status,statusText:s.statusText,headers:u,webSocket:s.webSocket})},"corsProcessor");fs.corsProcessor=rI;var nI=o((t,e)=>{if(t.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:t.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let r=e?.find(n=>n.name===t.corsPolicy);if(r===void 0)throw new Dm.ConfigurationError(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return r},"getCorsPolicy"),iI=o((t,e)=>{let r=(0,xm.findMatchingOrigin)(e.allowedOrigins,t.headers.get("origin"));return r?(0,xm.generateCorsHeaders)(e,r):{}},"getCorsHeaders")});var Mm=_(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});hs.registerPingRoute=void 0;var oI=Gt(),sI=Ul(),aI=Vr(),cI=gt(),uI=o((t,e)=>{let r=o(async()=>new Response(null,{status:200}),"pingRouteHandler"),n=new oI.Pipeline({processors:[sI.corsProcessor],handler:r,gateway:e}),i=new cI.SystemRouteConfiguration({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:aI.SystemRouteName.Ping});t.addRoute(i,n.execute)},"registerPingRoute");hs.registerPingRoute=uI});var _n=_(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.OutboundPolicy=bn.InboundPolicy=void 0;var lI=k(),dI=at(),ms=class{static{o(this,"PolicyBase")}options;policyName;constructor(e,r){if(!(0,dI.isString)(r))throw new lI.RuntimeError(`The name of a policy must be a string. Received '${r}' of type '${typeof r}'`);this.options=e,this.policyName=r}},kl=class extends ms{static{o(this,"InboundPolicy")}};bn.InboundPolicy=kl;var Fl=class extends ms{static{o(this,"OutboundPolicy")}};bn.OutboundPolicy=Fl});var En=_(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.createInternalPolicyProcessor=bt.policyProcessor=bt.toStackedInboundHandler=bt.getInboundPolicyInstances=void 0;var pI=$r(),$e=k(),ys=_n(),Um=Ke(),fI=ie(),$l=class extends ys.InboundPolicy{static{o(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,r,n){super(r,n),this.#e=e}handler(e,r){return this.#e(e,r,this.options,this.policyName)}},jl=class extends ys.OutboundPolicy{static{o(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,r,n){super(r,n),this.#e=e}handler(e,r,n){return this.#e(e,r,n,this.options,this.policyName)}},Hl=new Map;function km(t,e){let r,n;return Array.isArray(t)?r=t:(r=t.policies?.inbound??[],n=t.path),r.filter(s=>!Hl.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new $e.ConfigurationError(`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 $e.ConfigurationError(`Invalid state - invalid policy '${s}' on route '${n}' (typeof policy '${typeof a.handler?.module}')`);let c=a.handler?.module[a.handler.export];if(typeof c!="function")throw new $e.ConfigurationError(`Invalid state - invalid policy '${s}' on route '${n}' (typeof module '${typeof c}')`);let u;if(typeof c!="function")throw new $e.ConfigurationError(`Invalid state - invalid policy '${s}' on route '${n}' (typeof module '${typeof c}')`);if(c.prototype instanceof ys.InboundPolicy)u=new c(a.handler.options,a.name);else if(typeof c=="function")u=new $l(c,a.handler.options,a.name);else throw new $e.ConfigurationError(`Invalid state - invalid policy '${s}' on route '${n}' (typeof policy '${typeof c}')`);if(typeof u.handler!="function")throw new $e.ConfigurationError(`Invalid state - invalid handler on policy '${s}' on route '${n}' (typeof handler '${typeof u.handler}')`);Hl.set(a.name,u)}),r.map(s=>{let a=Hl.get(s);if(a===void 0)throw new $e.RuntimeError("Internal error. Policy not found in cache.");return a})}o(km,"getInboundPolicyInstances");bt.getInboundPolicyInstances=km;var ql=new Map;function hI(t,e){let r=t.policies?.outbound??[];return r.filter(i=>!ql.has(i)).forEach(i=>{let s=e?.find(u=>u.name===i);if(!s)throw new $e.ConfigurationError(`Invalid state - no Policy with the name '${i}' on route '${t.path}' was found in the policies configuration (check case).`);if(typeof s.handler?.module!="object")throw new $e.ConfigurationError(`Invalid state - invalid policy '${i}' on route '${t.path}' (typeof policy '${typeof s.handler?.module}')`);let a=s.handler?.module[s.handler.export],c;if(typeof a!="function")throw new $e.ConfigurationError(`Invalid state - invalid policy '${i}' on route '${t.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof ys.OutboundPolicy)c=new a(s.handler.options??{},s.name);else if(typeof a=="function")c=new jl(a,s.handler.options??{},s.name);else throw new $e.ConfigurationError(`Invalid state - invalid policy '${i}' on route '${t.path}' (typeof policy '${typeof a}')`);if(typeof c.handler!="function")throw new $e.ConfigurationError(`Invalid state - invalid handler on policy '${i}' on route '${t.path}'`);ql.set(s.name,c)}),r.map(i=>{let s=ql.get(i);if(s===void 0)throw new $e.RuntimeError("Internal error. Policy not found in cache.");return s})}o(hI,"getOutboundPolicyInstances");var mI=o(t=>async(e,r)=>{let n=pI.ZuploContextExtensions.getContextExtensions(r),i=[...t],s=e;for(;i.length>0;){let a=i.shift();if(!a)return s;let c=await a.handler(s,r);if(c instanceof Um.ZuploRequest)s=c;else if(c instanceof Request)s=new Um.ZuploRequest(c);else{if(c instanceof Response)return c;throw new $e.ConfigurationError(`Invalid state - invalid handler on policy '${a.policyName}' on route '${r.route.path}. The result of an inbound policy must be a Response or Request.`)}n.latestRequest=s}return s},"toStackedInboundHandler");bt.toStackedInboundHandler=mI;var yI=o(t=>async(e,r,n)=>{let i=[...t],s=e;for(;i.length>0;){let a=i.shift();if(!a)return s;let c=await a.handler(s,r,n);if(!(c instanceof Response))throw new $e.ConfigurationError(`Invalid state - invalid handler on policy '${a.policyName}' on route '${n.route.path}. The result of an outbound policy must be a Response.`);s=c}return s},"toStackedOutboundHandler"),gI=o(async(t,e,r,n)=>{let i=km(e.route,r.routeData.policies),s=hI(e.route,r.routeData.policies);return Fm({request:t,context:e,inboundPolicies:i,outboundPolicies:s,gateway:r,next:n})},"policyProcessor");bt.policyProcessor=gI;function bI({inboundPolicies:t=[],outboundPolicies:e=[]}){return o(async(n,i,s,a)=>Fm({request:n,context:i,inboundPolicies:t,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}o(bI,"createInternalPolicyProcessor");bt.createInternalPolicyProcessor=bI;async function Fm({request:t,context:e,inboundPolicies:r,outboundPolicies:n,gateway:i,next:s}){let a=(0,bt.toStackedInboundHandler)(r);try{let c=await a(t,e);if(c instanceof Response)return c;let u=await s(c),l=yI(n),d;return fI.Environment.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(u,t,e):d=u.ok?l(u,t,e):u,d}catch(c){return e.log.error(c),i.errorHandler(t,e,c)}}o(Fm,"executePolicyProcessor")});var Hm=_(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.serialize=wn.parse=void 0;var _I=Object.prototype.toString,gs=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function EI(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");let r={},i=(e||{}).decode||vI,s=0;for(;s<t.length;){let a=t.indexOf("=",s);if(a===-1)break;let c=t.indexOf(";",s);if(c===-1)c=t.length;else if(c<a){s=t.lastIndexOf(";",a-1)+1;continue}let u=t.slice(s,a).trim();if(r[u]===void 0){let l=t.slice(a+1,c).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),r[u]=II(l,i)}s=c+1}return r}o(EI,"parse");wn.parse=EI;function wI(t,e,r){let n=r||{},i=n.encode||TI;if(typeof i!="function")throw new TypeError("option encode is invalid");if(!gs.test(t))throw new TypeError("argument name is invalid");let s=i(e);if(s&&!gs.test(s))throw new TypeError("argument val is invalid");let a=t+"="+s;if(n.maxAge!=null){let c=n.maxAge-0;if(isNaN(c)||!isFinite(c))throw new TypeError("option maxAge is invalid");a+="; Max-Age="+Math.floor(c)}if(n.domain){if(!gs.test(n.domain))throw new TypeError("option domain is invalid");a+="; Domain="+n.domain}if(n.path){if(!gs.test(n.path))throw new TypeError("option path is invalid");a+="; Path="+n.path}if(n.expires){let c=n.expires;if(!SI(c)||isNaN(c.valueOf()))throw new TypeError("option expires is invalid");a+="; Expires="+c.toUTCString()}if(n.httpOnly&&(a+="; HttpOnly"),n.secure&&(a+="; Secure"),n.priority)switch(typeof n.priority=="string"?n.priority.toLowerCase():n.priority){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}if(n.sameSite)switch(typeof n.sameSite=="string"?n.sameSite.toLowerCase():n.sameSite){case!0:a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"strict":a+="; SameSite=Strict";break;case"none":a+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return a}o(wI,"serialize");wn.serialize=wI;function vI(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}o(vI,"decode");function TI(t){return encodeURIComponent(t)}o(TI,"encode");function SI(t){return _I.call(t)==="[object Date]"||t instanceof Date}o(SI,"isDate");function II(t,e){try{return e(t)}catch{return t}}o(II,"tryDecode")});var qm=_(bs=>{"use strict";Object.defineProperty(bs,"__esModule",{value:!0});bs.devPortalBaseURL=void 0;var PI=Hm();function AI(t,e){try{let r=/v\d+(-\d+)?/g,i=(0,PI.parse)(e.get("Cookie")||"")["zp-dev-portal"];return i!==null&&i&&r.test(i)?`https://dev-portal-${i}.zuplo.com`:t}catch{}return t}o(AI,"devPortalBaseURL");bs.devPortalBaseURL=AI});var Gm=_(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.registerDevPortalLegacyRedirectRoute=vn.registerDevPortalV3Route=void 0;var Vl=Kt(),jm=Gt(),Vm=ar(),RI=En(),Bm=gt(),OI=qm(),lr=ie(),$m="/__zuplo/dev-portal",NI="dev-portal-id",CI="dev-portal-host",xI="zp-account",LI="zp-project",DI="dev-portal-build",MI=`
36
36
  <!DOCTYPE html>
37
37
  <html lang="en">
38
38
  <head>
@@ -71,7 +71,7 @@ Signature verification is impossible without access to the original signed mater
71
71
  `+d}):new Xr.StripeSignatureVerificationError(e,t,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
72
72
  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.
73
73
  `+l+`
74
- `+d});let p=Math.floor((typeof c=="number"?c:Date.now())/1e3)-r.timestamp;if(i>0&&p>i)throw new Xr.StripeSignatureVerificationError(e,t,{message:"Timestamp outside the tolerance zone"});return!0}o(QR,"validateComputedSignature");function YR(t,e){return typeof t!="string"?null:t.split(",").reduce((r,n)=>{let i=n.split("=");return i[0]==="t"&&(r.timestamp=parseInt(i[1],10)),i[0]===e&&r.signatures.push(i[1]),r},{timestamp:-1,signatures:[]})}o(YR,"parseHeader");function ZR(t,e){if(t.length!==e.length)return!1;let r=t.length,n=0;for(let i=0;i<r;++i)n|=t.charCodeAt(i)^e.charCodeAt(i);return n===0}o(ZR,"secureCompare");async function o_(t,e){let r=new TextEncoder,n=await crypto.subtle.importKey("raw",r.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),i=await crypto.subtle.sign("hmac",n,r.encode(t)),s=new Uint8Array(i),a=new Array(s.length);for(let c=0;c<s.length;c++)a[c]=tf[s[c]];return a.join("")}o(o_,"computeHMACSignatureAsync");ti.computeHMACSignatureAsync=o_;var tf=new Array(256);for(let t=0;t<tf.length;t++)tf[t]=t.toString(16).padStart(2,"0")});var lt=_(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});Ga.optionValidator=void 0;var ri=k(),XR=at();function eO(t,e,r="policy"){let n=`${r} '${e}'`;if(!(0,XR.isObject)(t))throw new ri.ConfigurationError(`Options on ${n} is expected to be an object. Received the type '${typeof t}'.`);let i=o((c,u,l)=>{let d=t[c];if(!(l&&d===void 0)){if(d===void 0)throw new ri.ConfigurationError(`Value of '${String(c)}' on ${n} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(u==="array"&&Array.isArray(d))throw new ri.ConfigurationError(`Value of '${String(c)}' on ${n} must be an array. Received type ${typeof d}.`);if(typeof d!==u)throw new ri.ConfigurationError(`Value of '${String(c)}' on ${n} must be of type ${u}. Received type ${typeof d}.`);if(typeof d=="string"&&d.length===0)throw new ri.ConfigurationError(`Value of '${String(c)}' on ${n} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof d=="number"&&isNaN(d))throw new ri.ConfigurationError(`Value of '${String(c)}' on ${n} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),s=o((c,u)=>(i(c,u,!0),{optional:s,required:a}),"optional"),a=o((c,u)=>(i(c,u,!1),{optional:s,required:a}),"required");return{optional:s,required:a}}o(eO,"optionValidator");Ga.optionValidator=eO});var nf=_(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.StripeWebhookVerificationInboundPolicy=void 0;var tO=_n(),rO=de(),nO=s_(),iO=lt(),rf=class extends tO.InboundPolicy{static{o(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,r){(0,iO.optionValidator)(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let n=e.headers.get("stripe-signature");try{let i=await e.clone().text();await(0,nO.constructEventAsync)(i,n,this.options.signingSecret)}catch(i){let s=i.message;if(i.type&&i.type==="StripeSignatureVerificationError"){let a=i.message,u=/Note:(.*)/g.exec(a);s=u?u[1].trim():a}return r.log.error("Error validating stripe webhook",s),rO.HttpProblems.badRequest(e,r,{title:"Webhook Error",detail:s})}return e}};Ka.StripeWebhookVerificationInboundPolicy=rf});var c_=_(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});Ja.isStripeWebhookEvent=void 0;var a_=at();function oO(t){return t!==null&&typeof t=="object"&&"id"in t&&(0,a_.isString)(t.id)&&"type"in t&&(0,a_.isString)(t.type)}o(oO,"isStripeWebhookEvent");Ja.isStripeWebhookEvent=oO});var u_=_(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.MeteringPlugin=void 0;var sO=Ot(),of=class extends sO.SystemRuntimePlugin{static{o(this,"MeteringPlugin")}};za.MeteringPlugin=of});var cf=_(af=>{"use strict";Object.defineProperty(af,"__esModule",{value:!0});var sf=k(),aO={getSubscription:async({subscriptionId:t,stripeSecretKey:e,logger:r})=>{let n=await fetch(`https://api.stripe.com/v1/subscriptions/${t}`,{headers:{Authorization:`Bearer ${e}`}}),i=await n.json();if(n.status!==200){let s="Error retrieving subscription from Stripe API.";throw r.error(s,i),new sf.RuntimeError(s)}return i},getCustomer:async({customerId:t,stripeSecretKey:e,logger:r})=>{let n=await fetch(`https://api.stripe.com/v1/customers/${t}`,{headers:{Authorization:`Bearer ${e}`}}),i=await n.json();if(n.status!==200){let s="Error retrieving customer from Stripe API.";throw r.error(s,i),new sf.RuntimeError(s)}return i},getUpcomingInvoice:async({customerId:t,stripeSecretKey:e,logger:r})=>{let n=await fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${t}`,{headers:{Authorization:`Bearer ${e}`}}),i=await n.json();if(n.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw r.error(s,i),new sf.RuntimeError(s)}return i}};af.default=aO});var d_=_(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.deleteConsumer=Ar.createConsumerInvite=Ar.createConsumer=void 0;var uf=k(),lf=Je(),df=ie(),pf=kn(),ff="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",l_="My API Key";async function cO({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:r,stripeCustomerId:n,managerEmail:i,managerSub:s,context:a}){let{authApiJWT:c}=df.Environment.instance,u=new URL(`/v1/buckets/${t}/consumers`,ff);u.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:l_,tags:{subscriptionExternalId:e,planExternalIds:[r]},metadata:{stripeSubscriptionId:e,stripeProductId:r,stripeCustomerId:n},managers:[{sub:s,email:i}]},p=await(0,pf.fetchRetry)({retryDelayMs:5,retries:2,logger:lf.SystemLogMap.getLogger(a)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${c}`,"content-type":"application/json"},body:JSON.stringify(d)}),f=await p.json();if(p.status!==200){let h="Error creating API Key Consumer";throw a.log.error(h,f),new uf.RuntimeError(h)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:r}),l}o(cO,"createConsumer");Ar.createConsumer=cO;async function uO({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:r,stripeCustomerId:n,managerEmail:i,context:s}){let{authApiJWT:a}=df.Environment.instance,c=new URL(`/v1/buckets/${t}/consumers`,ff);c.searchParams.set("with-api-key","true");let u=crypto.randomUUID(),l={name:u,description:l_,tags:{subscriptionExternalId:e,planExternalIds:[r]},metadata:{stripeSubscriptionId:e,stripeProductId:r,stripeCustomerId:n},managers:[i]},d=await(0,pf.fetchRetry)({retryDelayMs:5,retries:2,logger:lf.SystemLogMap.getLogger(s)},c.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 uf.RuntimeError(f)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:u,stripeSubscriptionId:e,stripeProductId:r}),u}o(uO,"createConsumerInvite");Ar.createConsumerInvite=uO;async function lO({apiKeyBucketName:t,consumerId:e,context:r}){let{authApiJWT:n}=df.Environment.instance,i=new URL(`/v1/buckets/${t}/consumers/${e}`,ff);i.searchParams.set("with-api-key","true");let s=await(0,pf.fetchRetry)({retryDelayMs:5,retries:2,logger:lf.SystemLogMap.getLogger(r)},i.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),c="Error invalidating API Key Consumer";throw r.log.error(c,a),new uf.RuntimeError(c)}return r.log.info(`Successfully invalidated API Key Consumer '${e}`),e}o(lO,"deleteConsumer");Ar.deleteConsumer=lO});var Wa=_(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.getSubscription=Or.updateSubscription=Or.createSubscription=void 0;var Rr=k(),hf=Je(),mf=ie(),yf=kn(),gf=at();async function dO({context:t,stripeSubscriptionId:e,stripeProductId:r,customerKey:n,meteringBucketId:i,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:c,metadata:u}){let l={status:c,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[r],customerKey:n,customerExternalId:a,metadata:u},{authApiJWT:d,meteringServiceUrl:p}=mf.Environment.instance;if(!(0,gf.isNonEmptyString)(d))throw new Rr.SystemError("No Zuplo JWT token set.");let f=await(0,yf.fetchRetry)({retryDelayMs:5,retries:2,logger:hf.SystemLogMap.getLogger(t)},`${p}/internal/v1/metering/${i}/subscriptions`,{headers:{Authorization:`Bearer ${d}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(l)});if(!f.ok){let h="Error creating monetization subscription.",y;try{y=await f.json()}catch{y={status:f.status,statusText:f.statusText}}throw t.log.error(h,y),new Rr.RuntimeError(h)}t.log.info("Successfully created monetization subscription.",l)}o(dO,"createSubscription");Or.createSubscription=dO;async function pO({context:t,meteringSubscriptionId:e,meteringBucketId:r,requestBody:n}){let{authApiJWT:i,meteringServiceUrl:s}=mf.Environment.instance;if(!(0,gf.isNonEmptyString)(i))throw new Rr.SystemError("No Zuplo JWT token set.");let a=await(0,yf.fetchRetry)({retryDelayMs:5,retries:2,logger:hf.SystemLogMap.getLogger(t)},`${s}/internal/v1/metering/${r}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"PATCH",body:JSON.stringify(n)});if(!a.ok){let c=`Error updating monetization subscription with: '${JSON.stringify(n)}'.`,u;try{u=await a.json()}catch{u={status:a.status,statusText:a.statusText}}throw t.log.error(c,u),new Rr.RuntimeError(c)}t.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(n)}'.`)}o(pO,"updateSubscription");Or.updateSubscription=pO;async function fO({context:t,stripeSubscriptionId:e,stripeCustomerId:r,meteringBucketId:n}){let{authApiJWT:i,meteringServiceUrl:s}=mf.Environment.instance;if(!(0,gf.isNonEmptyString)(i))throw new Rr.SystemError("No Zuplo JWT token set.");let a=await(0,yf.fetchRetry)({retryDelayMs:5,retries:2,logger:hf.SystemLogMap.getLogger(t)},`${s}/internal/v1/metering/${n}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":t.requestId},method:"GET"});if(!a.ok){let u="Error retrieving the monetization subscription.",l;try{l=await a.json()}catch{l={status:a.status,statusText:a.statusText}}throw t.log.error(u,l),new Rr.RuntimeError(u,l)}let c=await a.json();if(c.data.length===0){let u="Subscription was not found and the event was ignored by Zuplo.";throw t.log.error(u),new Rr.RuntimeError(u)}if(c.data[0].customerExternalId!==r){let u="A subscription was not found for the customer provided and the event was ignored by Zuplo.";throw t.log.error(u),new Rr.RuntimeError(u)}return c.data[0]}o(fO,"getSubscription");Or.getSubscription=fO});var bf=_(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});Qa.stripeStatusToMeteringStatus=void 0;function hO(t){return t.replaceAll("_","-")}o(hO,"stripeStatusToMeteringStatus");Qa.stripeStatusToMeteringStatus=hO});var p_=_(to=>{"use strict";var mO=to&&to.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(to,"__esModule",{value:!0});var en=de(),yO=mO(cf()),_f=d_(),gO=Wa(),bO=bf();async function _O(t,e,r,n){let i=r.data.object.id;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected event '${r.id}' to have '.data.object.id' be the subscription ID.`),en.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=r.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${r.id}' to have a plan data.`),en.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=r.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${r.id}'`),en.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let c=s.product,u,l,d;if(r.data.object.metadata&&r.data.object.metadata.zuplo_created_by_email&&r.data.object.metadata.zuplo_created_by_sub)l=r.data.object.metadata.zuplo_created_by_email,d=r.data.object.metadata.zuplo_created_by_sub,u=await(0,_f.createConsumer)({apiKeyBucketName:n.apiKeyBucketName,stripeProductId:c,stripeSubscriptionId:i,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await yO.default.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.`),en.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe API result. Expected customer to contain email address."});u=await(0,_f.createConsumerInvite)({apiKeyBucketName:n.apiKeyBucketName,stripeProductId:c,stripeSubscriptionId:i,stripeCustomerId:a,managerEmail:p.email,context:e})}if(!u)return en.HttpProblems.internalServerError(t,e,{detail:"No API Key Consumer was created, skipping creation of subscription"});try{let p=(0,bO.stripeStatusToMeteringStatus)(r.data.object.status),f;l&&d&&(f={subscriber:{sub:d,email:l}}),await(0,gO.createSubscription)({context:e,stripeProductId:c,stripeSubscriptionId:i,customerKey:u,meteringBucketId:n.meteringBucketId,meteringBucketRegion:n.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:f})}catch(p){return await(0,_f.deleteConsumer)({apiKeyBucketName:n.apiKeyBucketName,consumerId:u,context:e}),en.HttpProblems.internalServerError(t,e,{detail:p.message})}return en.HttpProblems.ok(t,e)}o(_O,"onCustomerSubscriptionCreated");to.default=_O});var h_=_(wf=>{"use strict";Object.defineProperty(wf,"__esModule",{value:!0});var Ef=de(),f_=Wa();async function EO(t,e,r,n){let i=r.data.object.id;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected event '${r.id}' to have '.data.object.id' be the subscription ID.`),Ef.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=r.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${r.id}'`),Ef.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let a=await(0,f_.getSubscription)({context:e,stripeSubscriptionId:i,stripeCustomerId:s,meteringBucketId:n.meteringBucketId});return await(0,f_.updateSubscription)({context:e,meteringSubscriptionId:a.id,meteringBucketId:n.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}}),Ef.HttpProblems.ok(t,e)}o(EO,"onCustomerSubscriptionDeleted");wf.default=EO});var m_=_(no=>{"use strict";var wO=no&&no.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(no,"__esModule",{value:!0});var ro=de(),vO=wO(cf()),Ya=Wa(),TO=bf();async function SO(t,e,r,n){let i=r.data.object.id;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected event '${r.id}' to include '.data.object.id' as the subscription ID.`),ro.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=r.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${r.id}'`),ro.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(r.data.previous_attributes){let a=r.data.previous_attributes;if(a.status&&a.status!==r.data.object.status){e.log.debug(`Processing subscription status change from Stripe event '${r.id}'.`);let c=await(0,Ya.getSubscription)({context:e,stripeSubscriptionId:i,stripeCustomerId:s,meteringBucketId:n.meteringBucketId}),u=(0,TO.stripeStatusToMeteringStatus)(r.data.object.status);return await(0,Ya.updateSubscription)({context:e,meteringSubscriptionId:c.id,meteringBucketId:n.meteringBucketId,requestBody:{status:u,planExternalIds:c.planExternalIds}}),ro.HttpProblems.ok(t,e)}if(a.plan&&a.plan.product!==r.data.object.plan.product){e.log.debug(`Processing subscription plan change from Stripe event '${r.id}'.`);let c=await(0,Ya.getSubscription)({context:e,stripeSubscriptionId:i,stripeCustomerId:s,meteringBucketId:n.meteringBucketId}),u=r.data.object.plan.product,d=(await vO.default.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:n.stripeSecretKey})).lines.data.filter(f=>f.proration&&f.price.product===u),p=0;return d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${r.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await(0,Ya.updateSubscription)({context:e,meteringSubscriptionId:c.id,meteringBucketId:n.meteringBucketId,requestBody:{status:c.status,planExternalIds:[u],prorate:p}}),ro.HttpProblems.ok(t,e)}}return e.log.warn(`This update event '${r.id}' is not supported by Stripe metering plugin webhook.`),ro.HttpProblems.badRequest(t,e,{detail:"This update event is not supported by Stripe metering plugin webhook."})}o(SO,"onCustomerSubscriptionUpdated");no.default=SO});var g_=_(ni=>{"use strict";var Tf=ni&&ni.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ni,"__esModule",{value:!0});ni.StripeMonetizationPlugin=void 0;var Za=Yi(),Xa=k(),IO=Gt(),PO=nf(),y_=de(),AO=ar(),RO=En(),OO=Sl(),NO=gt(),CO=ie(),xO=c_(),LO=lt(),DO=u_(),MO=Tf(p_()),UO=Tf(h_()),kO=Tf(m_()),vf=class extends DO.MeteringPlugin{static{o(this,"StripeMonetizationPlugin")}options;constructor(e){super(),this.options=e}registerRoutes(e,r){let n=o(async(c,u)=>{if(this.options.__testMode===!0)return u.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:l,apiKeyBucketName:d}=this.options;if(!l)if(Za.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)l=Za.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new Xa.ConfigurationError("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!d)if(Za.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)d=Za.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new Xa.ConfigurationError("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!CO.Environment.instance.build.ACCOUNT_NAME)throw new Xa.SystemError("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let p=this.options.meteringBucketRegion??"us-central1";if(!FO(p))throw new Xa.ConfigurationError(`StripeMonetizationPlugin - The value '${p}' on the property 'meteringBucketRegion' is invalid.`);let f=await c.json();if(!(0,xO.isStripeWebhookEvent)(f))return y_.HttpProblems.badRequest(c,u,{detail:"The received body was not in the expected format."});switch(u.log.info(`Received Stripe webhook event of type '${f.type}' with ID '${f.id}'.`),f.type){case"customer.subscription.created":return await(0,MO.default)(c,u,f,{meteringBucketId:l,apiKeyBucketName:d,meteringBucketRegion:p,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await(0,kO.default)(c,u,f,{meteringBucketId:l,apiKeyBucketName:d,meteringBucketRegion:p,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await(0,UO.default)(c,u,f,{meteringBucketId:l});default:return y_.HttpProblems.badRequest(c,u,{detail:"Event is not supported by Stripe monetization plugin webhook."})}},"stripeWebhookHandler"),i=(0,RO.createInternalPolicyProcessor)({inboundPolicies:[new PO.StripeWebhookVerificationInboundPolicy({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});(0,LO.optionValidator)(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let s=new IO.Pipeline({processors:[AO.metricsProcessor,i],handler:n,gateway:r}),a=new NO.SystemRouteConfiguration({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:OO.SystemRouteName.StripePlugin});e.addRoute(a,s.execute)}};ni.StripeMonetizationPlugin=vf;function FO(t){return t!==null&&typeof t=="string"&&["us-central1","europe-west4"].includes(t)}o(FO,"isMetricsRegion")});var v_=_(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.AmberfloMeteringInboundPolicy=ii.AmberfloMeteringPolicy=void 0;var b_=k(),HO=Re(),__=Jt(),w_=new WeakMap,E_={},Sf=class{static{o(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,r){w_.set(e,r)}};ii.AmberfloMeteringPolicy=Sf;async function qO(t,e,r,n){if(!r.statusCodes)throw new b_.ConfigurationError(`Invalid AmberfloMeterInboundPolicy '${n}': options.statusCodes must be an array of HTTP status code numbers`);let i=(0,__.statusCodesStringToNumberArray)(r.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(i.includes(s.status)){let a=w_.get(e),c=r.customerId;if(r.customerIdPropertyPath){if(!t.user)throw new b_.RuntimeError(`Unable to apply customerIdPropertyPath '${r.customerIdPropertyPath}' as request.user is 'undefined'.`);c=(0,__.getValueFromRequestUser)(t.user,r.customerIdPropertyPath,"customerIdPropertyPath")}let u=a?.customerId??c;if(!u){e.log.error(`Error in AmberfloMeterInboundPolicy '${n}': customerId cannot be undefined`);return}let l=a?.meterApiName??r.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterApiName cannot be undefined`);return}let d=a?.meterValue??r.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterValue cannot be undefined`);return}let p={customerId:u,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(r.dimensions??{},a?.dimensions)},f=E_[r.apiKey];if(!f){let h=r.apiKey,y=t.headers.get("zm-test-id")??"";f=new HO.BatchDispatch("amberflo-ingest-meter",10,async b=>{try{let I=r.url??"https://app.amberflo.io/ingest",A=await fetch(I,{method:"POST",body:JSON.stringify(b),headers:{"content-type":"application/json","x-api-key":h,"zm-test-id":y}});A.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${n}'. ${A.status}: ${await A.text()}`)}catch(I){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${n}': ${I.message}`),I}}),E_[h]=f}f.enqueue(p),e.waitUntil(f.waitUntilFlushed())}}),t}o(qO,"AmberfloMeteringInboundPolicy");ii.AmberfloMeteringInboundPolicy=qO});var If=_(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});ec.sha256=void 0;async function $O(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(r)].map(i=>i.toString(16).padStart(2,"0")).join("")}o($O,"sha256");ec.sha256=$O});var Zt=_(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});tc.getPolicyCacheName=void 0;var jO=If(),T_=new Map;async function VO(t,e){let r,n=T_.get(t);return n!==void 0?r=n:(r=`zuplo-policy-${await(0,jO.sha256)(JSON.stringify({policyName:t,options:e}))}`,T_.set(t,r)),r}o(VO,"getPolicyCacheName");tc.getPolicyCacheName=VO});var Rf=_(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});rc.ApiKeyInboundPolicy=void 0;var BO=Zt(),GO=Bt(),S_=Yi(),Pf=k(),KO=Kt(),I_=Je(),Af=ie(),JO=kn(),P_="key-metadata-cache-type";function zO(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}o(zO,"getKeyValue");async function WO(t,e,r,n){if(!r.bucketName)if(S_.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)r.bucketName=S_.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new Pf.ConfigurationError(`ApiKeyInboundPolicy '${n}' - no bucketName property provided`);let i={authHeader:r.authHeader??"authorization",authScheme:r.authScheme??"Bearer",bucketName:r.bucketName,cacheTtlSeconds:r.cacheTtlSeconds??60,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:r.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(i.cacheTtlSeconds<60)throw new Pf.ConfigurationError(`ApiKeyInboundPolicy '${n}' - minimum cacheTtlSeconds value is 60s, '${i.cacheTtlSeconds}' is invalid`);let s=o(I=>i.allowUnauthenticatedRequests?t:KO.HttpProblems.unauthorized(t,e,{detail:I}),"unauthorizedResponse"),a=t.headers.get(i.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(i.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let c=zO(a,i);if(!c||c==="")return s("No key present");let u=await QO(c),l=await(0,BO.getPolicyCacheName)(n,i),d=new GO.MemoryZoneReadThroughCache(l,e),p=await d.get(u);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==P_&&I_.SystemLogMap.getLogger(e).error(`ApiKeyInboundPolicy '${n}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let f={key:c},h=await(0,JO.fetchRetry)({retryDelayMs:5,retries:2,logger:I_.SystemLogMap.getLogger(e)},`${Af.Environment.instance.apiKeyServiceUrl}/v1/$validate/${i.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":Af.Environment.instance.deploymentName??"unknown","User-Agent":Af.Environment.instance.systemUserAgent},body:JSON.stringify(f)});if(h.status===401)return e.log.info(`ApiKeyInboundPolicy '${n}' - 401 response from Key Service`),s("Authorization Failed");if(h.status!==200){try{let I=await h.text(),A=JSON.parse(I);e.log.error("Unexpected response from key service",A)}catch{e.log.error("Invalid response from key service")}throw new Pf.RuntimeError(`ApiKeyInboundPolicy '${n}' - unexpected response from Key Service. Status: ${h.status}`)}let y=await h.json(),b={isValid:!0,typeId:P_,user:{sub:y.name,data:y.metadata}};return t.user=b.user,d.put(u,b,i.cacheTtlSeconds),t}o(WO,"ApiKeyInboundPolicy");rc.ApiKeyInboundPolicy=WO;async function QO(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}o(QO,"hashValue")});var A_=_(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});nc.ApiAuthKeyInboundPolicy=void 0;var YO=Rf();nc.ApiAuthKeyInboundPolicy=YO.ApiKeyInboundPolicy});var Xt=_(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});ic.OpenIdJwtInboundPolicy=void 0;var Nf=(ra(),xo(ta)),Cf=k(),ZO=de(),Of={},XO=o(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new Cf.ConfigurationError("Invalid State - jwkUrl not set");Of[e.jwkUrl]||(Of[e.jwkUrl]=(0,Nf.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:r}=await(0,Nf.jwtVerify)(t,Of[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return r},"jwkVerifier"),eN=o(async(t,e)=>{let r;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);r=new Uint8Array(s)}else r=e.secret;let{payload:n}=await(0,Nf.jwtVerify)(t,r,{issuer:e.issuer,audience:e.audience});return n},"secretVerifier"),tN=o(async(t,e,r,n)=>{let i=t.headers.get("Authorization"),s="bearer ",a=o(f=>ZO.HttpProblems.unauthorized(t,e,{detail:f}),"unauthorizedResponse");if(!r.jwkUrl&&!r.secret)throw new Cf.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': One of 'jwkUrl' or 'secret' options are required.`);if(r.jwkUrl&&r.secret)throw new Cf.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let c=r.jwkUrl?XO:eN,l=await o(async()=>{if(!i)return a("No authorization header");if(i.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let f=i.substring(s.length);if(!f||f.length===0)return a("No bearer token on authorization header");try{return await c(f,r)}catch(h){let y=new URL(t.url);return"code"in h&&h.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${y.pathname} `,h):e.log.warn(`Invalid token on: ${t.method} ${y.pathname}`,h),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return r.allowUnauthenticatedRequests===!0?t:l;let d=r.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");ic.OpenIdJwtInboundPolicy=tN});var R_=_(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});oc.Auth0JwtInboundPolicy=void 0;var rN=Xt(),nN=o(async(t,e,r,n)=>(0,rN.OpenIdJwtInboundPolicy)(t,e,{issuer:`https://${r.auth0Domain}/`,audience:r.audience,jwkUrl:`https://${r.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"Auth0JwtInboundPolicy");oc.Auth0JwtInboundPolicy=nN});var O_=_(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});sc.BasicAuthInboundPolicy=void 0;var iN=de(),oN=o(async(t,e,r)=>{let n=t.headers.get("Authorization"),i="basic ",s=o(l=>iN.HttpProblems.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),c=await o(async()=>{if(!n)return await s("No Authorization header");if(n.toLowerCase().indexOf(i)!==0)return await s("Invalid Basic token format for Authorization header");let l=n.substring(i.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),h=d.substring(p+1),y=r.accounts.find(b=>b.username===f&&b.password===h);return y||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(c instanceof Response)return r.allowUnauthenticatedRequests?t:c;let u=c.username;return t.user={sub:u,data:c.data},t},"BasicAuthInboundPolicy");sc.BasicAuthInboundPolicy=oN});var N_=_(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});ac.CachingInboundPolicy=void 0;var sN=Zt(),aN=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function cN(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}o(cN,"digestMessage");var uN=o(async(t,e)=>{let r=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],n=[];for(let[d,p]of t.headers.entries())r.includes(d)&&n.push({key:d.toLowerCase(),value:p});n.sort((d,p)=>d.key.localeCompare(p.key));let i=await cN(JSON.stringify(n)),s=new URL(t.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",i);let c=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";c&&a.set("_z-original-method",t.method);let u=`${s.origin}${s.pathname}?${a}`;return new Request(u,{method:c?"GET":t.method})},"createCacheKeyRequest");async function lN(t,e,r,n){let i=await(0,sN.getPolicyCacheName)(n,r),s=await caches.open(i),a=r?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],c=await uN(t,r),u=await s.match(c);return u||(e.addEventListener("responseSent",l=>{try{let d=r.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let f=r?.expirationSecondsTtl??60,h=new Response(p.body,p);aN.forEach(y=>h.headers.delete(y)),h.headers.set("cache-control",`s-maxage=${f}`),e.waitUntil(s.put(c,h))}catch(d){e.log.error(`Error in caching-inbound-policy '${n}': "${d.message}"`,d)}}),t)}o(lN,"CachingInboundPolicy");ac.CachingInboundPolicy=lN});var C_=_(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});cc.ChangeMethodInboundPolicy=void 0;var dN=k(),pN=Ke(),fN=o(async(t,e,r,n)=>{if(!r.method)throw new dN.ConfigurationError(`ChangeMethodInboundPolicy '${n}' options.method must be valid HttpMethod`);return new pN.ZuploRequest(t,{method:r.method})},"ChangeMethodInboundPolicy");cc.ChangeMethodInboundPolicy=fN});var x_=_(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});uc.ClearHeadersInboundPolicy=void 0;var hN=Ke(),mN=o(async(t,e,r)=>{let n=[...r.exclude??[]],i=new Headers;return n.forEach(a=>{let c=t.headers.get(a);c&&i.set(a,c)}),new hN.ZuploRequest(t,{headers:i})},"ClearHeadersInboundPolicy");uc.ClearHeadersInboundPolicy=mN});var L_=_(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});lc.ClearHeadersOutboundPolicy=void 0;var yN=o(async(t,e,r,n)=>{let i=[...n.exclude??[]],s=new Headers;return i.forEach(c=>{let u=t.headers.get(c);u&&s.set(c,u)}),new Response(t.body,{headers:s,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");lc.ClearHeadersOutboundPolicy=yN});var D_=_(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});dc.ClerkJwtInboundPolicy=void 0;var gN=Xt(),bN=o(async(t,e,r,n)=>{let i=new URL(r.frontendApiUrl.startsWith("https://")||r.frontendApiUrl.startsWith("http://")?r.frontendApiUrl:`https://${r.frontendApiUrl}`),s=new URL(i);return s.pathname="/.well-known/jwks.json",(0,gN.OpenIdJwtInboundPolicy)(t,e,{issuer:i.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"ClerkJwtInboundPolicy");dc.ClerkJwtInboundPolicy=bN});var U_=_(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});pc.CognitoJwtInboundPolicy=void 0;var M_=k(),_N=Xt(),EN=o(async(t,e,r,n)=>{if(!r.userPoolId)throw new M_.ConfigurationError("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!r.region)throw new M_.ConfigurationError("region must be set in the options for CognitoJwtInboundPolicy");return(0,_N.OpenIdJwtInboundPolicy)(t,e,{issuer:`https://cognito-idp.${r.region}.amazonaws.com/${r.userPoolId}`,jwkUrl:`https://cognito-idp.${r.region}.amazonaws.com/${r.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"CognitoJwtInboundPolicy");pc.CognitoJwtInboundPolicy=EN});var F_=_(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});fc.CompositeInboundPolicy=void 0;var wN=k(),vN=qr(),k_=En(),TN=o(async(t,e,r,n)=>{if(!r.policies||r.policies.length===0)throw new wN.ConfigurationError(`CompositeInboundPolicy '${n}' must have valid policies defined`);let i=vN.Gateway.instance,s=(0,k_.getInboundPolicyInstances)(r.policies,i?.routeData.policies);return(0,k_.toStackedInboundHandler)(s)(t,e)},"CompositeInboundPolicy");fc.CompositeInboundPolicy=TN});var H_=_(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});mc.CurityPhantomTokenInboundPolicy=void 0;var SN=Zt(),IN=Bt(),hc=de(),PN=o(async(t,e,r,n)=>{let i=t.headers.get("Authorization");if(!i)return hc.HttpProblems.unauthorized(t,e,{detail:"No authorization header"});let s=AN(i);if(!s)return hc.HttpProblems.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await(0,SN.getPolicyCacheName)(n,r),c=new IN.MemoryZoneReadThroughCache(a,e),u=await c.get(s);if(!u){let l=await fetch(r.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${r.clientId}:${r.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)u=d,c.put(s,u,r.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),hc.HttpProblems.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):hc.HttpProblems.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${u}`),t},"CurityPhantomTokenInboundPolicy");mc.CurityPhantomTokenInboundPolicy=PN;function AN(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}o(AN,"getToken")});var q_=_(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});yc.FirebaseJwtInboundPolicy=void 0;var RN=lt(),ON=Xt(),NN=o(async(t,e,r,n)=>((0,RN.optionValidator)(r,n).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),(0,ON.OpenIdJwtInboundPolicy)(t,e,{issuer:`https://securetoken.google.com/${r.projectId}`,audience:r.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)),"FirebaseJwtInboundPolicy");yc.FirebaseJwtInboundPolicy=NN});var $_=_(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});gc.FormDataToJsonInboundPolicy=void 0;var CN=Ke(),xN=o(async(t,e,r)=>{let n="application/x-www-form-urlencoded",i="multipart/form-data",s=t.headers.get("content-type")?.toLowerCase();if(!s||![i,n].includes(s))return r&&r.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${n}' or ${i}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(r&&r.optionalHoneypotName&&a.get(r.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let c={};for(let[d,p]of a)c[d]=p.toString();let u=new Headers(t.headers);return u.set("content-type","application/json"),u.delete("content-length"),new CN.ZuploRequest(t,{body:JSON.stringify(c),headers:u})},"FormDataToJsonInboundPolicy");gc.FormDataToJsonInboundPolicy=xN});var j_=_(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});bc.GeoFilterInboundPolicy=void 0;var LN=k(),DN=de(),oi="__unknown__",MN=o(async(t,e,r,n)=>{let i={allow:{countries:ai(r.allow?.countries,"allow.countries",n),regionCodes:ai(r.allow?.regionCodes,"allow.regionCode",n),asns:ai(r.allow?.asns,"allow.asOrganization",n)},block:{countries:ai(r.block?.countries,"block.countries",n),regionCodes:ai(r.block?.regionCodes,"block.regionCode",n),asns:ai(r.block?.asns,"block.asOrganization",n)},ignoreUnknown:r.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??oi,a=e.incomingRequestProperties.regionCode?.toLowerCase()??oi,c=e.incomingRequestProperties.asn?.toString()??oi,u=i.ignoreUnknown&&s===oi,l=i.ignoreUnknown&&a===oi,d=i.ignoreUnknown&&c===oi,p=i.allow.countries,f=i.allow.regionCodes,h=i.allow.asns;if(p.length>0&&!p.includes(s)&&!u||f.length>0&&!f.includes(a)&&!l||h.length>0&&!h.includes(c)&&!d)return si(t,e,n,s,a,c);let y=i.block.countries,b=i.block.regionCodes,I=i.block.asns;return y.length>0&&y.includes(s)&&!u||b.length>0&&b.includes(a)&&!l||I.length>0&&I.includes(c)&&!d?si(t,e,n,s,a,c):t},"GeoFilterInboundPolicy");bc.GeoFilterInboundPolicy=MN;function si(t,e,r,n,i,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${r}' (country: '${n}', regionCode: '${i}', asn: '${s}')`),DN.HttpProblems.forbidden(t,e,{geographicContext:{country:n,regionCode:i,asn:s}})}o(si,"blockedResponse");function ai(t,e,r){if(typeof t=="string")return t.split(",").map(n=>n.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(n=>n.trim().toLowerCase());throw new LN.ConfigurationError(`Invalid '${e}' for GeoFilterInboundPolicy '${r}': '${t}', must be a string or string[]`)}o(ai,"toLowerStringArray")});var V_=_(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});_c.JWTScopeValidationInboundPolicy=void 0;var UN=o(async(t,e,r)=>{let n=t.user?.data.scope.split(" ")||[];if(!o((s,a)=>a.every(c=>s.includes(c)),"scopeChecker")(n,r.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${r.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");_c.JWTScopeValidationInboundPolicy=UN});var G_=_(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});Ec.MockApiInboundPolicy=void 0;var kN=de(),FN=o(async(t,e,r,n)=>{let i=e.route.raw().responses;if(!i)return xf(n,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(i),a=[];if(s.length===0)return xf(n,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(c=>{i[c].content&&Object.keys(i[c].content).forEach(l=>{let d=i[c].content[l].examples;d&&Object.keys(d).forEach(f=>{a.push({responseName:c,contentName:l,exampleName:f,exampleValue:d[f]})})})}),a=a.filter(c=>!(r.responsePrefixFilter&&!c.responseName.startsWith(r.responsePrefixFilter)||r.contentType&&c.contentName!==r.contentType||r.exampleName&&c.exampleName!==r.exampleName)),r.random&&a.length>1){let c=Math.floor(Math.random()*a.length);return B_(a[c])}else return a.length>0?B_(a[0]):xf(n,t,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");Ec.MockApiInboundPolicy=FN;function B_(t){let e=JSON.stringify(t.exampleValue,null,2),r=new Headers;switch(r.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:r});case"2XX":return new Response(e,{status:200,headers:r});case"3XX":return new Response(e,{status:300,headers:r});case"4XX":return new Response(e,{status:400,headers:r});case"5XX":case"default":return new Response(e,{status:500,headers:r});default:return new Response(e,{status:Number(t.responseName),headers:r})}}o(B_,"generateResponse");var xf=o((t,e,r,n)=>{let i=`Error in policy: ${t} - On route ${e.method} ${r.route.path}. ${n}`;return kN.HttpProblems.internalServerError(e,r,{detail:i})},"getProblemDetailResponse")});var Q_=_(ci=>{"use strict";Object.defineProperty(ci,"__esModule",{value:!0});ci.MoesifInboundPolicy=ci.setMoesifContext=void 0;var HN=k(),qN=Re(),$N="Incoming",jN={logRequestBody:!0,logResponseBody:!0};function K_(t){let e={};return t.forEach((r,n)=>{e[n]=r}),e}o(K_,"headersToObject");function J_(){return new Date().toISOString()}o(J_,"timestamp");var Lf=new WeakMap,VN={};function BN(t,e){let r=Lf.get(t);r||(r=VN);let n=Object.assign({...r},e);Lf.set(t,n)}o(BN,"setMoesifContext");ci.setMoesifContext=BN;async function z_(t,e){let r=t.headers.get("content-type");if(r&&r.indexOf("json")!==0)try{return await t.clone().json()}catch(i){e.log.error(i)}let n=await t.clone().text();return e.log.debug({textBody:n}),n}o(z_,"readBody");var GN={},Df;function W_(){if(!Df)throw new HN.RuntimeError("Invalid State - no _lastLogger");return Df}o(W_,"getLastLogger");function KN(t){let e=GN[t];return e||(e=new qN.BatchDispatch("moesif-inbound",100,async r=>{let n=JSON.stringify(r);W_().debug("posting",n);let i=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:n});i.ok||W_().error({status:i.status,body:await i.text()})})),e}o(KN,"getDispatcher");async function JN(t,e,r,n){Df=e.log;let i=J_(),s=Object.assign(jN,r);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${n}' - applicationId is required`);let a=s.logRequestBody?await z_(t,e):void 0;return e.addResponseSendingFinalHook(async(c,u)=>{let l=KN(s.applicationId),d=t.headers.get("true-client-ip"),p=Lf.get(e)??{},f={time:i,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:K_(t.headers)},h=s.logResponseBody?await z_(c,e):void 0,y={time:J_(),status:c.status,headers:K_(c.headers),body:h},b={request:f,response:y,user_id:p.userId??u.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:$N};l.enqueue(b),e.waitUntil(l.waitUntilFlushed())}),t}o(JN,"MoesifInboundPolicy");ci.MoesifInboundPolicy=JN});var X_=_(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});ui.consumeSubcriptionQuotas=ui.loadSubscription=void 0;var Y_=Je(),Z_=ie();async function zN(t,e,r,n){let i=Y_.SystemLogMap.getLogger(t),{authApiJWT:s,meteringServiceUrl:a}=Z_.Environment.instance,c;try{let l=await fetch(`${a}/internal/v1/metering/${n}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.requestId},method:"GET"});if(l.ok)c=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${r}' - Error loading subscription. ${l.status} - ${p}`),i.error(`MonetizationInboundPolicy '${r}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){i.error(`MonetizationInboundPolicy '${r}' - Error loading subscription`,l)}return c&&c.data&&c.data.length>0?c.data[0]:void 0}o(zN,"loadSubscription");ui.loadSubscription=zN;async function WN(t,e,r,n,i){let{authApiJWT:s,meteringServiceUrl:a}=Z_.Environment.instance,c=Y_.SystemLogMap.getLogger(t);try{let u=await fetch(`${a}/internal/v1/metering/${n}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.requestId},method:"POST",body:JSON.stringify({meters:i})});if(!u.ok){let l=await u.json(),d=l.detail??l.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota. ${u.status} - ${d}`),c.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota. ${u.status} - ${d}`)}}catch(u){t.log.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota.`),c.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota.`,u)}}o(WN,"consumeSubcriptionQuotas");ui.consumeSubcriptionQuotas=WN});var eE=_(Nr=>{"use strict";Object.defineProperty(Nr,"__esModule",{value:!0});Nr.compareMeters=Nr.parseAllowedSubscriptionStatuses=Nr.validateMeters=void 0;var tn=k(),QN=Jt(),YN=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function ZN(t,e){try{let r=[];for(let n in t)typeof t[n]!="number"&&!(Number.isInteger(t[n])&&/^-?\d+$/.test(t[n].toString()))&&r.push(n);if(r.length>0)throw new tn.ConfigurationError(r.length>1?`The values found in these properties are not integers : ${r.join(", ")}`:`The value in property '${r[0]}' is not an integer`)}catch(r){throw r instanceof tn.ConfigurationError?new tn.ConfigurationError(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${r.message}`):r}}o(ZN,"validateMeters");Nr.validateMeters=ZN;function XN(t,e){if(t)try{if(t.length===0)throw new tn.ConfigurationError("Must set valid subscription statuses");let r=(0,QN.parseValueToStringArray)(t),n=[];for(let i of r)YN.has(i)||n.push(i);if(n.length>0)throw new tn.ConfigurationError(`Found the following invalid statuses: ${n.join(", ")}`);return t}catch(r){throw r instanceof tn.ConfigurationError?new tn.ConfigurationError(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${r.message}`):r}else return["active","incomplete","trialing"]}o(XN,"parseAllowedSubscriptionStatuses");Nr.parseAllowedSubscriptionStatuses=XN;function eC(t,e){let r={},n={};for(let i in e)t.hasOwnProperty(i)?r[i]=e[i]:n[i]=e[i];return{metersInSubscription:r,metersNotInSubscription:n}}o(eC,"compareMeters");Nr.compareMeters=eC});var nE=_(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});vc.MonetizationInboundPolicy=void 0;var rn=Fr(),nn=_p(),wc=Yi(),tE=k(),tC=_n(),on=de(),rC=Jt(),nC=lt(),rE=X_(),io=eE(),Mf=class extends tC.InboundPolicy{static{o(this,"MonetizationInboundPolicy")}static getSubscription(e){return nn.ContextData.get(e,rn.METERING_SUBSCRIPTION_CONTEXT_DATA)}static setMeters(e,r){(0,io.validateMeters)(r,"setMeters"),nn.ContextData.set(e,rn.DYNAMIC_METERS_CONTEXT_DATA,r)}async handler(e,r){(0,nC.optionValidator)(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,i=(0,rC.statusCodesStringToNumberArray)(this.options.meterOnStatusCodes),s=nn.ContextData.get(r,rn.DYNAMIC_METERS_CONTEXT_DATA),a={...this.options.meters,...s};(0,io.validateMeters)(a,this.policyName);let c=this.options.allowRequestsWithoutSubscription??!1,u=(0,io.parseAllowedSubscriptionStatuses)(this.options.allowedSubscriptionStatuses,this.policyName);r.addResponseSendingFinalHook(async(b,I,A)=>{let g=nn.ContextData.get(A,rn.METERING_SUBSCRIPTION_CONTEXT_DATA);if((this.options.allowRequestsWithoutSubscription??!1)&&!g){A.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(wc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=wc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new tE.ConfigurationError(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let O=nn.ContextData.get(A,rn.DYNAMIC_METERS_CONTEXT_DATA),V={...this.options.meters,...O};if((0,io.validateMeters)(V,this.policyName),i.includes(b.status)&&g&&V){A.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${g.id}' with meters '${JSON.stringify(V)} on response status '${b.status}'`);let{metersInSubscription:E,metersNotInSubscription:T}=(0,io.compareMeters)(g.meters,V);if(T&&Object.keys(T).length>0){let C=Object.keys(T);A.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${C}'`)}await(0,rE.consumeSubcriptionQuotas)(A,g.id,this.policyName,this.options.bucketId,E)}});let l=e.user;if(!l)return c?e:on.HttpProblems.unauthorized(e,r,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(wc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=wc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new tE.ConfigurationError(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await(0,rE.loadSubscription)(r,d,this.policyName,this.options.bucketId);if(!p)return r.log.warn("No valid subscription found"),c?e:on.HttpProblems.unauthorized(e,r,{detail:"No valid subscription found"});if(!u.includes(p.status)&&!c)return r.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),on.HttpProblems.unauthorized(e,r,{detail:"No valid subscription found"});u.includes(p.status)&&(r.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),nn.ContextData.set(r,rn.METERING_SUBSCRIPTION_CONTEXT_DATA,p));let f=nn.ContextData.get(r,rn.METERING_SUBSCRIPTION_CONTEXT_DATA);if(!f)return c?e:(r.log.warn("Subscription is not available for user"),on.HttpProblems.paymentRequired(e,r,{detail:"Subscription is not available for user",title:"No Subscription"}));if(f&&Object.keys(f.meters).length===0)return r.log.error(`Quota is not set up for subscription '${f.id}'`),on.HttpProblems.tooManyRequests(e,r,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let y=Object.keys(a).filter(b=>!Object.keys(f.meters).includes(b));if(y.length>0)return r.log.warn(`The following policy meters are not present in the subscription: ${y.join(", ")}`),on.HttpProblems.tooManyRequests(e,r,{detail:`The following policy meters are not present in the subscription: ${y.join(", ")}`,title:"Quota Exceeded"});for(let b of Object.keys(a))if(f.meters[b].consumed<=0&&!n)return on.HttpProblems.tooManyRequests(e,r,{detail:`Quota exceeded for meter '${b}'`,title:"Quota Exceeded"});return e}};vc.MonetizationInboundPolicy=Mf});var iE=_(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});Tc.OktaJwtInboundPolicy=void 0;var iC=Xt(),oC=o(async(t,e,r,n)=>(0,iC.OpenIdJwtInboundPolicy)(t,e,{issuer:r.issuerUrl,audience:r.audience,jwkUrl:`${r.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"OktaJwtInboundPolicy");Tc.OktaJwtInboundPolicy=oC});var oE=_(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});Sc.PropelAuthJwtInboundPolicy=void 0;var sC=(ra(),xo(ta)),aC=Xt(),Uf,cC=o(async(t,e,r,n)=>{if(!Uf)try{Uf=await(0,sC.importSPKI)(r.verifierKey,"RS256")}catch(i){throw e.log.error("Could not import verifier key"),i}return(0,aC.OpenIdJwtInboundPolicy)(t,e,{issuer:r.authUrl,secret:Uf,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests,subPropertyName:"user_id"},n)},"PropelAuthJwtInboundPolicy");Sc.PropelAuthJwtInboundPolicy=cC});var sE=_(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.throwIfStateNotObject=Z.throwIfStateNotNumber=Z.throwIfStateNotString=Z.throwIfStateUndefinedOrNull=Z.throwIfStateUndefined=Z.throwIfOptionNotObject=Z.throwIfOptionNotNumber=Z.throwIfOptionNotString=Z.throwIfOptionUndefinedOrNull=Z.throwIfOptionUndefined=Z.OptionTypeError=Z.OptionUndefinedError=Z.throwIfNotNumber=Z.throwIfNotString=Z.throwIfUndefinedOrNull=Z.throwIfUndefined=Z.ArgumentTypeError=Z.ArgumentUndefinedError=Z.ValidationError=void 0;var Ye=at(),dt=class extends Error{static{o(this,"ValidationError")}constructor(e){super(e)}};Z.ValidationError=dt;var oo=class extends dt{static{o(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}};Z.ArgumentUndefinedError=oo;var so=class extends dt{static{o(this,"ArgumentTypeError")}constructor(e,r){super(`The argument '${e}' must be of type '${r}'.`)}};Z.ArgumentTypeError=so;function uC(t,e){if((0,Ye.isUndefined)(t))throw new oo(e)}o(uC,"throwIfUndefined");Z.throwIfUndefined=uC;function kf(t,e){if((0,Ye.isUndefinedOrNull)(t))throw new oo(e)}o(kf,"throwIfUndefinedOrNull");Z.throwIfUndefinedOrNull=kf;function lC(t,e){if(kf(t,e),!(0,Ye.isString)(t))throw new so(e,"string")}o(lC,"throwIfNotString");Z.throwIfNotString=lC;function dC(t,e){if(kf(t,e),!(0,Ye.isNumber)(t))throw new so(e,"number")}o(dC,"throwIfNotNumber");Z.throwIfNotNumber=dC;var ao=class extends dt{static{o(this,"OptionUndefinedError")}constructor(e,r,n){super(`The option '${n}' on the ${e} named '${r}' is undefined.`)}};Z.OptionUndefinedError=ao;var li=class extends dt{static{o(this,"OptionTypeError")}constructor(e,r,n,i){super(`The option '${n}' on the ${e} named '${r}' must be of type '${i}'.`)}};Z.OptionTypeError=li;function pC(t,e,r,n){if((0,Ye.isUndefined)(n))throw new ao(t,e,r)}o(pC,"throwIfOptionUndefined");Z.throwIfOptionUndefined=pC;function Ic(t,e,r,n){if((0,Ye.isUndefinedOrNull)(n))throw new ao(t,e,r)}o(Ic,"throwIfOptionUndefinedOrNull");Z.throwIfOptionUndefinedOrNull=Ic;function fC(t,e,r,n){if(Ic(t,e,r,n),!(0,Ye.isString)(n))throw new li(t,e,r,"string")}o(fC,"throwIfOptionNotString");Z.throwIfOptionNotString=fC;function hC(t,e,r,n){if(Ic(t,e,r,n),!(0,Ye.isNumber)(n))throw new li(t,e,r,"number")}o(hC,"throwIfOptionNotNumber");Z.throwIfOptionNotNumber=hC;function mC(t,e,r,n){if(Ic(t,e,r,n),!(0,Ye.isObject)(n))throw new li(t,e,r,"object")}o(mC,"throwIfOptionNotObject");Z.throwIfOptionNotObject=mC;function yC(t,e){if((0,Ye.isUndefined)(t))throw new dt(e)}o(yC,"throwIfStateUndefined");Z.throwIfStateUndefined=yC;function Pc(t,e){if((0,Ye.isUndefinedOrNull)(t))throw new dt(e)}o(Pc,"throwIfStateUndefinedOrNull");Z.throwIfStateUndefinedOrNull=Pc;function gC(t,e){if(Pc(t,e),!(0,Ye.isString)(t))throw new dt(e);return!0}o(gC,"throwIfStateNotString");Z.throwIfStateNotString=gC;function bC(t,e){if(Pc(t,e),!(0,Ye.isNumber)(t))throw new dt(e);return!0}o(bC,"throwIfStateNotNumber");Z.throwIfStateNotNumber=bC;function _C(t,e){if(Pc(t,e),!(0,Ye.isObject)(t))throw new dt(e);return!0}o(_C,"throwIfStateNotObject");Z.throwIfStateNotObject=_C});var aE=_(di=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});di.InMemoryRedisClient=di.StandardRedisClient=void 0;var Ff=k(),Ac=sE(),Hf=class t{static{o(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,r,n,i){this.redisClientUrl=e,this.clientAuthToken=r,this.deploymentName=n,this.userAgent=i}static initialize(e,r,n,i){return(0,Ac.throwIfNotString)(e,"redisClientUrl"),(0,Ac.throwIfNotString)(r,"clientAuthToken"),t.instance||(t.instance=new t(e,r,n,i)),t.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:r,method:n,requestId:i}){(0,Ac.throwIfNotString)(e,"url");let s=await fetch(`${this.redisClientUrl}${e}`,{method:n,body:r,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":i,"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 Ff.SystemError("Redis client failed with 401: Unauthorized"):new Ff.SystemError(`Redis client failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}};di.StandardRedisClient=Hf;var qf=class{static{o(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:r,method:n}){if((0,Ac.throwIfNotString)(e,"url"),n==="POST"&&e==="/rate-limit"){let{incrBy:i,expire:s,key:a}=JSON.parse(r),c=Date.now()+s*1e3,u=this.keyValueStore.get(a);u?Date.now()>u.expiresAt?this.keyValueStore.set(a,{value:i,expiresAt:c}):this.keyValueStore.set(a,{value:u.value+i,expiresAt:u.expiresAt}):this.keyValueStore.set(a,{value:i,expiresAt:c});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new Ff.SystemError("The in-memory redis client only supports /rate-limit calls")}};di.InMemoryRedisClient=qf});var $f=_(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.RETRY_AFTER_HEADER=Ae.wrapUserFunction=Ae.getCountAndUpdateExpiry=Ae.getRedisClient=Ae.getAll=Ae.getUser=Ae.getIP=Ae.getRealIP=void 0;var Cr=k(),Rc=ie(),cE=aE(),uE=at(),EC=o(t=>{let e=t.headers.get("x-real-ip")??t.headers.get("true-client-ip")??t.headers.get("cf-connecting-ip");if(e)return e;let r=t.headers.get("x-forwarded-for");return r?r.split(",")[0]:"127.0.0.1"},"getRealIP");Ae.getRealIP=EC;var wC=o(async t=>({key:`ip-${(0,Ae.getRealIP)(t)}`}),"getIP");Ae.getIP=wC;var vC=o(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser");Ae.getUser=vC;var TC=o(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll");Ae.getAll=TC;var Oc;function SC(t,e){let r;if(Oc)return Oc;if(Rc.Environment.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),r=new cE.InMemoryRedisClient,Oc=r,r;let{authApiJWT:n,redisURL:i}=Rc.Environment.instance;if(!(0,uE.isString)(i))throw new Cr.SystemError(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!(0,uE.isString)(n))throw new Cr.SystemError(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(i&&(r=cE.StandardRedisClient.initialize(i,n,Rc.Environment.instance.deploymentName??"unknown",Rc.Environment.instance.systemUserAgent)),!r||!r.isEnabled())throw new Cr.SystemError(`RateLimitInboundPolicy '${t}' - no redis ('${r}') or redis.isEnabled ('${r?.isEnabled}) is false`);return Oc=r,r}o(SC,"getRedisClient");Ae.getRedisClient=SC;async function IC(t,e,r,n,i){let s=Math.floor(e*60);return await r.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:s,key:t}),requestId:i})}o(IC,"getCountAndUpdateExpiry");Ae.getCountAndUpdateExpiry=IC;function PC(t,e){let r;if(t.rateLimitBy==="function"){if(!t.identifier)throw new Cr.ConfigurationError(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new Cr.ConfigurationError(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new Cr.ConfigurationError(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=t.identifier.module[t.identifier.export],!r||typeof r!="function")throw new Cr.ConfigurationError(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return o(async(i,s,a)=>{let c=await r(i,s,a);if(!c.key){let u=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(c,null,2)}'`;throw s.log.error(u),new Cr.RuntimeError(u)}return c},"outerFunction")}o(PC,"wrapUserFunction");Ae.wrapUserFunction=PC;Ae.RETRY_AFTER_HEADER="Retry-After"});var dE=_(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});Nc.AsyncRateLimitInboundPolicy=void 0;var AC=or(),RC=Zt(),OC=de(),NC=Je(),CC=ie(),xC=Bt(),sn=$f(),lE=(0,AC.debug)("zuplo:policies:RateLimitInboundPolicy"),LC=o(async(t,e,r,n)=>{let i=NC.SystemLogMap.getLogger(e),s=o((E,T)=>{let C={};return(!E||E==="retry-after")&&(C[sn.RETRY_AFTER_HEADER]=T.toString()),OC.HttpProblems.tooManyRequests(t,e,void 0,C)},"rateLimited"),c={function:(0,sn.wrapUserFunction)(r,n),user:sn.getUser,ip:sn.getIP,all:sn.getAll}[r.rateLimitBy],u=await c(t,e,n),l=u.key,d=u.requestsAllowed??r.requestsAllowed,p=u.timeWindowMinutes??r.timeWindowMinutes,f=r.headerMode??"retry-after",h=(0,sn.getRedisClient)(n,i),b=`bucket/${CC.Environment.instance.build.BUILD_ID}/${n}/${l}`,I=await(0,RC.getPolicyCacheName)(n,r),A=new xC.MemoryZoneReadThroughCache(I,e),g=(0,sn.getCountAndUpdateExpiry)(b,p,h,i,e.requestId),v;o(async()=>{let E=await g;if(E.count>d){let T=Date.now()+E.ttlSeconds*1e3;A.put(b,T,E.ttlSeconds),lE(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${b}' (async mode)`),v=s(f,E.ttlSeconds)}},"asyncCheck")();let V=await A.get(b);if(V!==void 0&&V>Date.now()){lE(`RateLimitInboundPolicy '${n}' - returning 429 from cache for '${b}' (async mode)`);let E=Math.round((V-Date.now())/1e3);return s(f,E)}return e.addResponseSendingHook(async E=>v??E),t},"AsyncRateLimitInboundPolicy");Nc.AsyncRateLimitInboundPolicy=LC});var fE=_(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});Cc.RateLimitInboundPolicy=void 0;var DC=or(),MC=k(),UC=de(),kC=Je(),FC=ie(),HC=dE(),an=$f(),pE=(0,DC.debug)("zuplo:policies:RateLimitInboundPolicy"),qC="strict",$C=o(async(t,e,r,n)=>{if((r.mode??qC)==="async")return(0,HC.AsyncRateLimitInboundPolicy)(t,e,r,n);let s=Date.now(),a=kC.SystemLogMap.getLogger(e),c=o((l,d)=>{if(r.throwOnFailure)throw new MC.SystemError(l,{cause:d});a.error(l,d)},"throwOrLog"),u=o((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[an.RETRY_AFTER_HEADER]=d.toString()),UC.HttpProblems.tooManyRequests(t,e,void 0,p)},"rateLimited");try{let d={function:(0,an.wrapUserFunction)(r,n),user:an.getUser,ip:an.getIP,all:an.getAll}[r.rateLimitBy],p=await d(t,e,n),f=p.key,h=p.requestsAllowed??r.requestsAllowed,y=p.timeWindowMinutes??r.timeWindowMinutes,b=r.headerMode??"retry-after",I=(0,an.getRedisClient)(n,a),g=`bucket/${FC.Environment.instance.build.BUILD_ID}/${n}/${f}`,v=await(0,an.getCountAndUpdateExpiry)(g,y,I,a,e.requestId);return v.count>h?(pE(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${g}' (strict mode)`),u(b,v.ttlSeconds)):t}catch(l){return c(l.message,l),t}finally{let l=Date.now()-s;pE(`RateLimitInboundPolicy '${n}' - latency ${l}ms`)}},"RateLimitInboundPolicy");Cc.RateLimitInboundPolicy=$C});var gE=_(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});xc.ReadmeMetricsInboundPolicy=void 0;var jC=Re(),jf=ie(),hE=Jt(),Vf;function mE(t){let e=[];for(let[r,n]of t)e.push({name:r,value:n});return e}o(mE,"headersToNameValuePairs");function VC(t){let e=[];return Object.entries(t).forEach(([r,n])=>{e.push({name:r,value:n})}),e}o(VC,"queryToNameValueParis");function BC(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}o(BC,"parseIntOrUndefined");var yE={};async function GC(t,e,r,n){let i=new Date,s=Date.now();return Vf||(Vf={name:"zuplo",version:jf.Environment.instance.build.ZUPLO_VERSION,comment:`zuplo/${jf.Environment.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let c=r.userLabelPropertyPath&&t.user?(0,hE.getValueFromRequestUser)(t.user,r.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,u=r.userEmailPropertyPath&&t.user?(0,hE.getValueFromRequestUser)(t.user,r.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:r.development!==void 0?r.development:jf.Environment.instance.isDeno,group:{label:c,email:u,id:t.user?.sub??"anonymous"},request:{log:{creator:Vf,entries:[{startedDateTime:i.toISOString(),time:Date.now()-s,request:{method:t.method,url:r.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:mE(t.headers),queryString:VC(t.query)},response:{status:a.status,statusText:a.statusText,headers:mE(a.headers),content:{size:BC(t.headers.get("content-length"))}}}]}}},d=yE[r.apiKey];if(!d){let p=r.apiKey;d=new jC.BatchDispatch("readme-metering-inbound-policy",10,async f=>{try{let h=r.url??"https://metrics.readme.io/request",y=await fetch(h,{method:"POST",body:JSON.stringify(f),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});y.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${n}'. ${y.status}: '${await y.text()}'`)}catch(h){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${n}': '${h.message}'`),h}}),yE[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(c){e.log.error(c)}}),t}o(GC,"ReadmeMetricsInboundPolicy");xc.ReadmeMetricsInboundPolicy=GC});var bE=_(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});Lc.RemoveHeadersInboundPolicy=void 0;var KC=k(),JC=Ke(),zC=o(async(t,e,r,n)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new KC.ConfigurationError(`RemoveHeadersInboundPolicy '${n}' options.headers must be a non-empty string array of header names`);let s=new Headers(t.headers);return i.forEach(c=>{s.delete(c)}),new JC.ZuploRequest(t,{headers:s})},"RemoveHeadersInboundPolicy");Lc.RemoveHeadersInboundPolicy=zC});var _E=_(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});Dc.RemoveHeadersOutboundPolicy=void 0;var WC=k(),QC=o(async(t,e,r,n,i)=>{let s=n?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new WC.ConfigurationError(`RemoveHeadersOutboundPolicy '${i}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return s.forEach(u=>{a.delete(u)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");Dc.RemoveHeadersOutboundPolicy=QC});var EE=_(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});Mc.RemoveQueryParamsInboundPolicy=void 0;var YC=k(),ZC=Ke(),XC=o(async(t,e,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length===0)throw new YC.ConfigurationError(`RemoveQueryParamsInboundPolicy '${n}' options.params must be a non-empty string array of header names`);let s=new URL(t.url);return i.forEach(c=>{s.searchParams.delete(c)}),new ZC.ZuploRequest(s.toString(),t)},"RemoveQueryParamsInboundPolicy");Mc.RemoveQueryParamsInboundPolicy=XC});var wE=_(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});Uc.ReplaceStringOutboundPolicy=void 0;var ex=o(async(t,e,r,n)=>{let i=await t.text(),s=n.mode==="regexp"?new RegExp(n.match,"gm"):n.match,a=i.replaceAll(s,n.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");Uc.ReplaceStringOutboundPolicy=ex});var TE=_(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});kc.RequestSizeLimitInboundPolicy=void 0;var vE=o(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),tx=o(async(t,e,r)=>{let n=r.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let i=t.headers.get("content-length"),s=i!==null?parseInt(i):void 0;return s&&!isNaN(s)&&s>r.maxSizeInBytes?vE():s&&n?t:(await t.clone().text()).length>r.maxSizeInBytes?vE():t},"RequestSizeLimitInboundPolicy");kc.RequestSizeLimitInboundPolicy=tx});var Fc=_(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.sanitizedIdentifierName=pt.getIdForRefSchema=pt.getIdForRequestBodySchema=pt.getIdForParameterSchema=pt.getRawOperationDataIdentifierName=void 0;function rx(t,e,r){return`_${cn(t+"_"+e+"_"+r)}`}o(rx,"getRawOperationDataIdentifierName");pt.getRawOperationDataIdentifierName=rx;function nx(t,e,r,n){return`_${cn(t.toLowerCase())}_`+e.toLowerCase()+"_"+r.toLowerCase()+`_${n.toLowerCase()}`}o(nx,"getIdForParameterSchema");pt.getIdForParameterSchema=nx;function ix(t,e,r){return`_${cn(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${cn(r.toLowerCase())}`}o(ix,"getIdForRequestBodySchema");pt.getIdForRequestBodySchema=ix;function ox(t,e){return`_${cn(t)}__${cn(e)}`}o(ox,"getIdForRefSchema");pt.getIdForRefSchema=ox;function cn(t){let e=[];for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);n>="0".charCodeAt(0)&&n<="9".charCodeAt(0)||n>="A".charCodeAt(0)&&n<="Z".charCodeAt(0)||n>="a".charCodeAt(0)&&n<="z".charCodeAt(0)?e.push(t.charAt(r)):e.push("_")}return e.join("")}o(cn,"sanitizedIdentifierName");pt.sanitizedIdentifierName=cn});var co=_(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.getErrorsFromValidator=je.shouldReject=je.shouldLog=je.logErrors=je.validateParameters=je.getParametersForOperation=void 0;var sx=qr(),ax=Fc(),cx=o(t=>{let e=t.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");je.getParametersForOperation=cx;var ux=o((t,e,r,n,i)=>{let s=[],a=!0,c=[];return t.forEach(u=>{let l=u.required||i==="path";if(l&&!e[u.name])a=!1,s.push(`Required ${i} parameter '${u.name}' not found`);else if(!(!l&&!e[u.name])){let d=(0,ax.getIdForParameterSchema)(r,n,i,u.name),p=sx.Gateway.instance.schemaValidator[d],f=p(e[u.name]),h=(0,je.getErrorsFromValidator)(p.errors);f||(a=!1,c.push(`${i} parameter: ${u.name} : ${e[u.name]}`),s.push(`Invalid value for ${i} parameter: '${u.name}' ${h.join(", ")}`))}}),{isValid:a,invalidValues:c,errors:s}},"validateParameters");je.validateParameters=ux;var lx=o((t,e,r,n,i)=>{n?t.log[e](r,n,i):t.log[e](r,i)},"logErrors");je.logErrors=lx;var dx=o(t=>t==="log-only"||t==="reject-and-log","shouldLog");je.shouldLog=dx;var px=o(t=>t==="reject-only"||t==="reject-and-log","shouldReject");je.shouldReject=px;var fx=o(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");je.getErrorsFromValidator=fx});var SE=_(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});qc.handleBodyValidation=void 0;var hx=qr(),Hc=de(),mx=Fc(),tt=co();async function yx(t,e,r){if(!r.validateBody||r.validateBody==="none")return;let n;try{n=await e.clone().json()}catch(h){let y=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,b=Hc.HttpProblems.badRequest(e,t,{detail:`${y}, see errors property for more details`,errors:`${h}`});if((0,tt.shouldLog)(r.validateBody)&&(0,tt.logErrors)(t,r.logLevel??"info",y,[n],h),(0,tt.shouldReject)(r.validateBody))return b}if(!e.headers.get("Content-Type")){let h=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,y=Hc.HttpProblems.badRequest(e,t,{detail:h});return(0,tt.shouldLog)(r.validateBody)&&(0,tt.logErrors)(t,r.logLevel??"info",h,[n],[h]),(0,tt.shouldReject)(r.validateBody)?y:void 0}let i=e.headers.get("Content-Type"),s=i.indexOf(";");s>-1&&(i=i.substring(0,s));let a=(0,mx.getIdForRequestBodySchema)(t.route.path,e.method,i),c=hx.Gateway.instance.schemaValidator[a];if(!c){let h=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,y=Hc.HttpProblems.badRequest(e,t,{detail:h});return(0,tt.shouldLog)(r.validateBody)&&(0,tt.logErrors)(t,r.logLevel??"info",h,[n],[h]),(0,tt.shouldReject)(r.validateBody)?y:void 0}if(c(n))return;let l=c.errors,d="Request body did not pass validation",p=(0,tt.getErrorsFromValidator)(l),f=Hc.HttpProblems.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if((0,tt.shouldLog)(r.validateBody)&&(0,tt.logErrors)(t,r.logLevel??"info",d,[n],p),(0,tt.shouldReject)(r.validateBody))return f}o(yx,"handleBodyValidation");qc.handleBodyValidation=yx});var IE=_($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});$c.handleHeadersValidation=void 0;var gx=de(),uo=co();function bx(t,e,r){if(!r.validateHeaders||r.validateHeaders==="none")return;let n={};e.headers.forEach((a,c)=>{n[c]=a});let i=(0,uo.getParametersForOperation)(t),s=(0,uo.validateParameters)(i.filter(a=>a.location==="header"),n,t.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",c=gx.HttpProblems.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:s.errors});if((0,uo.shouldLog)(r.validateHeaders)&&(0,uo.logErrors)(t,r.logLevel??"info",a,s.invalidValues,s.errors),(0,uo.shouldReject)(r.validateHeaders))return c}}o(bx,"handleHeadersValidation");$c.handleHeadersValidation=bx});var PE=_(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});jc.handlePathParameterValidation=void 0;var _x=de(),lo=co();function Ex(t,e,r){if(!r.validatePathParameters||r.validatePathParameters==="none")return;let n=(0,lo.getParametersForOperation)(t),i=(0,lo.validateParameters)(n.filter(s=>s.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!i.isValid){let s="Path parameters validation failed",a=_x.HttpProblems.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:i.errors});if((0,lo.shouldLog)(r.validatePathParameters)&&(0,lo.logErrors)(t,r.logLevel??"info",s,i.invalidValues,i.errors),(0,lo.shouldReject)(r.validatePathParameters))return a}}o(Ex,"handlePathParameterValidation");jc.handlePathParameterValidation=Ex});var AE=_(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});Vc.handleQueryParameterValidation=void 0;var wx=de(),po=co();function vx(t,e,r){if(!r.validateQueryParameters||r.validateQueryParameters==="none")return;let n=(0,po.getParametersForOperation)(t),i=(0,po.validateParameters)(n.filter(s=>s.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!i.isValid){let s="Query parameters validation failed",a=wx.HttpProblems.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:i.errors});if((0,po.shouldLog)(r.validateQueryParameters)&&(0,po.logErrors)(t,r.logLevel??"info",s,i.invalidValues,i.errors),(0,po.shouldReject)(r.validateQueryParameters))return a}}o(vx,"handleQueryParameterValidation");Vc.handleQueryParameterValidation=vx});var RE=_(un=>{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.SchemaBasedRequestValidation=un.RequestValidationInboundPolicy=void 0;var Tx=SE(),Sx=IE(),Ix=PE(),Px=AE(),Ax=o(async(t,e,r)=>{let n=(0,Px.handleQueryParameterValidation)(e,t,r);if(n!==void 0||(n=(0,Ix.handlePathParameterValidation)(e,t,r),n!==void 0)||(n=(0,Sx.handleHeadersValidation)(e,t,r),n!==void 0))return n;let i=await(0,Tx.handleBodyValidation)(e,t,r);return i!==void 0?i:t},"RequestValidationInboundPolicy");un.RequestValidationInboundPolicy=Ax;un.SchemaBasedRequestValidation=un.RequestValidationInboundPolicy});var OE=_(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});Bc.RequireOriginInboundPolicy=void 0;var Rx=k(),Ox=de(),Nx=o(async(t,e,r,n)=>{if(r.origins===void 0||r.origins.length===0)throw new Rx.ConfigurationError(`RequireOriginInboundPolicy '${n}' configuration error - no allowed origins specified`);let i=typeof r.origins=="string"?r.origins.split(","):r.origins;i=i.map(a=>a.trim());let s=t.headers.get("origin");if(!s||!i.includes(s)){let a=r.failureDetail??"Forbidden";return Ox.HttpProblems.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");Bc.RequireOriginInboundPolicy=Nx});var NE=_(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});Gc.SetBodyInboundPolicy=void 0;var Cx=Ke(),xx=o(async(t,e,r)=>new Cx.ZuploRequest(t,{body:r.body}),"SetBodyInboundPolicy");Gc.SetBodyInboundPolicy=xx});var xE=_(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});Kc.SetHeadersInboundPolicy=void 0;var CE=k(),Lx=Ke(),Dx=o(async(t,e,r,n)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new CE.ConfigurationError(`SetHeadersInboundPolicy '${n}' options.headers must be a valid array of { name, value }`);let s=new Headers(t.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new CE.ConfigurationError(`SetHeadersInboundPolicy '${n}' each option.headers[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!s.has(c.name)||u)&&s.set(c.name,c.value)}),new Lx.ZuploRequest(t,{headers:s})},"SetHeadersInboundPolicy");Kc.SetHeadersInboundPolicy=Dx});var DE=_(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});Jc.SetHeadersOutboundPolicy=void 0;var LE=k(),Mx=o(async(t,e,r,n,i)=>{let s=n.headers;if(!s||!Array.isArray(s)||s.length==0)throw new LE.ConfigurationError(`SetHeadersOutboundPolicy '${i}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return s.forEach(u=>{if(!u.name||u.name.length===0)throw new LE.ConfigurationError(`SetHeadersOutboundPolicy '${i}' each option.headers[] entry must have a name property`);let l=u.overwrite===void 0?!0:u.overwrite;(!a.has(u.name)||l)&&a.set(u.name,u.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");Jc.SetHeadersOutboundPolicy=Mx});var UE=_(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});zc.SetQueryParamsInboundPolicy=void 0;var ME=k(),Ux=Ke(),kx=o(async(t,e,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length==0)throw new ME.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' options.params must be a valid array of { name, value }`);let s=new URL(t.url);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new ME.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' each option.params[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!s.searchParams.has(c.name)||u)&&s.searchParams.set(c.name,c.value)}),new Ux.ZuploRequest(s.toString(),t)},"SetQueryParamsInboundPolicy");zc.SetQueryParamsInboundPolicy=kx});var kE=_(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});Wc.SetStatusOutboundPolicy=void 0;var Fx=o(async(t,e,r,n,i)=>{if(!n.status||isNaN(n.status)||n.status<100||n.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${i}' - status must be a valid number between 100 and 599, not '${n.status}'`);return new Response(t.body,{headers:t.headers,status:n.status,statusText:n.statusText??t.statusText})},"SetStatusOutboundPolicy");Wc.SetStatusOutboundPolicy=Fx});var FE=_(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});Qc.SleepInboundPolicy=void 0;var Hx=k(),qx=o(async t=>new Promise(r=>{setTimeout(r,t)}),"sleep"),$x=o(async(t,e,r,n)=>{if(!r||r.sleepInMs===void 0||isNaN(r.sleepInMs))throw new Hx.ConfigurationError(`SleepInboundPolicy '${n} must have a valid options.sleepInMs value`);return await qx(r.sleepInMs),t},"SleepInboundPolicy");Qc.SleepInboundPolicy=$x});var qE=_(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});Yc.SupabaseJwtInboundPolicy=void 0;var HE=k(),jx=de(),Vx=Ke(),Bx=lt(),Gx=Xt(),Kx=o(async(t,e,r,n)=>{(0,Bx.optionValidator)(r,n).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let i={secret:r.secret,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1},s=await(0,Gx.OpenIdJwtInboundPolicy)(t,e,i,n);if(s instanceof Response)return s;if(!(s instanceof Vx.ZuploRequest))throw new HE.SystemError("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=r.requiredClaims;if(!a)return s;let c=t.user?.data.app_metadata;if(!c)throw new HE.RuntimeError(`SupabaseJwtInboundPolicy policy '${n}' - has requiredClaims but the JWT token had no app_metadata property`);let u=Object.keys(a),l=[];return u.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(c[d])||l.push(d):p!==c[d]&&l.push(d)}),l.length>0?jx.HttpProblems.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");Yc.SupabaseJwtInboundPolicy=Kx});var jE=_(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});Zc.UpstreamAzureAdServiceAuthInboundPolicy=void 0;var Jx=Zt(),zx=Bt(),$E=k(),Wx=kn(),Qx=lt(),Yx=o(async(t,e,r,n)=>{(0,Qx.optionValidator)(r,n).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let i=await(0,Jx.getPolicyCacheName)(n,r),s=new zx.MemoryZoneReadThroughCache(i,e),a=await s.get(n);if(!a){let c=await Zx(r,e);s.put(n,c.access_token,c.expires_in-(r.expirationOffsetSeconds??300)),a=c.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");Zc.UpstreamAzureAdServiceAuthInboundPolicy=Yx;async function Zx(t,e){let r=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),n=await(0,Wx.fetchRetry)({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:r});if(n.status!==200){try{let s=await n.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new $E.RuntimeError("Could not get token from Azure AD")}let i=await n.json();if(i&&typeof i=="object"&&"access_token"in i&&typeof i.access_token=="string"&&"expires_in"in i&&typeof i.expires_in=="number")return{access_token:i.access_token,expires_in:i.expires_in};throw new $E.RuntimeError("Response returned from Azure AD is not in the expected format.")}o(Zx,"getAccessToken")});var BE=_(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});Xc.UpstreamFirebaseAdminAuthInboundPolicy=void 0;var Xx=Zt(),eL=Bt(),tL=k(),Bf=Fn(),rL=lt(),VE="https://accounts.google.com/o/oauth2/token",Gf,nL=o(async(t,e,r,n)=>{(0,rL.optionValidator)(r,n).required("serviceAccountJson","string"),Gf||(Gf=await Bf.GcpServiceAccount.init(r.serviceAccountJson));let i={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(0,Xx.getPolicyCacheName)(n,r),a=new eL.MemoryZoneReadThroughCache(s,e),c=await a.get(n);if(!c){let u=await(0,Bf.getTokenFromGcpServiceAccount)({serviceAccount:Gf,audience:VE,payload:i}),l=await(0,Bf.exchangeGgpJwtForIdToken)(VE,u,{retries:r.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new tL.RuntimeError("Invalid OAuth response from Firebase");c=l.access_token,a.put(n,c,(l.expires_in??3600)-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${c}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");Xc.UpstreamFirebaseAdminAuthInboundPolicy=nL});var GE=_(eu=>{"use strict";Object.defineProperty(eu,"__esModule",{value:!0});eu.UpstreamFirebaseUserAuthInboundPolicy=void 0;var iL=Zt(),oL=Bt(),pi=k(),sL=If(),Kf=Fn(),aL=Jt(),cL=lt(),uL="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",lL=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Jf,dL=o(async(t,e,r,n)=>{if((0,cL.optionValidator)(r,n).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!r.userId&&!r.userIdPropertyPath)throw new pi.ConfigurationError(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${n}'.`);let i={};if(typeof r.developerClaims<"u"){for(let p in r.developerClaims)if(Object.prototype.hasOwnProperty.call(r.developerClaims,p)){if(lL.indexOf(p)!==-1)throw new pi.ConfigurationError(`Developer claim "${p}" is reserved and cannot be specified.`);i[p]=r.developerClaims[p]}}Jf||(Jf=await Kf.GcpServiceAccount.init(r.serviceAccountJson));let s=r.userId;if(!s&&!r.userIdPropertyPath){if(!t.user)throw new pi.RuntimeError("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=t.user?.sub}else if(r.userIdPropertyPath){if(!t.user)throw new pi.RuntimeError(`Unable to apply userIdPropertyPath '${r.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=(0,aL.getValueFromRequestUser)(t.user,r.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new pi.RuntimeError(`Unable to determine user from for the policy ${n}`);let a=await(0,iL.getPolicyCacheName)(n,r),c=new oL.MemoryZoneReadThroughCache(a,e),u={uid:s,claims:i},l=await(0,sL.sha256)(JSON.stringify(u)),d=await c.get(l);if(!d){let p=await(0,Kf.getTokenFromGcpServiceAccount)({serviceAccount:Jf,audience:uL,payload:u}),f=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${r.webApiKey}`,h=await(0,Kf.exchangeFirebaseJwtForIdToken)(f,p,{retries:r.tokenRetries??3,retryDelayMs:10});if(!h.idToken)throw new pi.RuntimeError("Invalid token response from Firebase");d=h.idToken,c.put(l,d,(h.expiresIn?parseInt(h.expiresIn):3600)-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");eu.UpstreamFirebaseUserAuthInboundPolicy=dL});var JE=_(tu=>{"use strict";Object.defineProperty(tu,"__esModule",{value:!0});tu.UpstreamGcpJwtInboundPolicy=void 0;var KE=Fn(),pL=lt(),zf,fL=o(async(t,e,r,n)=>{(0,pL.optionValidator)(r,n).required("audience","string").required("serviceAccountJson","string"),zf||(zf=await KE.GcpServiceAccount.init(r.serviceAccountJson));let i=await(0,KE.getTokenFromGcpServiceAccount)({serviceAccount:zf,audience:r.audience});return t.headers.set("Authorization",`Bearer ${i}`),t},"UpstreamGcpJwtInboundPolicy");tu.UpstreamGcpJwtInboundPolicy=fL});var WE=_(ru=>{"use strict";Object.defineProperty(ru,"__esModule",{value:!0});ru.UpstreamGcpServiceAuthInboundPolicy=void 0;var hL=Zt(),mL=Xu(),yL=Bt(),fo=k(),Wf=Fn(),gL=Jt(),bL=lt(),zE="https://www.googleapis.com/oauth2/v4/token",Qf,_L=o(async(t,e,r,n)=>{(0,bL.optionValidator)(r,n).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Qf||(Qf=await Wf.GcpServiceAccount.init(r.serviceAccountJson));let i={};if(r.scopes&&r.audience)throw new fo.ConfigurationError("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(r.scopes)try{let u=(0,gL.parseValueToStringArray)(r.scopes);i.scope=u.join(" ")}catch(u){throw u instanceof fo.ConfigurationError?new fo.ConfigurationError(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${u.message}`):u}r.audience&&(i.target_audience=`${r.audience}`);let s=await(0,hL.getPolicyCacheName)(n,r),a;r.useMemoryCacheOnly?a=new mL.MemoryCache(s):a=new yL.MemoryZoneReadThroughCache(s,e);let c=await a.get(n);if(!c){let u=await(0,Wf.getTokenFromGcpServiceAccount)({serviceAccount:Qf,audience:zE,payload:i}),l=await(0,Wf.exchangeGgpJwtForIdToken)(zE,u,{retries:r.tokenRetries??3,retryDelayMs:10});if(r.audience){if(!l.id_token)throw new fo.RuntimeError("Invalid token response from GCP");c=l.id_token}else{if(!l.access_token)throw new fo.RuntimeError("Invalid token response from GCP");c=l.access_token}a.put(n,c,3600-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${c}`),t},"UpstreamGcpServiceAuthInboundPolicy");ru.UpstreamGcpServiceAuthInboundPolicy=_L});var YE=_(nu=>{"use strict";Object.defineProperty(nu,"__esModule",{value:!0});nu.ValidateJsonSchemaInbound=void 0;var EL=k(),QE=de(),wL=o(async(t,e,r)=>{let n=t.clone(),i;try{i=await n.json()}catch{return QE.HttpProblems.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(r.validator(i))return t;let{errors:a}=r.validator;if(!a)throw new EL.SystemError("Invalid state - validator error object is undefined even though validation failed.");let c=a.map(u=>u.instancePath===void 0||u.instancePath===""?"Body "+u.message:u.instancePath.replace("/","")+" "+u.message);return QE.HttpProblems.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:c})},"ValidateJsonSchemaInbound");nu.ValidateJsonSchemaInbound=wL});var ew=_((JJ,XE)=>{"use strict";var vL=Object.defineProperty,TL=Object.getOwnPropertyNames,B=o((t,e)=>vL(t,"name",{value:e,configurable:!0}),"__name"),vt=o((t,e)=>o(function(){return e||(0,t[TL(t)[0]])((e={exports:{}}).exports,e),e.exports},"__require"),"__commonJS"),Yf=vt({"node_modules/fast-xml-parser/src/util.js"(t){"use strict";var e=":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",r=e+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",n="["+e+"]["+r+"]*",i=new RegExp("^"+n+"$"),s=B(function(c,u){let l=[],d=u.exec(c);for(;d;){let p=[];p.startIndex=u.lastIndex-d[0].length;let f=d.length;for(let h=0;h<f;h++)p.push(d[h]);l.push(p),d=u.exec(c)}return l},"getAllMatches"),a=B(function(c){let u=i.exec(c);return!(u===null||typeof u>"u")},"isName");t.isExist=function(c){return typeof c<"u"},t.isEmptyObject=function(c){return Object.keys(c).length===0},t.merge=function(c,u,l){if(u){let d=Object.keys(u),p=d.length;for(let f=0;f<p;f++)l==="strict"?c[d[f]]=[u[d[f]]]:c[d[f]]=u[d[f]]}},t.getValue=function(c){return t.isExist(c)?c:""},t.isName=a,t.getAllMatches=s,t.nameRegexp=n}}),ZE=vt({"node_modules/fast-xml-parser/src/validator.js"(t){"use strict";var e=Yf(),r={allowBooleanAttributes:!1,unpairedTags:[]};t.validate=function(g,v){v=Object.assign({},r,v);let O=[],V=!1,E=!1;g[0]==="\uFEFF"&&(g=g.substr(1));for(let T=0;T<g.length;T++)if(g[T]==="<"&&g[T+1]==="?"){if(T+=2,T=i(g,T),T.err)return T}else if(g[T]==="<"){let C=T;if(T++,g[T]==="!"){T=s(g,T);continue}else{let w=!1;g[T]==="/"&&(w=!0,T++);let P="";for(;T<g.length&&g[T]!==">"&&g[T]!==" "&&g[T]!==" "&&g[T]!==`
74
+ `+d});let p=Math.floor((typeof c=="number"?c:Date.now())/1e3)-r.timestamp;if(i>0&&p>i)throw new Xr.StripeSignatureVerificationError(e,t,{message:"Timestamp outside the tolerance zone"});return!0}o(QR,"validateComputedSignature");function YR(t,e){return typeof t!="string"?null:t.split(",").reduce((r,n)=>{let i=n.split("=");return i[0]==="t"&&(r.timestamp=parseInt(i[1],10)),i[0]===e&&r.signatures.push(i[1]),r},{timestamp:-1,signatures:[]})}o(YR,"parseHeader");function ZR(t,e){if(t.length!==e.length)return!1;let r=t.length,n=0;for(let i=0;i<r;++i)n|=t.charCodeAt(i)^e.charCodeAt(i);return n===0}o(ZR,"secureCompare");async function o_(t,e){let r=new TextEncoder,n=await crypto.subtle.importKey("raw",r.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),i=await crypto.subtle.sign("hmac",n,r.encode(t)),s=new Uint8Array(i),a=new Array(s.length);for(let c=0;c<s.length;c++)a[c]=tf[s[c]];return a.join("")}o(o_,"computeHMACSignatureAsync");ti.computeHMACSignatureAsync=o_;var tf=new Array(256);for(let t=0;t<tf.length;t++)tf[t]=t.toString(16).padStart(2,"0")});var lt=_(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});Ga.optionValidator=void 0;var ri=k(),XR=at();function eO(t,e,r="policy"){let n=`${r} '${e}'`;if(!(0,XR.isObject)(t))throw new ri.ConfigurationError(`Options on ${n} is expected to be an object. Received the type '${typeof t}'.`);let i=o((c,u,l)=>{let d=t[c];if(!(l&&d===void 0)){if(d===void 0)throw new ri.ConfigurationError(`Value of '${String(c)}' on ${n} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(u==="array"&&Array.isArray(d))throw new ri.ConfigurationError(`Value of '${String(c)}' on ${n} must be an array. Received type ${typeof d}.`);if(typeof d!==u)throw new ri.ConfigurationError(`Value of '${String(c)}' on ${n} must be of type ${u}. Received type ${typeof d}.`);if(typeof d=="string"&&d.length===0)throw new ri.ConfigurationError(`Value of '${String(c)}' on ${n} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof d=="number"&&isNaN(d))throw new ri.ConfigurationError(`Value of '${String(c)}' on ${n} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),s=o((c,u)=>(i(c,u,!0),{optional:s,required:a}),"optional"),a=o((c,u)=>(i(c,u,!1),{optional:s,required:a}),"required");return{optional:s,required:a}}o(eO,"optionValidator");Ga.optionValidator=eO});var nf=_(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.StripeWebhookVerificationInboundPolicy=void 0;var tO=_n(),rO=de(),nO=s_(),iO=lt(),rf=class extends tO.InboundPolicy{static{o(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,r){(0,iO.optionValidator)(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let n=e.headers.get("stripe-signature");try{let i=await e.clone().text();await(0,nO.constructEventAsync)(i,n,this.options.signingSecret)}catch(i){let s=i.message;if(i.type&&i.type==="StripeSignatureVerificationError"){let a=i.message,u=/Note:(.*)/g.exec(a);s=u?u[1].trim():a}return r.log.error("Error validating stripe webhook",s),rO.HttpProblems.badRequest(e,r,{title:"Webhook Error",detail:s})}return e}};Ka.StripeWebhookVerificationInboundPolicy=rf});var c_=_(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});Ja.isStripeWebhookEvent=void 0;var a_=at();function oO(t){return t!==null&&typeof t=="object"&&"id"in t&&(0,a_.isString)(t.id)&&"type"in t&&(0,a_.isString)(t.type)}o(oO,"isStripeWebhookEvent");Ja.isStripeWebhookEvent=oO});var u_=_(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.MeteringPlugin=void 0;var sO=Ot(),of=class extends sO.SystemRuntimePlugin{static{o(this,"MeteringPlugin")}};za.MeteringPlugin=of});var cf=_(af=>{"use strict";Object.defineProperty(af,"__esModule",{value:!0});var sf=k(),aO={getSubscription:async({subscriptionId:t,stripeSecretKey:e,logger:r})=>{let n=await fetch(`https://api.stripe.com/v1/subscriptions/${t}`,{headers:{Authorization:`Bearer ${e}`}}),i=await n.json();if(n.status!==200){let s="Error retrieving subscription from Stripe API.";throw r.error(s,i),new sf.RuntimeError(s)}return i},getCustomer:async({customerId:t,stripeSecretKey:e,logger:r})=>{let n=await fetch(`https://api.stripe.com/v1/customers/${t}`,{headers:{Authorization:`Bearer ${e}`}}),i=await n.json();if(n.status!==200){let s="Error retrieving customer from Stripe API.";throw r.error(s,i),new sf.RuntimeError(s)}return i},getUpcomingInvoice:async({customerId:t,stripeSecretKey:e,logger:r})=>{let n=await fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${t}`,{headers:{Authorization:`Bearer ${e}`}}),i=await n.json();if(n.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw r.error(s,i),new sf.RuntimeError(s)}return i}};af.default=aO});var d_=_(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.deleteConsumer=Ar.createConsumerInvite=Ar.createConsumer=void 0;var uf=k(),lf=Je(),df=ie(),pf=kn(),ff="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",l_="My API Key";async function cO({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:r,stripeCustomerId:n,managerEmail:i,managerSub:s,context:a}){let{authApiJWT:c}=df.Environment.instance,u=new URL(`/v1/buckets/${t}/consumers`,ff);u.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:l_,tags:{subscriptionExternalId:e,planExternalIds:[r]},metadata:{stripeSubscriptionId:e,stripeProductId:r,stripeCustomerId:n},managers:[{sub:s,email:i}]},p=await(0,pf.fetchRetry)({retryDelayMs:5,retries:2,logger:lf.SystemLogMap.getLogger(a)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${c}`,"content-type":"application/json"},body:JSON.stringify(d)}),f=await p.json();if(p.status!==200){let h="Error creating API Key Consumer";throw a.log.error(h,f),new uf.RuntimeError(h)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:r}),l}o(cO,"createConsumer");Ar.createConsumer=cO;async function uO({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:r,stripeCustomerId:n,managerEmail:i,context:s}){let{authApiJWT:a}=df.Environment.instance,c=new URL(`/v1/buckets/${t}/consumers`,ff);c.searchParams.set("with-api-key","true");let u=crypto.randomUUID(),l={name:u,description:l_,tags:{subscriptionExternalId:e,planExternalIds:[r]},metadata:{stripeSubscriptionId:e,stripeProductId:r,stripeCustomerId:n},managers:[i]},d=await(0,pf.fetchRetry)({retryDelayMs:5,retries:2,logger:lf.SystemLogMap.getLogger(s)},c.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 uf.RuntimeError(f)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:u,stripeSubscriptionId:e,stripeProductId:r}),u}o(uO,"createConsumerInvite");Ar.createConsumerInvite=uO;async function lO({apiKeyBucketName:t,consumerId:e,context:r}){let{authApiJWT:n}=df.Environment.instance,i=new URL(`/v1/buckets/${t}/consumers/${e}`,ff);i.searchParams.set("with-api-key","true");let s=await(0,pf.fetchRetry)({retryDelayMs:5,retries:2,logger:lf.SystemLogMap.getLogger(r)},i.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),c="Error invalidating API Key Consumer";throw r.log.error(c,a),new uf.RuntimeError(c)}return r.log.info(`Successfully invalidated API Key Consumer '${e}`),e}o(lO,"deleteConsumer");Ar.deleteConsumer=lO});var Wa=_(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.getSubscription=Or.updateSubscription=Or.createSubscription=void 0;var Rr=k(),hf=Je(),mf=ie(),yf=kn(),gf=at();async function dO({context:t,stripeSubscriptionId:e,stripeProductId:r,customerKey:n,meteringBucketId:i,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:c,metadata:u}){let l={status:c,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[r],customerKey:n,customerExternalId:a,metadata:u},{authApiJWT:d,meteringServiceUrl:p}=mf.Environment.instance;if(!(0,gf.isNonEmptyString)(d))throw new Rr.SystemError("No Zuplo JWT token set.");let f=await(0,yf.fetchRetry)({retryDelayMs:5,retries:2,logger:hf.SystemLogMap.getLogger(t)},`${p}/internal/v1/metering/${i}/subscriptions`,{headers:{Authorization:`Bearer ${d}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(l)});if(!f.ok){let h="Error creating monetization subscription.",y;try{y=await f.json()}catch{y={status:f.status,statusText:f.statusText}}throw t.log.error(h,y),new Rr.RuntimeError(h)}t.log.info("Successfully created monetization subscription.",l)}o(dO,"createSubscription");Or.createSubscription=dO;async function pO({context:t,meteringSubscriptionId:e,meteringBucketId:r,requestBody:n}){let{authApiJWT:i,meteringServiceUrl:s}=mf.Environment.instance;if(!(0,gf.isNonEmptyString)(i))throw new Rr.SystemError("No Zuplo JWT token set.");let a=await(0,yf.fetchRetry)({retryDelayMs:5,retries:2,logger:hf.SystemLogMap.getLogger(t)},`${s}/internal/v1/metering/${r}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"PATCH",body:JSON.stringify(n)});if(!a.ok){let c=`Error updating monetization subscription with: '${JSON.stringify(n)}'.`,u;try{u=await a.json()}catch{u={status:a.status,statusText:a.statusText}}throw t.log.error(c,u),new Rr.RuntimeError(c)}t.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(n)}'.`)}o(pO,"updateSubscription");Or.updateSubscription=pO;async function fO({context:t,stripeSubscriptionId:e,stripeCustomerId:r,meteringBucketId:n}){let{authApiJWT:i,meteringServiceUrl:s}=mf.Environment.instance;if(!(0,gf.isNonEmptyString)(i))throw new Rr.SystemError("No Zuplo JWT token set.");let a=await(0,yf.fetchRetry)({retryDelayMs:5,retries:2,logger:hf.SystemLogMap.getLogger(t)},`${s}/internal/v1/metering/${n}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":t.requestId},method:"GET"});if(!a.ok){let u="Error retrieving the monetization subscription.",l;try{l=await a.json()}catch{l={status:a.status,statusText:a.statusText}}throw t.log.error(u,l),new Rr.RuntimeError(u,l)}let c=await a.json();if(c.data.length===0){let u="Subscription was not found and the event was ignored by Zuplo.";throw t.log.error(u),new Rr.RuntimeError(u)}if(c.data[0].customerExternalId!==r){let u="A subscription was not found for the customer provided and the event was ignored by Zuplo.";throw t.log.error(u),new Rr.RuntimeError(u)}return c.data[0]}o(fO,"getSubscription");Or.getSubscription=fO});var bf=_(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});Qa.stripeStatusToMeteringStatus=void 0;function hO(t){return t.replaceAll("_","-")}o(hO,"stripeStatusToMeteringStatus");Qa.stripeStatusToMeteringStatus=hO});var p_=_(to=>{"use strict";var mO=to&&to.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(to,"__esModule",{value:!0});var en=de(),yO=mO(cf()),_f=d_(),gO=Wa(),bO=bf();async function _O(t,e,r,n){let i=r.data.object.id;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected event '${r.id}' to have '.data.object.id' be the subscription ID.`),en.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=r.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${r.id}' to have a plan data.`),en.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=r.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${r.id}'`),en.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let c=s.product,u,l,d;if(r.data.object.metadata&&r.data.object.metadata.zuplo_created_by_email&&r.data.object.metadata.zuplo_created_by_sub)l=r.data.object.metadata.zuplo_created_by_email,d=r.data.object.metadata.zuplo_created_by_sub,u=await(0,_f.createConsumer)({apiKeyBucketName:n.apiKeyBucketName,stripeProductId:c,stripeSubscriptionId:i,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await yO.default.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.`),en.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe API result. Expected customer to contain email address."});u=await(0,_f.createConsumerInvite)({apiKeyBucketName:n.apiKeyBucketName,stripeProductId:c,stripeSubscriptionId:i,stripeCustomerId:a,managerEmail:p.email,context:e})}if(!u)return en.HttpProblems.internalServerError(t,e,{detail:"No API Key Consumer was created, skipping creation of subscription"});try{let p=(0,bO.stripeStatusToMeteringStatus)(r.data.object.status),f;l&&d&&(f={subscriber:{sub:d,email:l}}),await(0,gO.createSubscription)({context:e,stripeProductId:c,stripeSubscriptionId:i,customerKey:u,meteringBucketId:n.meteringBucketId,meteringBucketRegion:n.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:f})}catch(p){return await(0,_f.deleteConsumer)({apiKeyBucketName:n.apiKeyBucketName,consumerId:u,context:e}),en.HttpProblems.internalServerError(t,e,{detail:p.message})}return en.HttpProblems.ok(t,e)}o(_O,"onCustomerSubscriptionCreated");to.default=_O});var h_=_(wf=>{"use strict";Object.defineProperty(wf,"__esModule",{value:!0});var Ef=de(),f_=Wa();async function EO(t,e,r,n){let i=r.data.object.id;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected event '${r.id}' to have '.data.object.id' be the subscription ID.`),Ef.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=r.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${r.id}'`),Ef.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let a=await(0,f_.getSubscription)({context:e,stripeSubscriptionId:i,stripeCustomerId:s,meteringBucketId:n.meteringBucketId});return await(0,f_.updateSubscription)({context:e,meteringSubscriptionId:a.id,meteringBucketId:n.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}}),Ef.HttpProblems.ok(t,e)}o(EO,"onCustomerSubscriptionDeleted");wf.default=EO});var m_=_(no=>{"use strict";var wO=no&&no.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(no,"__esModule",{value:!0});var ro=de(),vO=wO(cf()),Ya=Wa(),TO=bf();async function SO(t,e,r,n){let i=r.data.object.id;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected event '${r.id}' to include '.data.object.id' as the subscription ID.`),ro.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=r.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${r.id}'`),ro.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(r.data.previous_attributes){let a=r.data.previous_attributes;if(a.status&&a.status!==r.data.object.status){e.log.debug(`Processing subscription status change from Stripe event '${r.id}'.`);let c=await(0,Ya.getSubscription)({context:e,stripeSubscriptionId:i,stripeCustomerId:s,meteringBucketId:n.meteringBucketId}),u=(0,TO.stripeStatusToMeteringStatus)(r.data.object.status);return await(0,Ya.updateSubscription)({context:e,meteringSubscriptionId:c.id,meteringBucketId:n.meteringBucketId,requestBody:{status:u,planExternalIds:c.planExternalIds}}),ro.HttpProblems.ok(t,e)}if(a.plan&&a.plan.product!==r.data.object.plan.product){e.log.debug(`Processing subscription plan change from Stripe event '${r.id}'.`);let c=await(0,Ya.getSubscription)({context:e,stripeSubscriptionId:i,stripeCustomerId:s,meteringBucketId:n.meteringBucketId}),u=r.data.object.plan.product,d=(await vO.default.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:n.stripeSecretKey})).lines.data.filter(f=>f.proration&&f.price.product===u),p=0;return d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${r.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await(0,Ya.updateSubscription)({context:e,meteringSubscriptionId:c.id,meteringBucketId:n.meteringBucketId,requestBody:{status:c.status,planExternalIds:[u],prorate:p}}),ro.HttpProblems.ok(t,e)}}return e.log.warn(`This update event '${r.id}' is not supported by Stripe metering plugin webhook.`),ro.HttpProblems.badRequest(t,e,{detail:"This update event is not supported by Stripe metering plugin webhook."})}o(SO,"onCustomerSubscriptionUpdated");no.default=SO});var g_=_(ni=>{"use strict";var Tf=ni&&ni.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ni,"__esModule",{value:!0});ni.StripeMonetizationPlugin=void 0;var Za=Yi(),Xa=k(),IO=Gt(),PO=nf(),y_=de(),AO=ar(),RO=En(),OO=Sl(),NO=gt(),CO=ie(),xO=c_(),LO=lt(),DO=u_(),MO=Tf(p_()),UO=Tf(h_()),kO=Tf(m_()),vf=class extends DO.MeteringPlugin{static{o(this,"StripeMonetizationPlugin")}options;constructor(e){super(),this.options=e}registerRoutes(e,r){let n=o(async(c,u)=>{if(this.options.__testMode===!0)return u.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:l,apiKeyBucketName:d}=this.options;if(!l)if(Za.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)l=Za.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new Xa.ConfigurationError("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!d)if(Za.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)d=Za.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new Xa.ConfigurationError("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!CO.Environment.instance.build.ACCOUNT_NAME)throw new Xa.SystemError("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let p=this.options.meteringBucketRegion??"us-central1";if(!FO(p))throw new Xa.ConfigurationError(`StripeMonetizationPlugin - The value '${p}' on the property 'meteringBucketRegion' is invalid.`);let f=await c.json();if(!(0,xO.isStripeWebhookEvent)(f))return y_.HttpProblems.badRequest(c,u,{detail:"The received body was not in the expected format."});switch(u.log.info(`Received Stripe webhook event of type '${f.type}' with ID '${f.id}'.`),f.type){case"customer.subscription.created":return await(0,MO.default)(c,u,f,{meteringBucketId:l,apiKeyBucketName:d,meteringBucketRegion:p,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await(0,kO.default)(c,u,f,{meteringBucketId:l,apiKeyBucketName:d,meteringBucketRegion:p,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await(0,UO.default)(c,u,f,{meteringBucketId:l});default:return y_.HttpProblems.badRequest(c,u,{detail:"Event is not supported by Stripe monetization plugin webhook."})}},"stripeWebhookHandler"),i=(0,RO.createInternalPolicyProcessor)({inboundPolicies:[new PO.StripeWebhookVerificationInboundPolicy({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});(0,LO.optionValidator)(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let s=new IO.Pipeline({processors:[AO.metricsProcessor,i],handler:n,gateway:r}),a=new NO.SystemRouteConfiguration({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:OO.SystemRouteName.StripePlugin});e.addRoute(a,s.execute)}};ni.StripeMonetizationPlugin=vf;function FO(t){return t!==null&&typeof t=="string"&&["us-central1","europe-west4"].includes(t)}o(FO,"isMetricsRegion")});var v_=_(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.AmberfloMeteringInboundPolicy=ii.AmberfloMeteringPolicy=void 0;var b_=k(),HO=Re(),__=Jt(),w_=new WeakMap,E_={},Sf=class{static{o(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,r){w_.set(e,r)}};ii.AmberfloMeteringPolicy=Sf;async function qO(t,e,r,n){if(!r.statusCodes)throw new b_.ConfigurationError(`Invalid AmberfloMeterInboundPolicy '${n}': options.statusCodes must be an array of HTTP status code numbers`);let i=(0,__.statusCodesStringToNumberArray)(r.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(i.includes(s.status)){let a=w_.get(e),c=r.customerId;if(r.customerIdPropertyPath){if(!t.user)throw new b_.RuntimeError(`Unable to apply customerIdPropertyPath '${r.customerIdPropertyPath}' as request.user is 'undefined'.`);c=(0,__.getValueFromRequestUser)(t.user,r.customerIdPropertyPath,"customerIdPropertyPath")}let u=a?.customerId??c;if(!u){e.log.error(`Error in AmberfloMeterInboundPolicy '${n}': customerId cannot be undefined`);return}let l=a?.meterApiName??r.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterApiName cannot be undefined`);return}let d=a?.meterValue??r.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterValue cannot be undefined`);return}let p={customerId:u,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(r.dimensions??{},a?.dimensions)},f=E_[r.apiKey];if(!f){let h=r.apiKey,y=t.headers.get("zm-test-id")??"";f=new HO.BatchDispatch("amberflo-ingest-meter",10,async b=>{try{let I=r.url??"https://app.amberflo.io/ingest",A=await fetch(I,{method:"POST",body:JSON.stringify(b),headers:{"content-type":"application/json","x-api-key":h,"zm-test-id":y}});A.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${n}'. ${A.status}: ${await A.text()}`)}catch(I){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${n}': ${I.message}`),I}}),E_[h]=f}f.enqueue(p),e.waitUntil(f.waitUntilFlushed())}}),t}o(qO,"AmberfloMeteringInboundPolicy");ii.AmberfloMeteringInboundPolicy=qO});var If=_(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});ec.sha256=void 0;async function $O(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(r)].map(i=>i.toString(16).padStart(2,"0")).join("")}o($O,"sha256");ec.sha256=$O});var Zt=_(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});tc.getPolicyCacheName=void 0;var jO=If(),T_=new Map;async function VO(t,e){let r,n=T_.get(t);return n!==void 0?r=n:(r=`zuplo-policy-${await(0,jO.sha256)(JSON.stringify({policyName:t,options:e}))}`,T_.set(t,r)),r}o(VO,"getPolicyCacheName");tc.getPolicyCacheName=VO});var Rf=_(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});rc.ApiKeyInboundPolicy=void 0;var BO=Zt(),GO=Bt(),S_=Yi(),Pf=k(),KO=Kt(),I_=Je(),Af=ie(),JO=kn(),P_="key-metadata-cache-type";function zO(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}o(zO,"getKeyValue");async function WO(t,e,r,n){if(!r.bucketName)if(S_.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)r.bucketName=S_.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new Pf.ConfigurationError(`ApiKeyInboundPolicy '${n}' - no bucketName property provided`);let i={authHeader:r.authHeader??"authorization",authScheme:r.authScheme??"Bearer",bucketName:r.bucketName,cacheTtlSeconds:r.cacheTtlSeconds??60,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:r.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(i.cacheTtlSeconds<60)throw new Pf.ConfigurationError(`ApiKeyInboundPolicy '${n}' - minimum cacheTtlSeconds value is 60s, '${i.cacheTtlSeconds}' is invalid`);let s=o(I=>i.allowUnauthenticatedRequests?t:KO.HttpProblems.unauthorized(t,e,{detail:I}),"unauthorizedResponse"),a=t.headers.get(i.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(i.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let c=zO(a,i);if(!c||c==="")return s("No key present");let u=await QO(c),l=await(0,BO.getPolicyCacheName)(n,i),d=new GO.MemoryZoneReadThroughCache(l,e),p=await d.get(u);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==P_&&I_.SystemLogMap.getLogger(e).error(`ApiKeyInboundPolicy '${n}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let f={key:c},h=await(0,JO.fetchRetry)({retryDelayMs:5,retries:2,logger:I_.SystemLogMap.getLogger(e)},`${Af.Environment.instance.apiKeyServiceUrl}/v1/$validate/${i.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":Af.Environment.instance.deploymentName??"unknown","User-Agent":Af.Environment.instance.systemUserAgent},body:JSON.stringify(f)});if(h.status===401)return e.log.info(`ApiKeyInboundPolicy '${n}' - 401 response from Key Service`),s("Authorization Failed");if(h.status!==200){try{let I=await h.text(),A=JSON.parse(I);e.log.error("Unexpected response from key service",A)}catch{e.log.error("Invalid response from key service")}throw new Pf.RuntimeError(`ApiKeyInboundPolicy '${n}' - unexpected response from Key Service. Status: ${h.status}`)}let y=await h.json(),b={isValid:!0,typeId:P_,user:{sub:y.name,data:y.metadata}};return t.user=b.user,d.put(u,b,i.cacheTtlSeconds),t}o(WO,"ApiKeyInboundPolicy");rc.ApiKeyInboundPolicy=WO;async function QO(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}o(QO,"hashValue")});var A_=_(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});nc.ApiAuthKeyInboundPolicy=void 0;var YO=Rf();nc.ApiAuthKeyInboundPolicy=YO.ApiKeyInboundPolicy});var Xt=_(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});ic.OpenIdJwtInboundPolicy=void 0;var Nf=(ra(),xo(ta)),Cf=k(),ZO=de(),Of={},XO=o(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new Cf.ConfigurationError("Invalid State - jwkUrl not set");Of[e.jwkUrl]||(Of[e.jwkUrl]=(0,Nf.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:r}=await(0,Nf.jwtVerify)(t,Of[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return r},"jwkVerifier"),eN=o(async(t,e)=>{let r;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);r=new Uint8Array(s)}else r=e.secret;let{payload:n}=await(0,Nf.jwtVerify)(t,r,{issuer:e.issuer,audience:e.audience});return n},"secretVerifier"),tN=o(async(t,e,r,n)=>{let i=t.headers.get("Authorization"),s="bearer ",a=o(f=>ZO.HttpProblems.unauthorized(t,e,{detail:f}),"unauthorizedResponse");if(!r.jwkUrl&&!r.secret)throw new Cf.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': One of 'jwkUrl' or 'secret' options are required.`);if(r.jwkUrl&&r.secret)throw new Cf.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let c=r.jwkUrl?XO:eN,l=await o(async()=>{if(!i)return a("No authorization header");if(i.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let f=i.substring(s.length);if(!f||f.length===0)return a("No bearer token on authorization header");try{return await c(f,r)}catch(h){let y=new URL(t.url);return"code"in h&&h.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${y.pathname} `,h):e.log.warn(`Invalid token on: ${t.method} ${y.pathname}`,h),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return r.allowUnauthenticatedRequests===!0?t:l;let d=r.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");ic.OpenIdJwtInboundPolicy=tN});var R_=_(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});oc.Auth0JwtInboundPolicy=void 0;var rN=Xt(),nN=o(async(t,e,r,n)=>(0,rN.OpenIdJwtInboundPolicy)(t,e,{issuer:`https://${r.auth0Domain}/`,audience:r.audience,jwkUrl:`https://${r.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"Auth0JwtInboundPolicy");oc.Auth0JwtInboundPolicy=nN});var O_=_(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});sc.BasicAuthInboundPolicy=void 0;var iN=de(),oN=o(async(t,e,r)=>{let n=t.headers.get("Authorization"),i="basic ",s=o(l=>iN.HttpProblems.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),c=await o(async()=>{if(!n)return await s("No Authorization header");if(n.toLowerCase().indexOf(i)!==0)return await s("Invalid Basic token format for Authorization header");let l=n.substring(i.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),h=d.substring(p+1),y=r.accounts.find(b=>b.username===f&&b.password===h);return y||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(c instanceof Response)return r.allowUnauthenticatedRequests?t:c;let u=c.username;return t.user={sub:u,data:c.data},t},"BasicAuthInboundPolicy");sc.BasicAuthInboundPolicy=oN});var N_=_(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});ac.CachingInboundPolicy=void 0;var sN=Zt(),aN=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function cN(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}o(cN,"digestMessage");var uN=o(async(t,e)=>{let r=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],n=[];for(let[d,p]of t.headers.entries())r.includes(d)&&n.push({key:d.toLowerCase(),value:p});n.sort((d,p)=>d.key.localeCompare(p.key));let i=await cN(JSON.stringify(n)),s=new URL(t.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",i);let c=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";c&&a.set("_z-original-method",t.method);let u=`${s.origin}${s.pathname}?${a}`;return new Request(u,{method:c?"GET":t.method})},"createCacheKeyRequest");async function lN(t,e,r,n){let i=await(0,sN.getPolicyCacheName)(n,r),s=await caches.open(i),a=r?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],c=await uN(t,r),u=await s.match(c);return u||(e.addEventListener("responseSent",l=>{try{let d=r.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let f=r?.expirationSecondsTtl??60,h=new Response(p.body,p);aN.forEach(y=>h.headers.delete(y)),h.headers.set("cache-control",`s-maxage=${f}`),e.waitUntil(s.put(c,h))}catch(d){e.log.error(`Error in caching-inbound-policy '${n}': "${d.message}"`,d)}}),t)}o(lN,"CachingInboundPolicy");ac.CachingInboundPolicy=lN});var C_=_(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});cc.ChangeMethodInboundPolicy=void 0;var dN=k(),pN=Ke(),fN=o(async(t,e,r,n)=>{if(!r.method)throw new dN.ConfigurationError(`ChangeMethodInboundPolicy '${n}' options.method must be valid HttpMethod`);return new pN.ZuploRequest(t,{method:r.method})},"ChangeMethodInboundPolicy");cc.ChangeMethodInboundPolicy=fN});var x_=_(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});uc.ClearHeadersInboundPolicy=void 0;var hN=Ke(),mN=o(async(t,e,r)=>{let n=[...r.exclude??[]],i=new Headers;return n.forEach(a=>{let c=t.headers.get(a);c&&i.set(a,c)}),new hN.ZuploRequest(t,{headers:i})},"ClearHeadersInboundPolicy");uc.ClearHeadersInboundPolicy=mN});var L_=_(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});lc.ClearHeadersOutboundPolicy=void 0;var yN=o(async(t,e,r,n)=>{let i=[...n.exclude??[]],s=new Headers;return i.forEach(c=>{let u=t.headers.get(c);u&&s.set(c,u)}),new Response(t.body,{headers:s,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");lc.ClearHeadersOutboundPolicy=yN});var D_=_(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});dc.ClerkJwtInboundPolicy=void 0;var gN=Xt(),bN=o(async(t,e,r,n)=>{let i=new URL(r.frontendApiUrl.startsWith("https://")||r.frontendApiUrl.startsWith("http://")?r.frontendApiUrl:`https://${r.frontendApiUrl}`),s=new URL(i);return s.pathname="/.well-known/jwks.json",(0,gN.OpenIdJwtInboundPolicy)(t,e,{issuer:i.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"ClerkJwtInboundPolicy");dc.ClerkJwtInboundPolicy=bN});var U_=_(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});pc.CognitoJwtInboundPolicy=void 0;var M_=k(),_N=Xt(),EN=o(async(t,e,r,n)=>{if(!r.userPoolId)throw new M_.ConfigurationError("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!r.region)throw new M_.ConfigurationError("region must be set in the options for CognitoJwtInboundPolicy");return(0,_N.OpenIdJwtInboundPolicy)(t,e,{issuer:`https://cognito-idp.${r.region}.amazonaws.com/${r.userPoolId}`,jwkUrl:`https://cognito-idp.${r.region}.amazonaws.com/${r.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"CognitoJwtInboundPolicy");pc.CognitoJwtInboundPolicy=EN});var F_=_(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});fc.CompositeInboundPolicy=void 0;var wN=k(),vN=qr(),k_=En(),TN=o(async(t,e,r,n)=>{if(!r.policies||r.policies.length===0)throw new wN.ConfigurationError(`CompositeInboundPolicy '${n}' must have valid policies defined`);let i=vN.Gateway.instance,s=(0,k_.getInboundPolicyInstances)(r.policies,i?.routeData.policies);return(0,k_.toStackedInboundHandler)(s)(t,e)},"CompositeInboundPolicy");fc.CompositeInboundPolicy=TN});var H_=_(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});mc.CurityPhantomTokenInboundPolicy=void 0;var SN=Zt(),IN=Bt(),hc=de(),PN=o(async(t,e,r,n)=>{let i=t.headers.get("Authorization");if(!i)return hc.HttpProblems.unauthorized(t,e,{detail:"No authorization header"});let s=AN(i);if(!s)return hc.HttpProblems.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await(0,SN.getPolicyCacheName)(n,r),c=new IN.MemoryZoneReadThroughCache(a,e),u=await c.get(s);if(!u){let l=await fetch(r.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${r.clientId}:${r.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)u=d,c.put(s,u,r.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),hc.HttpProblems.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):hc.HttpProblems.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${u}`),t},"CurityPhantomTokenInboundPolicy");mc.CurityPhantomTokenInboundPolicy=PN;function AN(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}o(AN,"getToken")});var q_=_(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});yc.FirebaseJwtInboundPolicy=void 0;var RN=lt(),ON=Xt(),NN=o(async(t,e,r,n)=>((0,RN.optionValidator)(r,n).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),(0,ON.OpenIdJwtInboundPolicy)(t,e,{issuer:`https://securetoken.google.com/${r.projectId}`,audience:r.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)),"FirebaseJwtInboundPolicy");yc.FirebaseJwtInboundPolicy=NN});var $_=_(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});gc.FormDataToJsonInboundPolicy=void 0;var CN=Ke(),xN=o(async(t,e,r)=>{let n="application/x-www-form-urlencoded",i="multipart/form-data",s=t.headers.get("content-type")?.toLowerCase();if(!s||![i,n].includes(s))return r&&r.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${n}' or ${i}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(r&&r.optionalHoneypotName&&a.get(r.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let c={};for(let[d,p]of a)c[d]=p.toString();let u=new Headers(t.headers);return u.set("content-type","application/json"),u.delete("content-length"),new CN.ZuploRequest(t,{body:JSON.stringify(c),headers:u})},"FormDataToJsonInboundPolicy");gc.FormDataToJsonInboundPolicy=xN});var j_=_(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});bc.GeoFilterInboundPolicy=void 0;var LN=k(),DN=de(),oi="__unknown__",MN=o(async(t,e,r,n)=>{let i={allow:{countries:ai(r.allow?.countries,"allow.countries",n),regionCodes:ai(r.allow?.regionCodes,"allow.regionCode",n),asns:ai(r.allow?.asns,"allow.asOrganization",n)},block:{countries:ai(r.block?.countries,"block.countries",n),regionCodes:ai(r.block?.regionCodes,"block.regionCode",n),asns:ai(r.block?.asns,"block.asOrganization",n)},ignoreUnknown:r.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??oi,a=e.incomingRequestProperties.regionCode?.toLowerCase()??oi,c=e.incomingRequestProperties.asn?.toString()??oi,u=i.ignoreUnknown&&s===oi,l=i.ignoreUnknown&&a===oi,d=i.ignoreUnknown&&c===oi,p=i.allow.countries,f=i.allow.regionCodes,h=i.allow.asns;if(p.length>0&&!p.includes(s)&&!u||f.length>0&&!f.includes(a)&&!l||h.length>0&&!h.includes(c)&&!d)return si(t,e,n,s,a,c);let y=i.block.countries,b=i.block.regionCodes,I=i.block.asns;return y.length>0&&y.includes(s)&&!u||b.length>0&&b.includes(a)&&!l||I.length>0&&I.includes(c)&&!d?si(t,e,n,s,a,c):t},"GeoFilterInboundPolicy");bc.GeoFilterInboundPolicy=MN;function si(t,e,r,n,i,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${r}' (country: '${n}', regionCode: '${i}', asn: '${s}')`),DN.HttpProblems.forbidden(t,e,{geographicContext:{country:n,regionCode:i,asn:s}})}o(si,"blockedResponse");function ai(t,e,r){if(typeof t=="string")return t.split(",").map(n=>n.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(n=>n.trim().toLowerCase());throw new LN.ConfigurationError(`Invalid '${e}' for GeoFilterInboundPolicy '${r}': '${t}', must be a string or string[]`)}o(ai,"toLowerStringArray")});var V_=_(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});_c.JWTScopeValidationInboundPolicy=void 0;var UN=o(async(t,e,r)=>{let n=t.user?.data.scope.split(" ")||[];if(!o((s,a)=>a.every(c=>s.includes(c)),"scopeChecker")(n,r.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${r.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");_c.JWTScopeValidationInboundPolicy=UN});var G_=_(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});Ec.MockApiInboundPolicy=void 0;var kN=de(),FN=o(async(t,e,r,n)=>{let i=e.route.raw().responses;if(!i)return xf(n,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(i),a=[];if(s.length===0)return xf(n,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(c=>{i[c].content&&Object.keys(i[c].content).forEach(l=>{let d=i[c].content[l].examples;d&&Object.keys(d).forEach(f=>{a.push({responseName:c,contentName:l,exampleName:f,exampleValue:d[f]})})})}),a=a.filter(c=>!(r.responsePrefixFilter&&!c.responseName.startsWith(r.responsePrefixFilter)||r.contentType&&c.contentName!==r.contentType||r.exampleName&&c.exampleName!==r.exampleName)),r.random&&a.length>1){let c=Math.floor(Math.random()*a.length);return B_(a[c])}else return a.length>0?B_(a[0]):xf(n,t,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");Ec.MockApiInboundPolicy=FN;function B_(t){let e=JSON.stringify(t.exampleValue,null,2),r=new Headers;switch(r.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:r});case"2XX":return new Response(e,{status:200,headers:r});case"3XX":return new Response(e,{status:300,headers:r});case"4XX":return new Response(e,{status:400,headers:r});case"5XX":case"default":return new Response(e,{status:500,headers:r});default:return new Response(e,{status:Number(t.responseName),headers:r})}}o(B_,"generateResponse");var xf=o((t,e,r,n)=>{let i=`Error in policy: ${t} - On route ${e.method} ${r.route.path}. ${n}`;return kN.HttpProblems.internalServerError(e,r,{detail:i})},"getProblemDetailResponse")});var Q_=_(ci=>{"use strict";Object.defineProperty(ci,"__esModule",{value:!0});ci.MoesifInboundPolicy=ci.setMoesifContext=void 0;var HN=k(),qN=Re(),$N="Incoming",jN={logRequestBody:!0,logResponseBody:!0};function K_(t){let e={};return t.forEach((r,n)=>{e[n]=r}),e}o(K_,"headersToObject");function J_(){return new Date().toISOString()}o(J_,"timestamp");var Lf=new WeakMap,VN={};function BN(t,e){let r=Lf.get(t);r||(r=VN);let n=Object.assign({...r},e);Lf.set(t,n)}o(BN,"setMoesifContext");ci.setMoesifContext=BN;async function z_(t,e){let r=t.headers.get("content-type");if(r&&r.indexOf("json")!==0)try{return await t.clone().json()}catch(i){e.log.error(i)}let n=await t.clone().text();return e.log.debug({textBody:n}),n}o(z_,"readBody");var GN={},Df;function W_(){if(!Df)throw new HN.RuntimeError("Invalid State - no _lastLogger");return Df}o(W_,"getLastLogger");function KN(t){let e=GN[t];return e||(e=new qN.BatchDispatch("moesif-inbound",100,async r=>{let n=JSON.stringify(r);W_().debug("posting",n);let i=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:n});i.ok||W_().error({status:i.status,body:await i.text()})})),e}o(KN,"getDispatcher");async function JN(t,e,r,n){Df=e.log;let i=J_(),s=Object.assign(jN,r);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${n}' - applicationId is required`);let a=s.logRequestBody?await z_(t,e):void 0;return e.addResponseSendingFinalHook(async(c,u)=>{let l=KN(s.applicationId),d=t.headers.get("true-client-ip"),p=Lf.get(e)??{},f={time:i,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:K_(t.headers)},h=s.logResponseBody?await z_(c,e):void 0,y={time:J_(),status:c.status,headers:K_(c.headers),body:h},b={request:f,response:y,user_id:p.userId??u.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:$N};l.enqueue(b),e.waitUntil(l.waitUntilFlushed())}),t}o(JN,"MoesifInboundPolicy");ci.MoesifInboundPolicy=JN});var X_=_(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});ui.consumeSubcriptionQuotas=ui.loadSubscription=void 0;var Y_=Je(),Z_=ie();async function zN(t,e,r,n){let i=Y_.SystemLogMap.getLogger(t),{authApiJWT:s,meteringServiceUrl:a}=Z_.Environment.instance,c;try{let l=await fetch(`${a}/internal/v1/metering/${n}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.requestId},method:"GET"});if(l.ok)c=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${r}' - Error loading subscription. ${l.status} - ${p}`),i.error(`MonetizationInboundPolicy '${r}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){i.error(`MonetizationInboundPolicy '${r}' - Error loading subscription`,l)}return c&&c.data&&c.data.length>0?c.data[0]:void 0}o(zN,"loadSubscription");ui.loadSubscription=zN;async function WN(t,e,r,n,i){let{authApiJWT:s,meteringServiceUrl:a}=Z_.Environment.instance,c=Y_.SystemLogMap.getLogger(t);try{let u=await fetch(`${a}/internal/v1/metering/${n}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.requestId},method:"POST",body:JSON.stringify({meters:i})});if(!u.ok){let l=await u.json(),d=l.detail??l.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota. ${u.status} - ${d}`),c.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota. ${u.status} - ${d}`)}}catch(u){t.log.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota.`),c.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota.`,u)}}o(WN,"consumeSubcriptionQuotas");ui.consumeSubcriptionQuotas=WN});var eE=_(Nr=>{"use strict";Object.defineProperty(Nr,"__esModule",{value:!0});Nr.compareMeters=Nr.parseAllowedSubscriptionStatuses=Nr.validateMeters=void 0;var tn=k(),QN=Jt(),YN=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function ZN(t,e){try{let r=[];for(let n in t)typeof t[n]!="number"&&!(Number.isInteger(t[n])&&/^-?\d+$/.test(t[n].toString()))&&r.push(n);if(r.length>0)throw new tn.ConfigurationError(r.length>1?`The values found in these properties are not integers : ${r.join(", ")}`:`The value in property '${r[0]}' is not an integer`)}catch(r){throw r instanceof tn.ConfigurationError?new tn.ConfigurationError(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${r.message}`):r}}o(ZN,"validateMeters");Nr.validateMeters=ZN;function XN(t,e){if(t)try{if(t.length===0)throw new tn.ConfigurationError("Must set valid subscription statuses");let r=(0,QN.parseValueToStringArray)(t),n=[];for(let i of r)YN.has(i)||n.push(i);if(n.length>0)throw new tn.ConfigurationError(`Found the following invalid statuses: ${n.join(", ")}`);return t}catch(r){throw r instanceof tn.ConfigurationError?new tn.ConfigurationError(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${r.message}`):r}else return["active","incomplete","trialing"]}o(XN,"parseAllowedSubscriptionStatuses");Nr.parseAllowedSubscriptionStatuses=XN;function eC(t,e){let r={},n={};for(let i in e)t.hasOwnProperty(i)?r[i]=e[i]:n[i]=e[i];return{metersInSubscription:r,metersNotInSubscription:n}}o(eC,"compareMeters");Nr.compareMeters=eC});var nE=_(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});vc.MonetizationInboundPolicy=void 0;var rn=Fr(),nn=_p(),wc=Yi(),tE=k(),tC=_n(),on=de(),rC=Jt(),nC=lt(),rE=X_(),io=eE(),Mf=class extends tC.InboundPolicy{static{o(this,"MonetizationInboundPolicy")}static getSubscription(e){return nn.ContextData.get(e,rn.METERING_SUBSCRIPTION_CONTEXT_DATA)}static setMeters(e,r){(0,io.validateMeters)(r,"setMeters"),nn.ContextData.set(e,rn.DYNAMIC_METERS_CONTEXT_DATA,r)}async handler(e,r){(0,nC.optionValidator)(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,i=(0,rC.statusCodesStringToNumberArray)(this.options.meterOnStatusCodes),s=nn.ContextData.get(r,rn.DYNAMIC_METERS_CONTEXT_DATA),a={...this.options.meters,...s};(0,io.validateMeters)(a,this.policyName);let c=this.options.allowRequestsWithoutSubscription??!1,u=(0,io.parseAllowedSubscriptionStatuses)(this.options.allowedSubscriptionStatuses,this.policyName);r.addResponseSendingFinalHook(async(b,I,A)=>{let g=nn.ContextData.get(A,rn.METERING_SUBSCRIPTION_CONTEXT_DATA);if((this.options.allowRequestsWithoutSubscription??!1)&&!g){A.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(wc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=wc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new tE.ConfigurationError(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let O=nn.ContextData.get(A,rn.DYNAMIC_METERS_CONTEXT_DATA),V={...this.options.meters,...O};if((0,io.validateMeters)(V,this.policyName),i.includes(b.status)&&g&&V){A.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${g.id}' with meters '${JSON.stringify(V)} on response status '${b.status}'`);let{metersInSubscription:E,metersNotInSubscription:T}=(0,io.compareMeters)(g.meters,V);if(T&&Object.keys(T).length>0){let C=Object.keys(T);A.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${C}'`)}await(0,rE.consumeSubcriptionQuotas)(A,g.id,this.policyName,this.options.bucketId,E)}});let l=e.user;if(!l)return c?e:on.HttpProblems.unauthorized(e,r,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(wc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=wc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new tE.ConfigurationError(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await(0,rE.loadSubscription)(r,d,this.policyName,this.options.bucketId);if(!p)return r.log.warn("No valid subscription found"),c?e:on.HttpProblems.unauthorized(e,r,{detail:"No valid subscription found"});if(!u.includes(p.status)&&!c)return r.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),on.HttpProblems.unauthorized(e,r,{detail:"No valid subscription found"});u.includes(p.status)&&(r.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),nn.ContextData.set(r,rn.METERING_SUBSCRIPTION_CONTEXT_DATA,p));let f=nn.ContextData.get(r,rn.METERING_SUBSCRIPTION_CONTEXT_DATA);if(!f)return c?e:(r.log.warn("Subscription is not available for user"),on.HttpProblems.paymentRequired(e,r,{detail:"Subscription is not available for user",title:"No Subscription"}));if(f&&Object.keys(f.meters).length===0)return r.log.error(`Quota is not set up for subscription '${f.id}'`),on.HttpProblems.tooManyRequests(e,r,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let y=Object.keys(a).filter(b=>!Object.keys(f.meters).includes(b));if(y.length>0)return r.log.warn(`The following policy meters are not present in the subscription: ${y.join(", ")}`),on.HttpProblems.tooManyRequests(e,r,{detail:`The following policy meters are not present in the subscription: ${y.join(", ")}`,title:"Quota Exceeded"});for(let b of Object.keys(a))if(f.meters[b].available<=0&&!n)return on.HttpProblems.tooManyRequests(e,r,{detail:`Quota exceeded for meter '${b}'`,title:"Quota Exceeded"});return e}};vc.MonetizationInboundPolicy=Mf});var iE=_(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});Tc.OktaJwtInboundPolicy=void 0;var iC=Xt(),oC=o(async(t,e,r,n)=>(0,iC.OpenIdJwtInboundPolicy)(t,e,{issuer:r.issuerUrl,audience:r.audience,jwkUrl:`${r.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"OktaJwtInboundPolicy");Tc.OktaJwtInboundPolicy=oC});var oE=_(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});Sc.PropelAuthJwtInboundPolicy=void 0;var sC=(ra(),xo(ta)),aC=Xt(),Uf,cC=o(async(t,e,r,n)=>{if(!Uf)try{Uf=await(0,sC.importSPKI)(r.verifierKey,"RS256")}catch(i){throw e.log.error("Could not import verifier key"),i}return(0,aC.OpenIdJwtInboundPolicy)(t,e,{issuer:r.authUrl,secret:Uf,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests,subPropertyName:"user_id"},n)},"PropelAuthJwtInboundPolicy");Sc.PropelAuthJwtInboundPolicy=cC});var sE=_(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.throwIfStateNotObject=Z.throwIfStateNotNumber=Z.throwIfStateNotString=Z.throwIfStateUndefinedOrNull=Z.throwIfStateUndefined=Z.throwIfOptionNotObject=Z.throwIfOptionNotNumber=Z.throwIfOptionNotString=Z.throwIfOptionUndefinedOrNull=Z.throwIfOptionUndefined=Z.OptionTypeError=Z.OptionUndefinedError=Z.throwIfNotNumber=Z.throwIfNotString=Z.throwIfUndefinedOrNull=Z.throwIfUndefined=Z.ArgumentTypeError=Z.ArgumentUndefinedError=Z.ValidationError=void 0;var Ye=at(),dt=class extends Error{static{o(this,"ValidationError")}constructor(e){super(e)}};Z.ValidationError=dt;var oo=class extends dt{static{o(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}};Z.ArgumentUndefinedError=oo;var so=class extends dt{static{o(this,"ArgumentTypeError")}constructor(e,r){super(`The argument '${e}' must be of type '${r}'.`)}};Z.ArgumentTypeError=so;function uC(t,e){if((0,Ye.isUndefined)(t))throw new oo(e)}o(uC,"throwIfUndefined");Z.throwIfUndefined=uC;function kf(t,e){if((0,Ye.isUndefinedOrNull)(t))throw new oo(e)}o(kf,"throwIfUndefinedOrNull");Z.throwIfUndefinedOrNull=kf;function lC(t,e){if(kf(t,e),!(0,Ye.isString)(t))throw new so(e,"string")}o(lC,"throwIfNotString");Z.throwIfNotString=lC;function dC(t,e){if(kf(t,e),!(0,Ye.isNumber)(t))throw new so(e,"number")}o(dC,"throwIfNotNumber");Z.throwIfNotNumber=dC;var ao=class extends dt{static{o(this,"OptionUndefinedError")}constructor(e,r,n){super(`The option '${n}' on the ${e} named '${r}' is undefined.`)}};Z.OptionUndefinedError=ao;var li=class extends dt{static{o(this,"OptionTypeError")}constructor(e,r,n,i){super(`The option '${n}' on the ${e} named '${r}' must be of type '${i}'.`)}};Z.OptionTypeError=li;function pC(t,e,r,n){if((0,Ye.isUndefined)(n))throw new ao(t,e,r)}o(pC,"throwIfOptionUndefined");Z.throwIfOptionUndefined=pC;function Ic(t,e,r,n){if((0,Ye.isUndefinedOrNull)(n))throw new ao(t,e,r)}o(Ic,"throwIfOptionUndefinedOrNull");Z.throwIfOptionUndefinedOrNull=Ic;function fC(t,e,r,n){if(Ic(t,e,r,n),!(0,Ye.isString)(n))throw new li(t,e,r,"string")}o(fC,"throwIfOptionNotString");Z.throwIfOptionNotString=fC;function hC(t,e,r,n){if(Ic(t,e,r,n),!(0,Ye.isNumber)(n))throw new li(t,e,r,"number")}o(hC,"throwIfOptionNotNumber");Z.throwIfOptionNotNumber=hC;function mC(t,e,r,n){if(Ic(t,e,r,n),!(0,Ye.isObject)(n))throw new li(t,e,r,"object")}o(mC,"throwIfOptionNotObject");Z.throwIfOptionNotObject=mC;function yC(t,e){if((0,Ye.isUndefined)(t))throw new dt(e)}o(yC,"throwIfStateUndefined");Z.throwIfStateUndefined=yC;function Pc(t,e){if((0,Ye.isUndefinedOrNull)(t))throw new dt(e)}o(Pc,"throwIfStateUndefinedOrNull");Z.throwIfStateUndefinedOrNull=Pc;function gC(t,e){if(Pc(t,e),!(0,Ye.isString)(t))throw new dt(e);return!0}o(gC,"throwIfStateNotString");Z.throwIfStateNotString=gC;function bC(t,e){if(Pc(t,e),!(0,Ye.isNumber)(t))throw new dt(e);return!0}o(bC,"throwIfStateNotNumber");Z.throwIfStateNotNumber=bC;function _C(t,e){if(Pc(t,e),!(0,Ye.isObject)(t))throw new dt(e);return!0}o(_C,"throwIfStateNotObject");Z.throwIfStateNotObject=_C});var aE=_(di=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});di.InMemoryRedisClient=di.StandardRedisClient=void 0;var Ff=k(),Ac=sE(),Hf=class t{static{o(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,r,n,i){this.redisClientUrl=e,this.clientAuthToken=r,this.deploymentName=n,this.userAgent=i}static initialize(e,r,n,i){return(0,Ac.throwIfNotString)(e,"redisClientUrl"),(0,Ac.throwIfNotString)(r,"clientAuthToken"),t.instance||(t.instance=new t(e,r,n,i)),t.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:r,method:n,requestId:i}){(0,Ac.throwIfNotString)(e,"url");let s=await fetch(`${this.redisClientUrl}${e}`,{method:n,body:r,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":i,"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 Ff.SystemError("Redis client failed with 401: Unauthorized"):new Ff.SystemError(`Redis client failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}};di.StandardRedisClient=Hf;var qf=class{static{o(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:r,method:n}){if((0,Ac.throwIfNotString)(e,"url"),n==="POST"&&e==="/rate-limit"){let{incrBy:i,expire:s,key:a}=JSON.parse(r),c=Date.now()+s*1e3,u=this.keyValueStore.get(a);u?Date.now()>u.expiresAt?this.keyValueStore.set(a,{value:i,expiresAt:c}):this.keyValueStore.set(a,{value:u.value+i,expiresAt:u.expiresAt}):this.keyValueStore.set(a,{value:i,expiresAt:c});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new Ff.SystemError("The in-memory redis client only supports /rate-limit calls")}};di.InMemoryRedisClient=qf});var $f=_(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.RETRY_AFTER_HEADER=Ae.wrapUserFunction=Ae.getCountAndUpdateExpiry=Ae.getRedisClient=Ae.getAll=Ae.getUser=Ae.getIP=Ae.getRealIP=void 0;var Cr=k(),Rc=ie(),cE=aE(),uE=at(),EC=o(t=>{let e=t.headers.get("x-real-ip")??t.headers.get("true-client-ip")??t.headers.get("cf-connecting-ip");if(e)return e;let r=t.headers.get("x-forwarded-for");return r?r.split(",")[0]:"127.0.0.1"},"getRealIP");Ae.getRealIP=EC;var wC=o(async t=>({key:`ip-${(0,Ae.getRealIP)(t)}`}),"getIP");Ae.getIP=wC;var vC=o(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser");Ae.getUser=vC;var TC=o(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll");Ae.getAll=TC;var Oc;function SC(t,e){let r;if(Oc)return Oc;if(Rc.Environment.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),r=new cE.InMemoryRedisClient,Oc=r,r;let{authApiJWT:n,redisURL:i}=Rc.Environment.instance;if(!(0,uE.isString)(i))throw new Cr.SystemError(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!(0,uE.isString)(n))throw new Cr.SystemError(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(i&&(r=cE.StandardRedisClient.initialize(i,n,Rc.Environment.instance.deploymentName??"unknown",Rc.Environment.instance.systemUserAgent)),!r||!r.isEnabled())throw new Cr.SystemError(`RateLimitInboundPolicy '${t}' - no redis ('${r}') or redis.isEnabled ('${r?.isEnabled}) is false`);return Oc=r,r}o(SC,"getRedisClient");Ae.getRedisClient=SC;async function IC(t,e,r,n,i){let s=Math.floor(e*60);return await r.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:s,key:t}),requestId:i})}o(IC,"getCountAndUpdateExpiry");Ae.getCountAndUpdateExpiry=IC;function PC(t,e){let r;if(t.rateLimitBy==="function"){if(!t.identifier)throw new Cr.ConfigurationError(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new Cr.ConfigurationError(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new Cr.ConfigurationError(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=t.identifier.module[t.identifier.export],!r||typeof r!="function")throw new Cr.ConfigurationError(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return o(async(i,s,a)=>{let c=await r(i,s,a);if(!c.key){let u=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(c,null,2)}'`;throw s.log.error(u),new Cr.RuntimeError(u)}return c},"outerFunction")}o(PC,"wrapUserFunction");Ae.wrapUserFunction=PC;Ae.RETRY_AFTER_HEADER="Retry-After"});var dE=_(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});Nc.AsyncRateLimitInboundPolicy=void 0;var AC=or(),RC=Zt(),OC=de(),NC=Je(),CC=ie(),xC=Bt(),sn=$f(),lE=(0,AC.debug)("zuplo:policies:RateLimitInboundPolicy"),LC=o(async(t,e,r,n)=>{let i=NC.SystemLogMap.getLogger(e),s=o((E,T)=>{let C={};return(!E||E==="retry-after")&&(C[sn.RETRY_AFTER_HEADER]=T.toString()),OC.HttpProblems.tooManyRequests(t,e,void 0,C)},"rateLimited"),c={function:(0,sn.wrapUserFunction)(r,n),user:sn.getUser,ip:sn.getIP,all:sn.getAll}[r.rateLimitBy],u=await c(t,e,n),l=u.key,d=u.requestsAllowed??r.requestsAllowed,p=u.timeWindowMinutes??r.timeWindowMinutes,f=r.headerMode??"retry-after",h=(0,sn.getRedisClient)(n,i),b=`bucket/${CC.Environment.instance.build.BUILD_ID}/${n}/${l}`,I=await(0,RC.getPolicyCacheName)(n,r),A=new xC.MemoryZoneReadThroughCache(I,e),g=(0,sn.getCountAndUpdateExpiry)(b,p,h,i,e.requestId),v;o(async()=>{let E=await g;if(E.count>d){let T=Date.now()+E.ttlSeconds*1e3;A.put(b,T,E.ttlSeconds),lE(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${b}' (async mode)`),v=s(f,E.ttlSeconds)}},"asyncCheck")();let V=await A.get(b);if(V!==void 0&&V>Date.now()){lE(`RateLimitInboundPolicy '${n}' - returning 429 from cache for '${b}' (async mode)`);let E=Math.round((V-Date.now())/1e3);return s(f,E)}return e.addResponseSendingHook(async E=>v??E),t},"AsyncRateLimitInboundPolicy");Nc.AsyncRateLimitInboundPolicy=LC});var fE=_(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});Cc.RateLimitInboundPolicy=void 0;var DC=or(),MC=k(),UC=de(),kC=Je(),FC=ie(),HC=dE(),an=$f(),pE=(0,DC.debug)("zuplo:policies:RateLimitInboundPolicy"),qC="strict",$C=o(async(t,e,r,n)=>{if((r.mode??qC)==="async")return(0,HC.AsyncRateLimitInboundPolicy)(t,e,r,n);let s=Date.now(),a=kC.SystemLogMap.getLogger(e),c=o((l,d)=>{if(r.throwOnFailure)throw new MC.SystemError(l,{cause:d});a.error(l,d)},"throwOrLog"),u=o((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[an.RETRY_AFTER_HEADER]=d.toString()),UC.HttpProblems.tooManyRequests(t,e,void 0,p)},"rateLimited");try{let d={function:(0,an.wrapUserFunction)(r,n),user:an.getUser,ip:an.getIP,all:an.getAll}[r.rateLimitBy],p=await d(t,e,n),f=p.key,h=p.requestsAllowed??r.requestsAllowed,y=p.timeWindowMinutes??r.timeWindowMinutes,b=r.headerMode??"retry-after",I=(0,an.getRedisClient)(n,a),g=`bucket/${FC.Environment.instance.build.BUILD_ID}/${n}/${f}`,v=await(0,an.getCountAndUpdateExpiry)(g,y,I,a,e.requestId);return v.count>h?(pE(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${g}' (strict mode)`),u(b,v.ttlSeconds)):t}catch(l){return c(l.message,l),t}finally{let l=Date.now()-s;pE(`RateLimitInboundPolicy '${n}' - latency ${l}ms`)}},"RateLimitInboundPolicy");Cc.RateLimitInboundPolicy=$C});var gE=_(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});xc.ReadmeMetricsInboundPolicy=void 0;var jC=Re(),jf=ie(),hE=Jt(),Vf;function mE(t){let e=[];for(let[r,n]of t)e.push({name:r,value:n});return e}o(mE,"headersToNameValuePairs");function VC(t){let e=[];return Object.entries(t).forEach(([r,n])=>{e.push({name:r,value:n})}),e}o(VC,"queryToNameValueParis");function BC(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}o(BC,"parseIntOrUndefined");var yE={};async function GC(t,e,r,n){let i=new Date,s=Date.now();return Vf||(Vf={name:"zuplo",version:jf.Environment.instance.build.ZUPLO_VERSION,comment:`zuplo/${jf.Environment.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let c=r.userLabelPropertyPath&&t.user?(0,hE.getValueFromRequestUser)(t.user,r.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,u=r.userEmailPropertyPath&&t.user?(0,hE.getValueFromRequestUser)(t.user,r.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:r.development!==void 0?r.development:jf.Environment.instance.isDeno,group:{label:c,email:u,id:t.user?.sub??"anonymous"},request:{log:{creator:Vf,entries:[{startedDateTime:i.toISOString(),time:Date.now()-s,request:{method:t.method,url:r.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:mE(t.headers),queryString:VC(t.query)},response:{status:a.status,statusText:a.statusText,headers:mE(a.headers),content:{size:BC(t.headers.get("content-length"))}}}]}}},d=yE[r.apiKey];if(!d){let p=r.apiKey;d=new jC.BatchDispatch("readme-metering-inbound-policy",10,async f=>{try{let h=r.url??"https://metrics.readme.io/request",y=await fetch(h,{method:"POST",body:JSON.stringify(f),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});y.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${n}'. ${y.status}: '${await y.text()}'`)}catch(h){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${n}': '${h.message}'`),h}}),yE[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(c){e.log.error(c)}}),t}o(GC,"ReadmeMetricsInboundPolicy");xc.ReadmeMetricsInboundPolicy=GC});var bE=_(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});Lc.RemoveHeadersInboundPolicy=void 0;var KC=k(),JC=Ke(),zC=o(async(t,e,r,n)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new KC.ConfigurationError(`RemoveHeadersInboundPolicy '${n}' options.headers must be a non-empty string array of header names`);let s=new Headers(t.headers);return i.forEach(c=>{s.delete(c)}),new JC.ZuploRequest(t,{headers:s})},"RemoveHeadersInboundPolicy");Lc.RemoveHeadersInboundPolicy=zC});var _E=_(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});Dc.RemoveHeadersOutboundPolicy=void 0;var WC=k(),QC=o(async(t,e,r,n,i)=>{let s=n?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new WC.ConfigurationError(`RemoveHeadersOutboundPolicy '${i}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return s.forEach(u=>{a.delete(u)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");Dc.RemoveHeadersOutboundPolicy=QC});var EE=_(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});Mc.RemoveQueryParamsInboundPolicy=void 0;var YC=k(),ZC=Ke(),XC=o(async(t,e,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length===0)throw new YC.ConfigurationError(`RemoveQueryParamsInboundPolicy '${n}' options.params must be a non-empty string array of header names`);let s=new URL(t.url);return i.forEach(c=>{s.searchParams.delete(c)}),new ZC.ZuploRequest(s.toString(),t)},"RemoveQueryParamsInboundPolicy");Mc.RemoveQueryParamsInboundPolicy=XC});var wE=_(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});Uc.ReplaceStringOutboundPolicy=void 0;var ex=o(async(t,e,r,n)=>{let i=await t.text(),s=n.mode==="regexp"?new RegExp(n.match,"gm"):n.match,a=i.replaceAll(s,n.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");Uc.ReplaceStringOutboundPolicy=ex});var TE=_(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});kc.RequestSizeLimitInboundPolicy=void 0;var vE=o(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),tx=o(async(t,e,r)=>{let n=r.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let i=t.headers.get("content-length"),s=i!==null?parseInt(i):void 0;return s&&!isNaN(s)&&s>r.maxSizeInBytes?vE():s&&n?t:(await t.clone().text()).length>r.maxSizeInBytes?vE():t},"RequestSizeLimitInboundPolicy");kc.RequestSizeLimitInboundPolicy=tx});var Fc=_(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.sanitizedIdentifierName=pt.getIdForRefSchema=pt.getIdForRequestBodySchema=pt.getIdForParameterSchema=pt.getRawOperationDataIdentifierName=void 0;function rx(t,e,r){return`_${cn(t+"_"+e+"_"+r)}`}o(rx,"getRawOperationDataIdentifierName");pt.getRawOperationDataIdentifierName=rx;function nx(t,e,r,n){return`_${cn(t.toLowerCase())}_`+e.toLowerCase()+"_"+r.toLowerCase()+`_${n.toLowerCase()}`}o(nx,"getIdForParameterSchema");pt.getIdForParameterSchema=nx;function ix(t,e,r){return`_${cn(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${cn(r.toLowerCase())}`}o(ix,"getIdForRequestBodySchema");pt.getIdForRequestBodySchema=ix;function ox(t,e){return`_${cn(t)}__${cn(e)}`}o(ox,"getIdForRefSchema");pt.getIdForRefSchema=ox;function cn(t){let e=[];for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);n>="0".charCodeAt(0)&&n<="9".charCodeAt(0)||n>="A".charCodeAt(0)&&n<="Z".charCodeAt(0)||n>="a".charCodeAt(0)&&n<="z".charCodeAt(0)?e.push(t.charAt(r)):e.push("_")}return e.join("")}o(cn,"sanitizedIdentifierName");pt.sanitizedIdentifierName=cn});var co=_(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.getErrorsFromValidator=je.shouldReject=je.shouldLog=je.logErrors=je.validateParameters=je.getParametersForOperation=void 0;var sx=qr(),ax=Fc(),cx=o(t=>{let e=t.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");je.getParametersForOperation=cx;var ux=o((t,e,r,n,i)=>{let s=[],a=!0,c=[];return t.forEach(u=>{let l=u.required||i==="path";if(l&&!e[u.name])a=!1,s.push(`Required ${i} parameter '${u.name}' not found`);else if(!(!l&&!e[u.name])){let d=(0,ax.getIdForParameterSchema)(r,n,i,u.name),p=sx.Gateway.instance.schemaValidator[d],f=p(e[u.name]),h=(0,je.getErrorsFromValidator)(p.errors);f||(a=!1,c.push(`${i} parameter: ${u.name} : ${e[u.name]}`),s.push(`Invalid value for ${i} parameter: '${u.name}' ${h.join(", ")}`))}}),{isValid:a,invalidValues:c,errors:s}},"validateParameters");je.validateParameters=ux;var lx=o((t,e,r,n,i)=>{n?t.log[e](r,n,i):t.log[e](r,i)},"logErrors");je.logErrors=lx;var dx=o(t=>t==="log-only"||t==="reject-and-log","shouldLog");je.shouldLog=dx;var px=o(t=>t==="reject-only"||t==="reject-and-log","shouldReject");je.shouldReject=px;var fx=o(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");je.getErrorsFromValidator=fx});var SE=_(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});qc.handleBodyValidation=void 0;var hx=qr(),Hc=de(),mx=Fc(),tt=co();async function yx(t,e,r){if(!r.validateBody||r.validateBody==="none")return;let n;try{n=await e.clone().json()}catch(h){let y=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,b=Hc.HttpProblems.badRequest(e,t,{detail:`${y}, see errors property for more details`,errors:`${h}`});if((0,tt.shouldLog)(r.validateBody)&&(0,tt.logErrors)(t,r.logLevel??"info",y,[n],h),(0,tt.shouldReject)(r.validateBody))return b}if(!e.headers.get("Content-Type")){let h=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,y=Hc.HttpProblems.badRequest(e,t,{detail:h});return(0,tt.shouldLog)(r.validateBody)&&(0,tt.logErrors)(t,r.logLevel??"info",h,[n],[h]),(0,tt.shouldReject)(r.validateBody)?y:void 0}let i=e.headers.get("Content-Type"),s=i.indexOf(";");s>-1&&(i=i.substring(0,s));let a=(0,mx.getIdForRequestBodySchema)(t.route.path,e.method,i),c=hx.Gateway.instance.schemaValidator[a];if(!c){let h=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,y=Hc.HttpProblems.badRequest(e,t,{detail:h});return(0,tt.shouldLog)(r.validateBody)&&(0,tt.logErrors)(t,r.logLevel??"info",h,[n],[h]),(0,tt.shouldReject)(r.validateBody)?y:void 0}if(c(n))return;let l=c.errors,d="Request body did not pass validation",p=(0,tt.getErrorsFromValidator)(l),f=Hc.HttpProblems.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if((0,tt.shouldLog)(r.validateBody)&&(0,tt.logErrors)(t,r.logLevel??"info",d,[n],p),(0,tt.shouldReject)(r.validateBody))return f}o(yx,"handleBodyValidation");qc.handleBodyValidation=yx});var IE=_($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});$c.handleHeadersValidation=void 0;var gx=de(),uo=co();function bx(t,e,r){if(!r.validateHeaders||r.validateHeaders==="none")return;let n={};e.headers.forEach((a,c)=>{n[c]=a});let i=(0,uo.getParametersForOperation)(t),s=(0,uo.validateParameters)(i.filter(a=>a.location==="header"),n,t.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",c=gx.HttpProblems.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:s.errors});if((0,uo.shouldLog)(r.validateHeaders)&&(0,uo.logErrors)(t,r.logLevel??"info",a,s.invalidValues,s.errors),(0,uo.shouldReject)(r.validateHeaders))return c}}o(bx,"handleHeadersValidation");$c.handleHeadersValidation=bx});var PE=_(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});jc.handlePathParameterValidation=void 0;var _x=de(),lo=co();function Ex(t,e,r){if(!r.validatePathParameters||r.validatePathParameters==="none")return;let n=(0,lo.getParametersForOperation)(t),i=(0,lo.validateParameters)(n.filter(s=>s.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!i.isValid){let s="Path parameters validation failed",a=_x.HttpProblems.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:i.errors});if((0,lo.shouldLog)(r.validatePathParameters)&&(0,lo.logErrors)(t,r.logLevel??"info",s,i.invalidValues,i.errors),(0,lo.shouldReject)(r.validatePathParameters))return a}}o(Ex,"handlePathParameterValidation");jc.handlePathParameterValidation=Ex});var AE=_(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});Vc.handleQueryParameterValidation=void 0;var wx=de(),po=co();function vx(t,e,r){if(!r.validateQueryParameters||r.validateQueryParameters==="none")return;let n=(0,po.getParametersForOperation)(t),i=(0,po.validateParameters)(n.filter(s=>s.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!i.isValid){let s="Query parameters validation failed",a=wx.HttpProblems.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:i.errors});if((0,po.shouldLog)(r.validateQueryParameters)&&(0,po.logErrors)(t,r.logLevel??"info",s,i.invalidValues,i.errors),(0,po.shouldReject)(r.validateQueryParameters))return a}}o(vx,"handleQueryParameterValidation");Vc.handleQueryParameterValidation=vx});var RE=_(un=>{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.SchemaBasedRequestValidation=un.RequestValidationInboundPolicy=void 0;var Tx=SE(),Sx=IE(),Ix=PE(),Px=AE(),Ax=o(async(t,e,r)=>{let n=(0,Px.handleQueryParameterValidation)(e,t,r);if(n!==void 0||(n=(0,Ix.handlePathParameterValidation)(e,t,r),n!==void 0)||(n=(0,Sx.handleHeadersValidation)(e,t,r),n!==void 0))return n;let i=await(0,Tx.handleBodyValidation)(e,t,r);return i!==void 0?i:t},"RequestValidationInboundPolicy");un.RequestValidationInboundPolicy=Ax;un.SchemaBasedRequestValidation=un.RequestValidationInboundPolicy});var OE=_(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});Bc.RequireOriginInboundPolicy=void 0;var Rx=k(),Ox=de(),Nx=o(async(t,e,r,n)=>{if(r.origins===void 0||r.origins.length===0)throw new Rx.ConfigurationError(`RequireOriginInboundPolicy '${n}' configuration error - no allowed origins specified`);let i=typeof r.origins=="string"?r.origins.split(","):r.origins;i=i.map(a=>a.trim());let s=t.headers.get("origin");if(!s||!i.includes(s)){let a=r.failureDetail??"Forbidden";return Ox.HttpProblems.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");Bc.RequireOriginInboundPolicy=Nx});var NE=_(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});Gc.SetBodyInboundPolicy=void 0;var Cx=Ke(),xx=o(async(t,e,r)=>new Cx.ZuploRequest(t,{body:r.body}),"SetBodyInboundPolicy");Gc.SetBodyInboundPolicy=xx});var xE=_(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});Kc.SetHeadersInboundPolicy=void 0;var CE=k(),Lx=Ke(),Dx=o(async(t,e,r,n)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new CE.ConfigurationError(`SetHeadersInboundPolicy '${n}' options.headers must be a valid array of { name, value }`);let s=new Headers(t.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new CE.ConfigurationError(`SetHeadersInboundPolicy '${n}' each option.headers[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!s.has(c.name)||u)&&s.set(c.name,c.value)}),new Lx.ZuploRequest(t,{headers:s})},"SetHeadersInboundPolicy");Kc.SetHeadersInboundPolicy=Dx});var DE=_(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});Jc.SetHeadersOutboundPolicy=void 0;var LE=k(),Mx=o(async(t,e,r,n,i)=>{let s=n.headers;if(!s||!Array.isArray(s)||s.length==0)throw new LE.ConfigurationError(`SetHeadersOutboundPolicy '${i}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return s.forEach(u=>{if(!u.name||u.name.length===0)throw new LE.ConfigurationError(`SetHeadersOutboundPolicy '${i}' each option.headers[] entry must have a name property`);let l=u.overwrite===void 0?!0:u.overwrite;(!a.has(u.name)||l)&&a.set(u.name,u.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");Jc.SetHeadersOutboundPolicy=Mx});var UE=_(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});zc.SetQueryParamsInboundPolicy=void 0;var ME=k(),Ux=Ke(),kx=o(async(t,e,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length==0)throw new ME.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' options.params must be a valid array of { name, value }`);let s=new URL(t.url);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new ME.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' each option.params[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!s.searchParams.has(c.name)||u)&&s.searchParams.set(c.name,c.value)}),new Ux.ZuploRequest(s.toString(),t)},"SetQueryParamsInboundPolicy");zc.SetQueryParamsInboundPolicy=kx});var kE=_(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});Wc.SetStatusOutboundPolicy=void 0;var Fx=o(async(t,e,r,n,i)=>{if(!n.status||isNaN(n.status)||n.status<100||n.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${i}' - status must be a valid number between 100 and 599, not '${n.status}'`);return new Response(t.body,{headers:t.headers,status:n.status,statusText:n.statusText??t.statusText})},"SetStatusOutboundPolicy");Wc.SetStatusOutboundPolicy=Fx});var FE=_(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});Qc.SleepInboundPolicy=void 0;var Hx=k(),qx=o(async t=>new Promise(r=>{setTimeout(r,t)}),"sleep"),$x=o(async(t,e,r,n)=>{if(!r||r.sleepInMs===void 0||isNaN(r.sleepInMs))throw new Hx.ConfigurationError(`SleepInboundPolicy '${n} must have a valid options.sleepInMs value`);return await qx(r.sleepInMs),t},"SleepInboundPolicy");Qc.SleepInboundPolicy=$x});var qE=_(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});Yc.SupabaseJwtInboundPolicy=void 0;var HE=k(),jx=de(),Vx=Ke(),Bx=lt(),Gx=Xt(),Kx=o(async(t,e,r,n)=>{(0,Bx.optionValidator)(r,n).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let i={secret:r.secret,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1},s=await(0,Gx.OpenIdJwtInboundPolicy)(t,e,i,n);if(s instanceof Response)return s;if(!(s instanceof Vx.ZuploRequest))throw new HE.SystemError("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=r.requiredClaims;if(!a)return s;let c=t.user?.data.app_metadata;if(!c)throw new HE.RuntimeError(`SupabaseJwtInboundPolicy policy '${n}' - has requiredClaims but the JWT token had no app_metadata property`);let u=Object.keys(a),l=[];return u.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(c[d])||l.push(d):p!==c[d]&&l.push(d)}),l.length>0?jx.HttpProblems.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");Yc.SupabaseJwtInboundPolicy=Kx});var jE=_(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});Zc.UpstreamAzureAdServiceAuthInboundPolicy=void 0;var Jx=Zt(),zx=Bt(),$E=k(),Wx=kn(),Qx=lt(),Yx=o(async(t,e,r,n)=>{(0,Qx.optionValidator)(r,n).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let i=await(0,Jx.getPolicyCacheName)(n,r),s=new zx.MemoryZoneReadThroughCache(i,e),a=await s.get(n);if(!a){let c=await Zx(r,e);s.put(n,c.access_token,c.expires_in-(r.expirationOffsetSeconds??300)),a=c.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");Zc.UpstreamAzureAdServiceAuthInboundPolicy=Yx;async function Zx(t,e){let r=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),n=await(0,Wx.fetchRetry)({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:r});if(n.status!==200){try{let s=await n.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new $E.RuntimeError("Could not get token from Azure AD")}let i=await n.json();if(i&&typeof i=="object"&&"access_token"in i&&typeof i.access_token=="string"&&"expires_in"in i&&typeof i.expires_in=="number")return{access_token:i.access_token,expires_in:i.expires_in};throw new $E.RuntimeError("Response returned from Azure AD is not in the expected format.")}o(Zx,"getAccessToken")});var BE=_(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});Xc.UpstreamFirebaseAdminAuthInboundPolicy=void 0;var Xx=Zt(),eL=Bt(),tL=k(),Bf=Fn(),rL=lt(),VE="https://accounts.google.com/o/oauth2/token",Gf,nL=o(async(t,e,r,n)=>{(0,rL.optionValidator)(r,n).required("serviceAccountJson","string"),Gf||(Gf=await Bf.GcpServiceAccount.init(r.serviceAccountJson));let i={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(0,Xx.getPolicyCacheName)(n,r),a=new eL.MemoryZoneReadThroughCache(s,e),c=await a.get(n);if(!c){let u=await(0,Bf.getTokenFromGcpServiceAccount)({serviceAccount:Gf,audience:VE,payload:i}),l=await(0,Bf.exchangeGgpJwtForIdToken)(VE,u,{retries:r.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new tL.RuntimeError("Invalid OAuth response from Firebase");c=l.access_token,a.put(n,c,(l.expires_in??3600)-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${c}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");Xc.UpstreamFirebaseAdminAuthInboundPolicy=nL});var GE=_(eu=>{"use strict";Object.defineProperty(eu,"__esModule",{value:!0});eu.UpstreamFirebaseUserAuthInboundPolicy=void 0;var iL=Zt(),oL=Bt(),pi=k(),sL=If(),Kf=Fn(),aL=Jt(),cL=lt(),uL="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",lL=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Jf,dL=o(async(t,e,r,n)=>{if((0,cL.optionValidator)(r,n).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!r.userId&&!r.userIdPropertyPath)throw new pi.ConfigurationError(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${n}'.`);let i={};if(typeof r.developerClaims<"u"){for(let p in r.developerClaims)if(Object.prototype.hasOwnProperty.call(r.developerClaims,p)){if(lL.indexOf(p)!==-1)throw new pi.ConfigurationError(`Developer claim "${p}" is reserved and cannot be specified.`);i[p]=r.developerClaims[p]}}Jf||(Jf=await Kf.GcpServiceAccount.init(r.serviceAccountJson));let s=r.userId;if(!s&&!r.userIdPropertyPath){if(!t.user)throw new pi.RuntimeError("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=t.user?.sub}else if(r.userIdPropertyPath){if(!t.user)throw new pi.RuntimeError(`Unable to apply userIdPropertyPath '${r.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=(0,aL.getValueFromRequestUser)(t.user,r.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new pi.RuntimeError(`Unable to determine user from for the policy ${n}`);let a=await(0,iL.getPolicyCacheName)(n,r),c=new oL.MemoryZoneReadThroughCache(a,e),u={uid:s,claims:i},l=await(0,sL.sha256)(JSON.stringify(u)),d=await c.get(l);if(!d){let p=await(0,Kf.getTokenFromGcpServiceAccount)({serviceAccount:Jf,audience:uL,payload:u}),f=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${r.webApiKey}`,h=await(0,Kf.exchangeFirebaseJwtForIdToken)(f,p,{retries:r.tokenRetries??3,retryDelayMs:10});if(!h.idToken)throw new pi.RuntimeError("Invalid token response from Firebase");d=h.idToken,c.put(l,d,(h.expiresIn?parseInt(h.expiresIn):3600)-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");eu.UpstreamFirebaseUserAuthInboundPolicy=dL});var JE=_(tu=>{"use strict";Object.defineProperty(tu,"__esModule",{value:!0});tu.UpstreamGcpJwtInboundPolicy=void 0;var KE=Fn(),pL=lt(),zf,fL=o(async(t,e,r,n)=>{(0,pL.optionValidator)(r,n).required("audience","string").required("serviceAccountJson","string"),zf||(zf=await KE.GcpServiceAccount.init(r.serviceAccountJson));let i=await(0,KE.getTokenFromGcpServiceAccount)({serviceAccount:zf,audience:r.audience});return t.headers.set("Authorization",`Bearer ${i}`),t},"UpstreamGcpJwtInboundPolicy");tu.UpstreamGcpJwtInboundPolicy=fL});var WE=_(ru=>{"use strict";Object.defineProperty(ru,"__esModule",{value:!0});ru.UpstreamGcpServiceAuthInboundPolicy=void 0;var hL=Zt(),mL=Xu(),yL=Bt(),fo=k(),Wf=Fn(),gL=Jt(),bL=lt(),zE="https://www.googleapis.com/oauth2/v4/token",Qf,_L=o(async(t,e,r,n)=>{(0,bL.optionValidator)(r,n).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Qf||(Qf=await Wf.GcpServiceAccount.init(r.serviceAccountJson));let i={};if(r.scopes&&r.audience)throw new fo.ConfigurationError("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(r.scopes)try{let u=(0,gL.parseValueToStringArray)(r.scopes);i.scope=u.join(" ")}catch(u){throw u instanceof fo.ConfigurationError?new fo.ConfigurationError(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${u.message}`):u}r.audience&&(i.target_audience=`${r.audience}`);let s=await(0,hL.getPolicyCacheName)(n,r),a;r.useMemoryCacheOnly?a=new mL.MemoryCache(s):a=new yL.MemoryZoneReadThroughCache(s,e);let c=await a.get(n);if(!c){let u=await(0,Wf.getTokenFromGcpServiceAccount)({serviceAccount:Qf,audience:zE,payload:i}),l=await(0,Wf.exchangeGgpJwtForIdToken)(zE,u,{retries:r.tokenRetries??3,retryDelayMs:10});if(r.audience){if(!l.id_token)throw new fo.RuntimeError("Invalid token response from GCP");c=l.id_token}else{if(!l.access_token)throw new fo.RuntimeError("Invalid token response from GCP");c=l.access_token}a.put(n,c,3600-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${c}`),t},"UpstreamGcpServiceAuthInboundPolicy");ru.UpstreamGcpServiceAuthInboundPolicy=_L});var YE=_(nu=>{"use strict";Object.defineProperty(nu,"__esModule",{value:!0});nu.ValidateJsonSchemaInbound=void 0;var EL=k(),QE=de(),wL=o(async(t,e,r)=>{let n=t.clone(),i;try{i=await n.json()}catch{return QE.HttpProblems.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(r.validator(i))return t;let{errors:a}=r.validator;if(!a)throw new EL.SystemError("Invalid state - validator error object is undefined even though validation failed.");let c=a.map(u=>u.instancePath===void 0||u.instancePath===""?"Body "+u.message:u.instancePath.replace("/","")+" "+u.message);return QE.HttpProblems.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:c})},"ValidateJsonSchemaInbound");nu.ValidateJsonSchemaInbound=wL});var ew=_((JJ,XE)=>{"use strict";var vL=Object.defineProperty,TL=Object.getOwnPropertyNames,B=o((t,e)=>vL(t,"name",{value:e,configurable:!0}),"__name"),vt=o((t,e)=>o(function(){return e||(0,t[TL(t)[0]])((e={exports:{}}).exports,e),e.exports},"__require"),"__commonJS"),Yf=vt({"node_modules/fast-xml-parser/src/util.js"(t){"use strict";var e=":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",r=e+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",n="["+e+"]["+r+"]*",i=new RegExp("^"+n+"$"),s=B(function(c,u){let l=[],d=u.exec(c);for(;d;){let p=[];p.startIndex=u.lastIndex-d[0].length;let f=d.length;for(let h=0;h<f;h++)p.push(d[h]);l.push(p),d=u.exec(c)}return l},"getAllMatches"),a=B(function(c){let u=i.exec(c);return!(u===null||typeof u>"u")},"isName");t.isExist=function(c){return typeof c<"u"},t.isEmptyObject=function(c){return Object.keys(c).length===0},t.merge=function(c,u,l){if(u){let d=Object.keys(u),p=d.length;for(let f=0;f<p;f++)l==="strict"?c[d[f]]=[u[d[f]]]:c[d[f]]=u[d[f]]}},t.getValue=function(c){return t.isExist(c)?c:""},t.isName=a,t.getAllMatches=s,t.nameRegexp=n}}),ZE=vt({"node_modules/fast-xml-parser/src/validator.js"(t){"use strict";var e=Yf(),r={allowBooleanAttributes:!1,unpairedTags:[]};t.validate=function(g,v){v=Object.assign({},r,v);let O=[],V=!1,E=!1;g[0]==="\uFEFF"&&(g=g.substr(1));for(let T=0;T<g.length;T++)if(g[T]==="<"&&g[T+1]==="?"){if(T+=2,T=i(g,T),T.err)return T}else if(g[T]==="<"){let C=T;if(T++,g[T]==="!"){T=s(g,T);continue}else{let w=!1;g[T]==="/"&&(w=!0,T++);let P="";for(;T<g.length&&g[T]!==">"&&g[T]!==" "&&g[T]!==" "&&g[T]!==`
75
75
  `&&g[T]!=="\r";T++)P+=g[T];if(P=P.trim(),P[P.length-1]==="/"&&(P=P.substring(0,P.length-1),T--),!b(P)){let j;return P.trim().length===0?j="Invalid space after '<'.":j="Tag '"+P+"' is an invalid name.",h("InvalidTag",j,I(g,T))}let L=u(g,T);if(L===!1)return h("InvalidAttr","Attributes for '"+P+"' have open quote.",I(g,T));let te=L.value;if(T=L.index,te[te.length-1]==="/"){let j=T-te.length;te=te.substring(0,te.length-1);let M=d(te,v);if(M===!0)V=!0;else return h(M.err.code,M.err.msg,I(g,j+M.err.line))}else if(w)if(L.tagClosed){if(te.trim().length>0)return h("InvalidTag","Closing tag '"+P+"' can't have attributes or invalid starting.",I(g,C));{let j=O.pop();if(P!==j.tagName){let M=I(g,j.tagStartPos);return h("InvalidTag","Expected closing tag '"+j.tagName+"' (opened in line "+M.line+", col "+M.col+") instead of closing tag '"+P+"'.",I(g,C))}O.length==0&&(E=!0)}}else return h("InvalidTag","Closing tag '"+P+"' doesn't have proper closing.",I(g,T));else{let j=d(te,v);if(j!==!0)return h(j.err.code,j.err.msg,I(g,T-te.length+j.err.line));if(E===!0)return h("InvalidXml","Multiple possible root nodes found.",I(g,T));v.unpairedTags.indexOf(P)!==-1||O.push({tagName:P,tagStartPos:C}),V=!0}for(T++;T<g.length;T++)if(g[T]==="<")if(g[T+1]==="!"){T++,T=s(g,T);continue}else if(g[T+1]==="?"){if(T=i(g,++T),T.err)return T}else break;else if(g[T]==="&"){let j=f(g,T);if(j==-1)return h("InvalidChar","char '&' is not expected.",I(g,T));T=j}else if(E===!0&&!n(g[T]))return h("InvalidXml","Extra text at the end",I(g,T));g[T]==="<"&&T--}}else{if(n(g[T]))continue;return h("InvalidChar","char '"+g[T]+"' is not expected.",I(g,T))}if(V){if(O.length==1)return h("InvalidTag","Unclosed tag '"+O[0].tagName+"'.",I(g,O[0].tagStartPos));if(O.length>0)return h("InvalidXml","Invalid '"+JSON.stringify(O.map(T=>T.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return h("InvalidXml","Start tag expected.",1);return!0};function n(g){return g===" "||g===" "||g===`
76
76
  `||g==="\r"}o(n,"isWhiteSpace"),B(n,"isWhiteSpace");function i(g,v){let O=v;for(;v<g.length;v++)if(g[v]=="?"||g[v]==" "){let V=g.substr(O,v-O);if(v>5&&V==="xml")return h("InvalidXml","XML declaration allowed only at the start of the document.",I(g,v));if(g[v]=="?"&&g[v+1]==">"){v++;break}else continue}return v}o(i,"readPI"),B(i,"readPI");function s(g,v){if(g.length>v+5&&g[v+1]==="-"&&g[v+2]==="-"){for(v+=3;v<g.length;v++)if(g[v]==="-"&&g[v+1]==="-"&&g[v+2]===">"){v+=2;break}}else if(g.length>v+8&&g[v+1]==="D"&&g[v+2]==="O"&&g[v+3]==="C"&&g[v+4]==="T"&&g[v+5]==="Y"&&g[v+6]==="P"&&g[v+7]==="E"){let O=1;for(v+=8;v<g.length;v++)if(g[v]==="<")O++;else if(g[v]===">"&&(O--,O===0))break}else if(g.length>v+9&&g[v+1]==="["&&g[v+2]==="C"&&g[v+3]==="D"&&g[v+4]==="A"&&g[v+5]==="T"&&g[v+6]==="A"&&g[v+7]==="["){for(v+=8;v<g.length;v++)if(g[v]==="]"&&g[v+1]==="]"&&g[v+2]===">"){v+=2;break}}return v}o(s,"readCommentAndCDATA"),B(s,"readCommentAndCDATA");var a='"',c="'";function u(g,v){let O="",V="",E=!1;for(;v<g.length;v++){if(g[v]===a||g[v]===c)V===""?V=g[v]:V!==g[v]||(V="");else if(g[v]===">"&&V===""){E=!0;break}O+=g[v]}return V!==""?!1:{value:O,index:v,tagClosed:E}}o(u,"readAttributeStr"),B(u,"readAttributeStr");var l=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function d(g,v){let O=e.getAllMatches(g,l),V={};for(let E=0;E<O.length;E++){if(O[E][1].length===0)return h("InvalidAttr","Attribute '"+O[E][2]+"' has no space in starting.",A(O[E]));if(O[E][3]!==void 0&&O[E][4]===void 0)return h("InvalidAttr","Attribute '"+O[E][2]+"' is without value.",A(O[E]));if(O[E][3]===void 0&&!v.allowBooleanAttributes)return h("InvalidAttr","boolean attribute '"+O[E][2]+"' is not allowed.",A(O[E]));let T=O[E][2];if(!y(T))return h("InvalidAttr","Attribute '"+T+"' is an invalid name.",A(O[E]));if(!V.hasOwnProperty(T))V[T]=1;else return h("InvalidAttr","Attribute '"+T+"' is repeated.",A(O[E]))}return!0}o(d,"validateAttributeString"),B(d,"validateAttributeString");function p(g,v){let O=/\d/;for(g[v]==="x"&&(v++,O=/[\da-fA-F]/);v<g.length;v++){if(g[v]===";")return v;if(!g[v].match(O))break}return-1}o(p,"validateNumberAmpersand"),B(p,"validateNumberAmpersand");function f(g,v){if(v++,g[v]===";")return-1;if(g[v]==="#")return v++,p(g,v);let O=0;for(;v<g.length;v++,O++)if(!(g[v].match(/\w/)&&O<20)){if(g[v]===";")break;return-1}return v}o(f,"validateAmpersand"),B(f,"validateAmpersand");function h(g,v,O){return{err:{code:g,msg:v,line:O.line||O,col:O.col}}}o(h,"getErrorObject"),B(h,"getErrorObject");function y(g){return e.isName(g)}o(y,"validateAttrName"),B(y,"validateAttrName");function b(g){return e.isName(g)}o(b,"validateTagName"),B(b,"validateTagName");function I(g,v){let O=g.substring(0,v).split(/\r?\n/);return{line:O.length,col:O[O.length-1].length+1}}o(I,"getLineNumberForPosition"),B(I,"getLineNumberForPosition");function A(g){return g.startIndex+g[1].length}o(A,"getPositionFromMatch"),B(A,"getPositionFromMatch")}}),SL=vt({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(t){var e={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:function(n,i){return i},attributeValueProcessor:function(n,i){return i},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(n,i,s){return n}},r=B(function(n){return Object.assign({},e,n)},"buildOptions");t.buildOptions=r,t.defaultOptions=e}}),IL=vt({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(t,e){"use strict";var r=class{static{o(this,"XmlNode")}static{B(this,"XmlNode")}constructor(n){this.tagname=n,this.child=[],this[":@"]={}}add(n,i){n==="__proto__"&&(n="#__proto__"),this.child.push({[n]:i})}addChild(n){n.tagname==="__proto__"&&(n.tagname="#__proto__"),n[":@"]&&Object.keys(n[":@"]).length>0?this.child.push({[n.tagname]:n.child,":@":n[":@"]}):this.child.push({[n.tagname]:n.child})}};e.exports=r}}),PL=vt({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(t,e){var r=Yf();function n(p,f){let h={};if(p[f+3]==="O"&&p[f+4]==="C"&&p[f+5]==="T"&&p[f+6]==="Y"&&p[f+7]==="P"&&p[f+8]==="E"){f=f+9;let y=1,b=!1,I=!1,A="";for(;f<p.length;f++)if(p[f]==="<"&&!I){if(b&&a(p,f))f+=7,[entityName,val,f]=i(p,f+1),val.indexOf("&")===-1&&(h[d(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(b&&c(p,f))f+=8;else if(b&&u(p,f))f+=8;else if(b&&l(p,f))f+=9;else if(s)I=!0;else throw new Error("Invalid DOCTYPE");y++,A=""}else if(p[f]===">"){if(I?p[f-1]==="-"&&p[f-2]==="-"&&(I=!1,y--):y--,y===0)break}else p[f]==="["?b=!0:A+=p[f];if(y!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:h,i:f}}o(n,"readDocType"),B(n,"readDocType");function i(p,f){let h="";for(;f<p.length&&p[f]!=="'"&&p[f]!=='"';f++)h+=p[f];if(h=h.trim(),h.indexOf(" ")!==-1)throw new Error("External entites are not supported");let y=p[f++],b="";for(;f<p.length&&p[f]!==y;f++)b+=p[f];return[h,b,f]}o(i,"readEntityExp"),B(i,"readEntityExp");function s(p,f){return p[f+1]==="!"&&p[f+2]==="-"&&p[f+3]==="-"}o(s,"isComment"),B(s,"isComment");function a(p,f){return p[f+1]==="!"&&p[f+2]==="E"&&p[f+3]==="N"&&p[f+4]==="T"&&p[f+5]==="I"&&p[f+6]==="T"&&p[f+7]==="Y"}o(a,"isEntity"),B(a,"isEntity");function c(p,f){return p[f+1]==="!"&&p[f+2]==="E"&&p[f+3]==="L"&&p[f+4]==="E"&&p[f+5]==="M"&&p[f+6]==="E"&&p[f+7]==="N"&&p[f+8]==="T"}o(c,"isElement"),B(c,"isElement");function u(p,f){return p[f+1]==="!"&&p[f+2]==="A"&&p[f+3]==="T"&&p[f+4]==="T"&&p[f+5]==="L"&&p[f+6]==="I"&&p[f+7]==="S"&&p[f+8]==="T"}o(u,"isAttlist"),B(u,"isAttlist");function l(p,f){return p[f+1]==="!"&&p[f+2]==="N"&&p[f+3]==="O"&&p[f+4]==="T"&&p[f+5]==="A"&&p[f+6]==="T"&&p[f+7]==="I"&&p[f+8]==="O"&&p[f+9]==="N"}o(l,"isNotation"),B(l,"isNotation");function d(p){if(r.isName(p))return p;throw new Error(`Invalid entity name ${p}`)}o(d,"validateEntityName"),B(d,"validateEntityName"),e.exports=n}}),AL=vt({"../../node_modules/strnum/strnum.js"(t,e){var r=/^[-+]?0x[a-fA-F0-9]+$/,n=/^([\-\+])?(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 i={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function s(c,u={}){if(u=Object.assign({},i,u),!c||typeof c!="string")return c;let l=c.trim();if(u.skipLike!==void 0&&u.skipLike.test(l))return c;if(u.hex&&r.test(l))return Number.parseInt(l,16);{let d=n.exec(l);if(d){let p=d[1],f=d[2],h=a(d[3]),y=d[4]||d[6];if(!u.leadingZeros&&f.length>0&&p&&l[2]!==".")return c;if(!u.leadingZeros&&f.length>0&&!p&&l[1]!==".")return c;{let b=Number(l),I=""+b;return I.search(/[eE]/)!==-1||y?u.eNotation?b:c:l.indexOf(".")!==-1?I==="0"&&h===""||I===h||p&&I==="-"+h?b:c:f?h===I||p+h===I?b:c:l===I||l===p+I?b:c}}else return c}}o(s,"toNumber"),B(s,"toNumber");function a(c){return c&&c.indexOf(".")!==-1&&(c=c.replace(/0+$/,""),c==="."?c="0":c[0]==="."?c="0"+c:c[c.length-1]==="."&&(c=c.substr(0,c.length-1))),c}o(a,"trimZeros"),B(a,"trimZeros"),e.exports=s}}),RL=vt({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(t,e){"use strict";var r=Yf(),n=IL(),i=PL(),s=AL(),a=class{static{o(this,"OrderedObjParser")}static{B(this,"OrderedObjParser")}constructor(E){this.options=E,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"}},this.addExternalEntities=c,this.parseXml=f,this.parseTextData=u,this.resolveNameSpace=l,this.buildAttributesMap=p,this.isItStopNode=I,this.replaceEntitiesValue=y,this.readStopNodeData=O,this.saveTextToParentTag=b,this.addChild=h}};function c(E){let T=Object.keys(E);for(let C=0;C<T.length;C++){let w=T[C];this.lastEntities[w]={regex:new RegExp("&"+w+";","g"),val:E[w]}}}o(c,"addExternalEntities"),B(c,"addExternalEntities");function u(E,T,C,w,P,L,te){if(E!==void 0&&(this.options.trimValues&&!w&&(E=E.trim()),E.length>0)){te||(E=this.replaceEntitiesValue(E));let j=this.options.tagValueProcessor(T,E,C,P,L);return j==null?E:typeof j!=typeof E||j!==E?j:this.options.trimValues?V(E,this.options.parseTagValue,this.options.numberParseOptions):E.trim()===E?V(E,this.options.parseTagValue,this.options.numberParseOptions):E}}o(u,"parseTextData"),B(u,"parseTextData");function l(E){if(this.options.removeNSPrefix){let T=E.split(":"),C=E.charAt(0)==="/"?"/":"";if(T[0]==="xmlns")return"";T.length===2&&(E=C+T[1])}return E}o(l,"resolveNameSpace"),B(l,"resolveNameSpace");var d=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function p(E,T,C){if(!this.options.ignoreAttributes&&typeof E=="string"){let w=r.getAllMatches(E,d),P=w.length,L={};for(let te=0;te<P;te++){let j=this.resolveNameSpace(w[te][1]),M=w[te][4],_e=this.options.attributeNamePrefix+j;if(j.length)if(this.options.transformAttributeName&&(_e=this.options.transformAttributeName(_e)),_e==="__proto__"&&(_e="#__proto__"),M!==void 0){this.options.trimValues&&(M=M.trim()),M=this.replaceEntitiesValue(M);let le=this.options.attributeValueProcessor(j,M,T);le==null?L[_e]=M:typeof le!=typeof M||le!==M?L[_e]=le:L[_e]=V(M,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(L[_e]=!0)}if(!Object.keys(L).length)return;if(this.options.attributesGroupName){let te={};return te[this.options.attributesGroupName]=L,te}return L}}o(p,"buildAttributesMap"),B(p,"buildAttributesMap");var f=B(function(E){E=E.replace(/\r\n?/g,`
77
77
  `);let T=new n("!xml"),C=T,w="",P="";for(let L=0;L<E.length;L++)if(E[L]==="<")if(E[L+1]==="/"){let j=g(E,">",L,"Closing Tag is not closed."),M=E.substring(L+2,j).trim();if(this.options.removeNSPrefix){let yt=M.indexOf(":");yt!==-1&&(M=M.substr(yt+1))}this.options.transformTagName&&(M=this.options.transformTagName(M)),C&&(w=this.saveTextToParentTag(w,C,P));let _e=P.substring(P.lastIndexOf(".")+1);if(M&&this.options.unpairedTags.indexOf(M)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${M}>`);let le=0;_e&&this.options.unpairedTags.indexOf(_e)!==-1?(le=P.lastIndexOf(".",P.lastIndexOf(".")-1),this.tagsNodeStack.pop()):le=P.lastIndexOf("."),P=P.substring(0,le),C=this.tagsNodeStack.pop(),w="",L=j}else if(E[L+1]==="?"){let j=v(E,L,!1,"?>");if(!j)throw new Error("Pi Tag is not closed.");if(w=this.saveTextToParentTag(w,C,P),!(this.options.ignoreDeclaration&&j.tagName==="?xml"||this.options.ignorePiTags)){let M=new n(j.tagName);M.add(this.options.textNodeName,""),j.tagName!==j.tagExp&&j.attrExpPresent&&(M[":@"]=this.buildAttributesMap(j.tagExp,P,j.tagName)),this.addChild(C,M,P)}L=j.closeIndex+1}else if(E.substr(L+1,3)==="!--"){let j=g(E,"-->",L+4,"Comment is not closed.");if(this.options.commentPropName){let M=E.substring(L+4,j-2);w=this.saveTextToParentTag(w,C,P),C.add(this.options.commentPropName,[{[this.options.textNodeName]:M}])}L=j}else if(E.substr(L+1,2)==="!D"){let j=i(E,L);this.docTypeEntities=j.entities,L=j.i}else if(E.substr(L+1,2)==="!["){let j=g(E,"]]>",L,"CDATA is not closed.")-2,M=E.substring(L+9,j);w=this.saveTextToParentTag(w,C,P);let _e=this.parseTextData(M,C.tagname,P,!0,!1,!0,!0);_e==null&&(_e=""),this.options.cdataPropName?C.add(this.options.cdataPropName,[{[this.options.textNodeName]:M}]):C.add(this.options.textNodeName,_e),L=j+2}else{let j=v(E,L,this.options.removeNSPrefix),M=j.tagName,_e=j.rawTagName,le=j.tagExp,yt=j.attrExpPresent,xh=j.closeIndex;this.options.transformTagName&&(M=this.options.transformTagName(M)),C&&w&&C.tagname!=="!xml"&&(w=this.saveTextToParentTag(w,C,P,!1));let Lh=C;if(Lh&&this.options.unpairedTags.indexOf(Lh.tagname)!==-1&&(C=this.tagsNodeStack.pop(),P=P.substring(0,P.lastIndexOf("."))),M!==T.tagname&&(P+=P?"."+M:M),this.isItStopNode(this.options.stopNodes,P,M)){let st="";if(le.length>0&&le.lastIndexOf("/")===le.length-1)L=j.closeIndex;else if(this.options.unpairedTags.indexOf(M)!==-1)L=j.closeIndex;else{let Ku=this.readStopNodeData(E,_e,xh+1);if(!Ku)throw new Error(`Unexpected end of ${_e}`);L=Ku.i,st=Ku.tagContent}let Gu=new n(M);M!==le&&yt&&(Gu[":@"]=this.buildAttributesMap(le,P,M)),st&&(st=this.parseTextData(st,M,P,!0,yt,!0,!0)),P=P.substr(0,P.lastIndexOf(".")),Gu.add(this.options.textNodeName,st),this.addChild(C,Gu,P)}else{if(le.length>0&&le.lastIndexOf("/")===le.length-1){M[M.length-1]==="/"?(M=M.substr(0,M.length-1),P=P.substr(0,P.length-1),le=M):le=le.substr(0,le.length-1),this.options.transformTagName&&(M=this.options.transformTagName(M));let st=new n(M);M!==le&&yt&&(st[":@"]=this.buildAttributesMap(le,P,M)),this.addChild(C,st,P),P=P.substr(0,P.lastIndexOf("."))}else{let st=new n(M);this.tagsNodeStack.push(C),M!==le&&yt&&(st[":@"]=this.buildAttributesMap(le,P,M)),this.addChild(C,st,P),C=st}w="",L=xh}}else w+=E[L];return T.child},"parseXml");function h(E,T,C){let w=this.options.updateTag(T.tagname,C,T[":@"]);w===!1||(typeof w=="string"&&(T.tagname=w),E.addChild(T))}o(h,"addChild"),B(h,"addChild");var y=B(function(E){if(this.options.processEntities){for(let T in this.docTypeEntities){let C=this.docTypeEntities[T];E=E.replace(C.regx,C.val)}for(let T in this.lastEntities){let C=this.lastEntities[T];E=E.replace(C.regex,C.val)}if(this.options.htmlEntities)for(let T in this.htmlEntities){let C=this.htmlEntities[T];E=E.replace(C.regex,C.val)}E=E.replace(this.ampEntity.regex,this.ampEntity.val)}return E},"replaceEntitiesValue");function b(E,T,C,w){return E&&(w===void 0&&(w=Object.keys(T.child).length===0),E=this.parseTextData(E,T.tagname,C,!1,T[":@"]?Object.keys(T[":@"]).length!==0:!1,w),E!==void 0&&E!==""&&T.add(this.options.textNodeName,E),E=""),E}o(b,"saveTextToParentTag"),B(b,"saveTextToParentTag");function I(E,T,C){let w="*."+C;for(let P in E){let L=E[P];if(w===L||T===L)return!0}return!1}o(I,"isItStopNode"),B(I,"isItStopNode");function A(E,T,C=">"){let w,P="";for(let L=T;L<E.length;L++){let te=E[L];if(w)te===w&&(w="");else if(te==='"'||te==="'")w=te;else if(te===C[0])if(C[1]){if(E[L+1]===C[1])return{data:P,index:L}}else return{data:P,index:L};else te===" "&&(te=" ");P+=te}}o(A,"tagExpWithClosingIndex"),B(A,"tagExpWithClosingIndex");function g(E,T,C,w){let P=E.indexOf(T,C);if(P===-1)throw new Error(w);return P+T.length-1}o(g,"findClosingIndex"),B(g,"findClosingIndex");function v(E,T,C,w=">"){let P=A(E,T+1,w);if(!P)return;let L=P.data,te=P.index,j=L.search(/\s/),M=L,_e=!0;j!==-1&&(M=L.substring(0,j),L=L.substring(j+1).trimStart());let le=M;if(C){let yt=M.indexOf(":");yt!==-1&&(M=M.substr(yt+1),_e=M!==P.data.substr(yt+1))}return{tagName:M,tagExp:L,closeIndex:te,attrExpPresent:_e,rawTagName:le}}o(v,"readTagExp"),B(v,"readTagExp");function O(E,T,C){let w=C,P=1;for(;C<E.length;C++)if(E[C]==="<")if(E[C+1]==="/"){let L=g(E,">",C,`${T} is not closed`);if(E.substring(C+2,L).trim()===T&&(P--,P===0))return{tagContent:E.substring(w,C),i:L};C=L}else if(E[C+1]==="?")C=g(E,"?>",C+1,"StopNode is not closed.");else if(E.substr(C+1,3)==="!--")C=g(E,"-->",C+3,"StopNode is not closed.");else if(E.substr(C+1,2)==="![")C=g(E,"]]>",C,"StopNode is not closed.")-2;else{let L=v(E,C,">");L&&((L&&L.tagName)===T&&L.tagExp[L.tagExp.length-1]!=="/"&&P++,C=L.closeIndex)}}o(O,"readStopNodeData"),B(O,"readStopNodeData");function V(E,T,C){if(T&&typeof E=="string"){let w=E.trim();return w==="true"?!0:w==="false"?!1:s(E,C)}else return r.isExist(E)?E:""}o(V,"parseValue"),B(V,"parseValue"),e.exports=a}}),OL=vt({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(t){"use strict";function e(a,c){return r(a,c)}o(e,"prettify"),B(e,"prettify");function r(a,c,u){let l,d={};for(let p=0;p<a.length;p++){let f=a[p],h=n(f),y="";if(u===void 0?y=h:y=u+"."+h,h===c.textNodeName)l===void 0?l=f[h]:l+=""+f[h];else{if(h===void 0)continue;if(f[h]){let b=r(f[h],c,y),I=s(b,c);f[":@"]?i(b,f[":@"],y,c):Object.keys(b).length===1&&b[c.textNodeName]!==void 0&&!c.alwaysCreateTextNode?b=b[c.textNodeName]:Object.keys(b).length===0&&(c.alwaysCreateTextNode?b[c.textNodeName]="":b=""),d[h]!==void 0&&d.hasOwnProperty(h)?(Array.isArray(d[h])||(d[h]=[d[h]]),d[h].push(b)):c.isArray(h,y,I)?d[h]=[b]:d[h]=b}}}return typeof l=="string"?l.length>0&&(d[c.textNodeName]=l):l!==void 0&&(d[c.textNodeName]=l),d}o(r,"compress"),B(r,"compress");function n(a){let c=Object.keys(a);for(let u=0;u<c.length;u++){let l=c[u];if(l!==":@")return l}}o(n,"propName"),B(n,"propName");function i(a,c,u,l){if(c){let d=Object.keys(c),p=d.length;for(let f=0;f<p;f++){let h=d[f];l.isArray(h,u+"."+h,!0,!0)?a[h]=[c[h]]:a[h]=c[h]}}}o(i,"assignAttributes"),B(i,"assignAttributes");function s(a,c){let{textNodeName:u}=c,l=Object.keys(a).length;return!!(l===0||l===1&&(a[u]||typeof a[u]=="boolean"||a[u]===0))}o(s,"isLeafTag"),B(s,"isLeafTag"),t.prettify=e}}),NL=vt({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(t,e){var{buildOptions:r}=SL(),n=RL(),{prettify:i}=OL(),s=ZE(),a=class{static{o(this,"XMLParser2")}static{B(this,"XMLParser")}constructor(c){this.externalEntities={},this.options=r(c)}parse(c,u){if(typeof c!="string")if(c.toString)c=c.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(u){u===!0&&(u={});let p=s.validate(c,u);if(p!==!0)throw Error(`${p.err.msg}:${p.err.line}:${p.err.col}`)}let l=new n(this.options);l.addExternalEntities(this.externalEntities);let d=l.parseXml(c);return this.options.preserveOrder||d===void 0?d:i(d,this.options)}addEntity(c,u){if(u.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(c.indexOf("&")!==-1||c.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(u==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[c]=u}};e.exports=a}}),CL=vt({"node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js"(t,e){var r=`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zuplo/graphql",
3
- "version": "5.1852.0",
3
+ "version": "5.1854.0",
4
4
  "repository": "https://github.com/zuplo/zuplo",
5
5
  "author": "Zuplo, Inc.",
6
6
  "exports": {