@zuplo/runtime 5.2361.0 → 5.2363.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/out/cjs/index.js +19 -18
- package/out/esm/index.js +17 -16
- package/out/types/index.d.ts +81 -0
- package/package.json +1 -1
package/out/esm/index.js
CHANGED
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
import{a as qe,d as Re,e as Oa,f as Fn,g as $n,h as Aa,i as ka}from"./chunk-IOKNFUPG.js";import{a as We,b as W,c as k,d as m,e as si,f as F,g as ai}from"./chunk-23DATJ57.js";import{a as f}from"./chunk-UTQUSNMK.js";import{a as s,c as Ve}from"./chunk-4DUPDUSC.js";Function.prototype.toString=function(){return"[native code]"};var Wt=globalThis,ui=Wt.caches;if(ui){let n=ui.open;Wt.caches.open=function(e){let t=f.instance.deploymentName??f.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete Wt.caches.default,Object.freeze(Wt.caches)}var ci=new Map,jn=class{static{s(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let t=this.#n.get(e);if(!t)return;let r=Date.now();if(r>t.expiresAt){this.#n.delete(e);return}return t.lastUsed=r,this.#o(),t?.data}put(e,t,r){if(r<=0)return;if(this.#n.size>=this.#e){let a=this.#r.shift();a&&this.#n.delete(a)}let o=Date.now(),i={created:o,lastUsed:o,expiresAt:o+r*1e3,data:t};this.#r.push(e),this.#n.set(e,i)}delete(e){let t=this.#r.indexOf(e);t>=0&&this.#r.slice(t,1),this.#n.delete(e)}get size(){return this.#n.size}#o(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#n.forEach((t,r)=>{t.expiresAt>=e&&this.#n.delete(r)})}},Ze=class{static{s(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=ci.get(e);r||(r=new jn(t),ci.set(e,r)),this.#e=r}name;#e;get(e){return this.#e.get(e)}put(e,t,r){return this.#e.put(e,t,r)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var zn="__zuplo-expiry-header",xt=class{static{s(this,"ZoneCache")}constructor(e,t){this.#t=e,this.#e=t}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let t=await this.#r(),r=this.#o(e),o=await t.match(r);if(!o)return;let i=o.headers.get(zn);if(!i){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(i);if(Date.now()>=a){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),await this.deleteFallback(e)}return}return await o.json()}catch(t){this.logDebug(t)}}async put(e,t,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(zn,`${Date.now()+r*1e3}`);let i=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(t),{headers:o});await i.put(a,u)}async delete(e){let t=await this.#r(),r=this.#o(e);try{await t.delete(r)}catch(o){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",o),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});t.set(zn,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),i=new Response("",{headers:t});await r.put(o,i)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var re=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Ze(r),this.#n=new xt(r,t),this.#r=t}#e;#t;#n;#r;async get(e){let t=this.#t.get(e);if(t)return t;let r=await this.#n.get(e);if(r){let o=Math.floor((r.expires-Date.now())/1e3);if(o>0)return this.#t.put(e,r.data,o),r.data}}put(e,t,r){this.#t.put(e,t,r);let o={data:t,expires:Date.now()+r*1e3},i=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(i)}};var li="zuplo-request-id",Ke="zp-rid",Bn="zp-body-removed",Je="cf-ray",di="x-real-ip",Gn="cf-ipcity",Vn="cf-ipcontinent",Wn="cf-ipcountry",Kn="cf-iplongitude",Jn="cf-iplatitude",pi="cf-region",mi="cf-region-code",gi="cf-metro-code",fi="cf-postal-code",hi="cf-timezone",yi="zp-ipcity",bi="zp-ipcontinent",wi="zp-ipcountry",Ri="zp-iplongitude",Pi="zp-iplatitude",Ii="true-client-ip",Xn="zp-asn",Yn="zp-asorg",Qn="zp-colo",er="zp-postalcode",tr="zp-metrocode",nr="zp-region",rr="zp-regioncode",or="zp-timezone",Ei=[Gn,Vn,Wn,Kn,Jn,Xn,Yn,Qn,er,tr,nr,rr,or],xi=["zp-","cf-"],Ti=[Ke,Je,Bn];var Tt=Symbol("zuplo_meters"),Kt=Symbol("zuplo_dynamic_meters"),Jt="system-logger";var gs=Ve(We());import{trace as fu}from"@opentelemetry/api";import{SpanStatusCode as La,trace as _a}from"@opentelemetry/api";import{SpanStatusCode as ur,trace as cr}from"@opentelemetry/api";var vi=s(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function Ci(n){vi=n}s(Ci,"setTelemetryInitFunction");var Si=s(n=>vi(n),"proxyHandler");var Fe=class{static{s(this,"RuntimePlugin")}},Me=class extends Fe{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},Xt=class extends Me{static{s(this,"MeteringPlugin")}},vt=class extends Fe{static{s(this,"TelemetryPlugin")}};var Yt=new Set,Oi=new Set;function g(n){Oi.has(n)||(Oi.add(n),Yt.add(n))}s(g,"trackFeature");function Ai(){let n=[...Yt];return Yt.clear(),n}s(Ai,"getUnsentFeatures");function ki(n){for(let e of n)Yt.add(e)}s(ki,"restoreFeatures");var Ct=class n{static{s(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let t=e.problem,r=JSON.stringify(t,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(g("runtime.problem-response-formatter"),n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(i){throw new k("Error in custom 'problemResponseFormat'",{cause:i})}})}},Xe=class{static{s(this,"ProblemResponseFormatter")}static async format(e,t,r){return await Ct.problemResponseFormat(e,t,r)}};function Qt(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&Qt(t)}return Object.freeze(n)}s(Qt,"deepFreeze");var te=class n extends Request{static{s(this,"ZuploRequest")}#e=void 0;#t;constructor(e,t){super(e,t);let r=t?.params;r?this.#t=r:e instanceof n?this.#t=e.#t:this.#t={};let o=t?.user;o?this.user=o:e instanceof n&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},t=new URL(this.url).searchParams;for(let[r,o]of t.entries())e[r]=o;this.#e=e}return Qt(this.#e)}get params(){return Qt(this.#t)}user};var St={},He=[],ir=[],sr=[],ar=[];var en={addPlugin(n){He.push(n)},addRequestHook(n){ir.push(n)},addResponseSendingHook(n){sr.push(n)},addResponseSendingFinalHook(n){ar.push(n)}},_i=s(async(n,e)=>{if(ir.length===0)return n;let t=cr.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let i of ir){let a=await t.startActiveSpan(i.name,async u=>{let c=await i(o,e);if(c instanceof te||c instanceof Response)return u.end(),c;{let l=new m(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw u.end(),u.recordException(l),u.setStatus({code:ur.ERROR}),l}});if(a instanceof te)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),Ni=s(async(n,e,t)=>{if(sr.length===0)return n;let r=cr.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let i=n;for(let a of sr)await r.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)i=c,u.end();else{let l=new m(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof i}.`);throw u.recordException(l),u.setStatus({code:ur.ERROR}),u.end(),l}});return i}finally{o.end()}})},"invokeOnResponseSendingExtensions"),Di=s(async(n,e,t)=>{if(ar.length===0)return;let r=cr.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let i of ar)await r.startActiveSpan(i.name,async a=>{try{await i(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:ur.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),Li=!1;async function Mi(n){if(!Li){n&&(g("runtime.extensions"),await n(en)),St.value=en;for(let e of He)if(e instanceof vt){let{requestHandlerProxy:t}=e.instrument({accountName:f.instance.build.ACCOUNT_NAME,projectName:f.instance.build.PROJECT_NAME,buildId:f.instance.build.BUILD_ID,zuploVersion:f.instance.build.ZUPLO_VERSION,compatibilityDate:f.instance.build.COMPATIBILITY_DATE,instanceId:f.instance.instanceId,environmentType:f.instance.loggingEnvironmentType,environmentStage:f.instance.loggingEnvironmentStage,deploymentName:f.instance.deploymentName});Ci(t)}for(let e of He)e instanceof Me&&await e.initialize(en);Ct.setProblemResponseFormat(en.problemResponseFormat),Li=!0}}s(Mi,"initializeRuntime");var lr={Json:"application/json",Form:"application/x-www-form-urlencoded"};function dr(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(lr.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(lr.Json)||!e?JSON.stringify(n):n}s(dr,"serialize");function ot(n){return he.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(he.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}s(ot,"isSystemRoute");var pe=class{static{s(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,t)=>async(r,o)=>_a.getTracer("pipeline").startActiveSpan(`handler:${o.route.handler.export}`,async a=>{try{return await e(r,o)}catch(u){o.log.error("Error executing request handler.",u);let c=t.errorHandler(r,o,u);return a.setStatus({code:La.ERROR}),c}finally{a.end()}});#t=({processors:e,gateway:t,handler:r})=>async(o,i)=>{let a=[...e],u=s(async P=>{let C=a.pop();return C?C(o,i,t,u):await this.#e(async j=>{let q=await r(j,i);return Na(q)},t)(P,i)},"nextPipe"),l=await u(o),d=new URL(o.url);if(ot(d)&&f.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new Ot(o,l);i.dispatchEvent(p);let h=ye.getContextExtensions(i),y=h.latestRequest,O;try{O=await p.mutableResponse}catch(P){return i.log.error(P),t.errorHandler(o,i,P)}try{O=await h.onResponseSending(O,y,i)}catch(P){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(o,i,P)}try{O=await Ni(O,y,i)}catch(P){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(o,i,P)}i.dispatchEvent(new At(o,O));try{await h.onResponseSendingFinal(l,y,i)}catch(P){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}try{await Di(l,y,i)}catch(P){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}return O}};function Na(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(dr(n),{headers:{"content-type":"application/json"}})}s(Na,"resultToResponse");var tn=(w=>(w[w.CONTINUE=100]="CONTINUE",w[w.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",w[w.PROCESSING=102]="PROCESSING",w[w.EARLY_HINTS=103]="EARLY_HINTS",w[w.OK=200]="OK",w[w.CREATED=201]="CREATED",w[w.ACCEPTED=202]="ACCEPTED",w[w.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",w[w.NO_CONTENT=204]="NO_CONTENT",w[w.RESET_CONTENT=205]="RESET_CONTENT",w[w.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",w[w.MULTI_STATUS=207]="MULTI_STATUS",w[w.ALREADY_REPORTED=208]="ALREADY_REPORTED",w[w.IM_USED=226]="IM_USED",w[w.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",w[w.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",w[w.FOUND=302]="FOUND",w[w.SEE_OTHER=303]="SEE_OTHER",w[w.NOT_MODIFIED=304]="NOT_MODIFIED",w[w.USE_PROXY=305]="USE_PROXY",w[w.SWITCH_PROXY=306]="SWITCH_PROXY",w[w.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",w[w.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",w[w.BAD_REQUEST=400]="BAD_REQUEST",w[w.UNAUTHORIZED=401]="UNAUTHORIZED",w[w.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",w[w.FORBIDDEN=403]="FORBIDDEN",w[w.NOT_FOUND=404]="NOT_FOUND",w[w.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",w[w.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",w[w.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",w[w.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",w[w.CONFLICT=409]="CONFLICT",w[w.GONE=410]="GONE",w[w.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",w[w.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",w[w.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",w[w.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",w[w.URI_TOO_LONG=414]="URI_TOO_LONG",w[w.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",w[w.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",w[w.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",w[w.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",w[w.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",w[w.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",w[w.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",w[w.LOCKED=423]="LOCKED",w[w.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",w[w.TOO_EARLY=425]="TOO_EARLY",w[w.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",w[w.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",w[w.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",w[w.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",w[w.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",w[w.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",w[w.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",w[w.BAD_GATEWAY=502]="BAD_GATEWAY",w[w.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",w[w.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",w[w.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",w[w.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",w[w.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",w[w.LOOP_DETECTED=508]="LOOP_DETECTED",w[w.NOT_EXTENDED=510]="NOT_EXTENDED",w[w.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",w))(tn||{}),Hi={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Content Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Content",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};var Da={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"},pr=Da;function Ma(n){return`${new URL(n.url).pathname}`}s(Ma,"instance");function Ha(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:f.instance.build.BUILD_ID},r=n.headers.get(Je);return r&&(t.rayId=r),t}s(Ha,"trace");var Ua=s((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:Ma(e),trace:Ha(e,t),...r},additionalHeaders:o,statusText:pr[n.status]}),"merge"),mr=class{static{s(this,"HttpProblemsBase")}static format=(e,t,r)=>"problem"in e?Xe.format(e,t,r):Xe.format({problem:e},t,r);static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:Hi[e],...t}}},x=class extends mr{static{s(this,"HttpProblems")}static#e(e,t,r,o,i){let a=Ua(this.getProblemFromStatus(e),t,r,o,i);return Xe.format(a,t,r)}static continue=(e,t,r,o)=>this.#e(200,e,t,r,o);static switchingProtocols=(e,t,r,o)=>this.#e(101,e,t,r,o);static processing=(e,t,r,o)=>this.#e(102,e,t,r,o);static earlyHints=(e,t,r,o)=>this.#e(103,e,t,r,o);static ok=(e,t,r,o)=>this.#e(200,e,t,r,o);static created=(e,t,r,o)=>this.#e(201,e,t,r,o);static accepted=(e,t,r,o)=>this.#e(202,e,t,r,o);static nonAuthoritativeInformation=(e,t,r,o)=>this.#e(203,e,t,r,o);static noContent=(e,t,r,o)=>this.#e(204,e,t,r,o);static resetContent=(e,t,r,o)=>this.#e(205,e,t,r,o);static partialContent=(e,t,r,o)=>this.#e(206,e,t,r,o);static multiStatus=(e,t,r,o)=>this.#e(207,e,t,r,o);static alreadyReported=(e,t,r,o)=>this.#e(208,e,t,r,o);static imUsed=(e,t,r,o)=>this.#e(226,e,t,r,o);static multipleChoices=(e,t,r,o)=>this.#e(300,e,t,r,o);static movedPermanently=(e,t,r,o)=>this.#e(301,e,t,r,o);static found=(e,t,r,o)=>this.#e(302,e,t,r,o);static seeOther=(e,t,r,o)=>this.#e(303,e,t,r,o);static notModified=(e,t,r,o)=>this.#e(304,e,t,r,o);static useProxy=(e,t,r,o)=>this.#e(305,e,t,r,o);static switchProxy=(e,t,r,o)=>this.#e(306,e,t,r,o);static temporaryRedirect=(e,t,r,o)=>this.#e(307,e,t,r,o);static permanentRedirect=(e,t,r,o)=>this.#e(308,e,t,r,o);static badRequest=(e,t,r,o)=>this.#e(400,e,t,r,o);static unauthorized=(e,t,r,o)=>this.#e(401,e,t,r,o);static paymentRequired=(e,t,r,o)=>this.#e(402,e,t,r,o);static forbidden=(e,t,r,o)=>this.#e(403,e,t,r,o);static notFound=(e,t,r,o)=>this.#e(404,e,t,r,o);static methodNotAllowed=(e,t,r,o)=>this.#e(405,e,t,r,o);static notAcceptable=(e,t,r,o)=>this.#e(406,e,t,r,o);static proxyAuthenticationRequired=(e,t,r,o)=>this.#e(407,e,t,r,o);static requestTimeout=(e,t,r,o)=>this.#e(408,e,t,r,o);static conflict=(e,t,r,o)=>this.#e(409,e,t,r,o);static gone=(e,t,r,o)=>this.#e(410,e,t,r,o);static lengthRequired=(e,t,r,o)=>this.#e(411,e,t,r,o);static preconditionFailed=(e,t,r,o)=>this.#e(412,e,t,r,o);static contentTooLarge=(e,t,r,o)=>this.#e(413,e,t,r,o);static uriTooLong=(e,t,r,o)=>this.#e(414,e,t,r,o);static unsupportedMediaType=(e,t,r,o)=>this.#e(415,e,t,r,o);static rangeNotSatisfiable=(e,t,r,o)=>this.#e(416,e,t,r,o);static expectationFailed=(e,t,r,o)=>this.#e(417,e,t,r,o);static imATeapot=(e,t,r,o)=>this.#e(418,e,t,r,o);static misdirectedRequest=(e,t,r,o)=>this.#e(421,e,t,r,o);static unprocessableContent=(e,t,r,o)=>this.#e(422,e,t,r,o);static locked=(e,t,r,o)=>this.#e(423,e,t,r,o);static failedDependency=(e,t,r,o)=>this.#e(424,e,t,r,o);static tooEarly=(e,t,r,o)=>this.#e(425,e,t,r,o);static upgradeRequired=(e,t,r,o)=>this.#e(426,e,t,r,o);static preconditionRequired=(e,t,r,o)=>this.#e(428,e,t,r,o);static tooManyRequests=(e,t,r,o)=>this.#e(429,e,t,r,o);static requestHeaderFieldsTooLarge=(e,t,r,o)=>this.#e(431,e,t,r,o);static unavailableForLegalReasons=(e,t,r,o)=>this.#e(451,e,t,r,o);static internalServerError=(e,t,r,o)=>this.#e(500,e,t,r,o);static notImplemented=(e,t,r,o)=>this.#e(501,e,t,r,o);static badGateway=(e,t,r,o)=>this.#e(502,e,t,r,o);static serviceUnavailable=(e,t,r,o)=>this.#e(503,e,t,r,o);static gatewayTimeout=(e,t,r,o)=>this.#e(504,e,t,r,o);static httpVersionNotSupported=(e,t,r,o)=>this.#e(505,e,t,r,o);static variantAlsoNegotiates=(e,t,r,o)=>this.#e(506,e,t,r,o);static insufficientStorage=(e,t,r,o)=>this.#e(507,e,t,r,o);static loopDetected=(e,t,r,o)=>this.#e(508,e,t,r,o);static notExtended=(e,t,r,o)=>this.#e(510,e,t,r,o);static networkAuthenticationRequired=(e,t,r,o)=>this.#e(511,e,t,r,o)};var $e=class extends Fe{static{s(this,"MetricsPlugin")}};var Y=class n{static{s(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let t=n.#e.get(e);if(!t){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new W(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var J=class{static{s(this,"BatchDispatch")}constructor(e,t,r,o){this.#t=e,this.#i=t,this.#r=r,this.#n=o??console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=e=>{this.#o.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{t()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var nn=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=f.instance.loggingId,this.#e=e,this.#t=new J("ellie-metrics-transport",10,this.dispatchFunction,Y.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let{remoteLogURL:t,deploymentName:r}=f.instance,{ACCOUNT_NAME:o,PROJECT_NAME:i}=f.instance.build,a=e.map(d=>{let p=Object.assign({},d);return delete p.requestContentLength,delete p.responseContentLength,p}),u=Ai(),c={metadata:{timestamp:new Date,accountName:o,projectName:i,deploymentName:r},metrics:a,features:u},l=await F.fetch(`${t}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(c),headers:{"content-type":"application/json","zp-dn":f.instance.deploymentName??"unknown","user-agent":f.instance.systemUserAgent}});if(!l.ok){let d=await l.text();Y.getLogger(this.#e).error(`Metrics POST responded ${l.status}: ${l.statusText}`,d),ki(u)}}};var ae=class{static{s(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:r,systemRouteName:o,corsPolicy:i="none"}){this.label=e,this.path=t,this.methods=r,this.corsPolicy=i,this.version=kt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},kt={name:"__system-no-version",pathPrefix:""};var be=s(async(n,e,t,r)=>{let o=new Date,i=Date.now(),a=await r(n),u=n.headers.get(Je)??void 0,c=n.headers.get(Ii)??void 0,l=e.incomingRequestProperties,d;e.route instanceof ae&&(d=e.route.systemRouteName);let p=ye.getContextExtensions(e).latestRequest,h={timestamp:o,statusCode:a.status,durationMs:Date.now()-i,requestContentLength:n.headers.get("content-length")?Number(n.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:n.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:f.instance.instanceId,userSub:p.user?.sub,clientIp:c},y=[];return y.push(new nn(e)),He.forEach(O=>{if(O instanceof $e){let P=O.getTransport();y.push(P)}}),y.forEach(O=>{O.pushMetrics(h,e)}),a},"metricsProcessor");var gr=s((n,e)=>{let t=s(async(i,a)=>{let c=new URL(i.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return x.notFound(i,a);let l=f.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=i.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&Y.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new pe({processors:[be],handler:t,gateway:e}),o=new ae({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var{toString:qa}=Object.prototype,{propertyIsEnumerable:Za}=Object.prototype;function fr(n){return qa.call(n)}s(fr,"toString");function Ee(n){return typeof n=="string"}s(Ee,"isString");function it(n){return Ee(n)&&n!==""}s(it,"isNonEmptyString");function Ui(n){return fr(n)==="[object RegExp]"}s(Ui,"isRegexp");function qi(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>Za.call(n,e))]}s(qi,"getOwnEnumerableKeys");function Ye(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}s(Ye,"isObject");function hr(n){return typeof n=="number"&&!isNaN(n)}s(hr,"isNumber");function yr(n){return n===!0||n===!1}s(yr,"isBoolean");function Zi(n){return typeof n>"u"}s(Zi,"isUndefined");function Fi(n){return Zi(n)||n===null}s(Fi,"isUndefinedOrNull");function Lt(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}s(Lt,"isErrorLike");var $i=new Map;function st(n){if(Array.isArray(n)&&!n.some(o=>typeof o!="number"))return n;if(typeof n!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(n))throw new Error("Malformed input string");let e=$i.get(n);if(e)return e;let t=n.split(","),r=[];for(let o of t){let i=o.split("-");if(i.length===2){let a=parseInt(i[0],10),u=parseInt(i[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return $i.set(n,r),r}s(st,"statusCodesStringToNumberArray");function Qe(n,e,t){if(!e.startsWith("."))throw new m(`Invalid ${t} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=n;return r.forEach(i=>{if(o===void 0)throw new k(`Error applying ${t} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(Qe,"getValueFromRequestUser");function et(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new m("Received an array that contains non-string values.");return n}if(Ee(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new m(`Expected type of string, received type '${typeof n}'`)}s(et,"parseValueToStringArray");function ji(n){if(n==null)return[];if(!Array.isArray(n))throw new m(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!Ye(t))throw new m(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!it(t.name))throw new m("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!hr(t.maxAge))throw new m(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!yr(t.allowCredentials))throw new m("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let r=br(t,"allowedHeaders"),o=br(t,"allowedMethods"),i=br(t,"exposeHeaders"),a;try{a=et(t.allowedOrigins)}catch(c){throw new m(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:t.name,allowCredentials:typeof t.allowCredentials=="boolean"?String(t.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:r?r.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:i?i.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}s(ji,"parseCorsPolicies");function br(n,e){let t;if(n[e]!==void 0)try{t=et(n[e])}catch(r){throw new m(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return t}s(br,"parseOptionalProperty");var rn=s((n,e)=>{if(e===null)return;if(n.find(a=>a==="*"))return e;let r=n.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),on=s((n,e)=>{let t={"access-control-allow-origin":e};n.allowedHeaders&&(t["access-control-allow-headers"]=n.allowedHeaders),n.allowedMethods&&(t["access-control-allow-methods"]=n.allowedMethods),n.exposeHeaders&&(t["access-control-expose-headers"]=n.exposeHeaders);let r=n.allowCredentials;r&&(t["access-control-allow-credentials"]=r);let o=n.maxAge?.toString()??void 0;return o&&(t["access-control-max-age"]=o),t},"generateCorsHeaders");var wr=s((n,e)=>{let t=e.routeData.corsPolicies,r=s(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return x.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let h=n.lookup(l,c);if(!h)return x.notFound(a,u);let y=h.routeConfiguration,O=Fa(l,d,p,y,t);return O.isValid?new Response(void 0,{status:200,statusText:"OK",headers:O.headers}):(O.error&&u.log.warn(O.error),x.notFound(a,u))},"optionsHandler"),o=new pe({processors:[be],handler:r,gateway:e}),i=new ae({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(i,o.execute)},"registerCorsRoute"),Fa=s((n,e,t,r,o)=>{let i={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":t,"access-control-allow-methods":n,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...i,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new m(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=rn(a.allowedOrigins,t);return u?{isValid:!0,headers:on(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var zi=s((n,e)=>{let t=s(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new pe({processors:[be],handler:t,gateway:e}),o=new ae({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});n.addRoute(o,r.execute)},"registerNoRoutes");var Rr=new ae({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Bi=s((n,e)=>{let t=s(async(o,i)=>{let a=St.value?.notFoundHandler;if(a){let u=ye.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return x.notFound(o,i)},"notFoundHandler"),r=new pe({processors:[be],handler:t,gateway:e});n.addRoute(Rr,r.execute)},"registerNotMatchedHandler");var $a=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Gi=s(n=>{$a.forEach(e=>n.delete(e))},"stripCorsHeaders"),sn=s(async(n,e,t,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await r(n),p=new Headers(d.headers);return Gi(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let i=await r(n);if(!(i instanceof Response))throw new W(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=ja(o,t.routeData.corsPolicies),u=za(n,a),c=new Headers(i.headers);return Gi(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(i.body,{status:i.status,statusText:i.statusText,headers:c,webSocket:i.webSocket})},"corsProcessor"),ja=s((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(r=>r.name===n.corsPolicy);if(t===void 0)throw new m(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),za=s((n,e)=>{let t=rn(e.allowedOrigins,n.headers.get("origin"));return t?on(e,t):{}},"getCorsHeaders");var Pr=s((n,e)=>{let t=s(async()=>new Response(JSON.stringify({buildId:f.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new pe({processors:[sn],handler:t,gateway:e}),o=new ae({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");import{SpanStatusCode as Vi,trace as Wi}from"@opentelemetry/api";var Le={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var an=class{static{s(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!Ee(t))throw new k(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},de=class extends an{static{s(this,"InboundPolicy")}},je=class extends an{static{s(this,"OutboundPolicy")}};var xr=class extends de{static{s(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t){return this.#e(e,t,this.options,this.policyName)}},Tr=class extends je{static{s(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t,r){return this.#e(e,t,r,this.options,this.policyName)}},Ir=new Map;function _t(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(i=>!Ir.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new m(`Invalid state - no Policy with the name '${i}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof de)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new xr(u,a.handler.options,a.name);else throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${i}' on route '${r}' (typeof handler '${typeof c.handler}')`);Ir.set(a.name,c)}),t.map(i=>{let a=Ir.get(i);if(a===void 0)throw new k("Internal error. Policy not found in cache.");return a})}s(_t,"getInboundPolicyInstances");var Er=new Map;function Ba(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!Er.has(o)).forEach(o=>{let i=e?.find(c=>c.name===o);if(!i)throw new m(`Invalid state - no Policy with the name '${o}' on route '${n.path}' was found in the policies configuration (check case).`);if(typeof i.handler?.module!="object")throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof i.handler?.module}')`);let a=i.handler?.module[i.handler.export],u;if(typeof a!="function")throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof je)u=new a(i.handler.options??{},i.name);else if(typeof a=="function")u=new Tr(a,i.handler.options??{},i.name);else throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new m(`Invalid state - invalid handler on policy '${o}' on route '${n.path}'`);Er.set(i.name,u)}),t.map(o=>{let i=Er.get(o);if(i===void 0)throw new k("Internal error. Policy not found in cache.");return i})}s(Ba,"getOutboundPolicyInstances");var vr=s(n=>async(e,t)=>{let r=ye.getContextExtensions(t),o=Wi.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async i=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;let l=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{let p=await c.handler(u,t);if(p instanceof Request||p instanceof te||p instanceof Response)return d.end(),p;{let h=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${t.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:Vi.ERROR}),d.recordException(h),h}});if(l instanceof te)u=l;else if(l instanceof Request)u=new te(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{i.end()}})},"toStackedInboundHandler"),Ga=s(n=>async(e,t,r)=>{let o=Wi.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async i=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(Le.PolicyName,c.policyName),d.setAttribute(Le.PolicyType,c.policyType);let p=await c.handler(u,t,r);if(p instanceof Response)return p;{let h=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:Vi.ERROR}),d.recordException(h),h}}finally{d.end()}})}return u}finally{i.end()}})},"toStackedOutboundHandler"),un=s(async(n,e,t,r)=>{let o=_t(e.route,t.routeData.policies),i=Ba(e.route,t.routeData.policies);return Ji({request:n,context:e,inboundPolicies:o,outboundPolicies:i,gateway:t,next:r})},"policyProcessor");function Ki({inboundPolicies:n=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>Ji({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:i,next:a}),"policyProcessor")}s(Ki,"createInternalPolicyProcessor");async function Ji({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:i}){let a=vr(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await i(u),l=Ga(r),d;return f.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,n,e):d=c.ok?l(c,n,e):c,d}catch(u){return e.log.error(u),o.errorHandler(n,e,u)}}s(Ji,"executePolicyProcessor");function Xi(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||Va,i=0;for(;i<n.length;){let a=n.indexOf("=",i);if(a===-1)break;let u=n.indexOf(";",i);if(u===-1)u=n.length;else if(u<a){i=n.lastIndexOf(";",a-1)+1;continue}let c=n.slice(i,a).trim();if(t[c]===void 0){let l=n.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),t[c]=Wa(l,o)}i=u+1}return t}s(Xi,"parse");function Va(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}s(Va,"decode");function Wa(n,e){try{return e(n)}catch{return n}}s(Wa,"tryDecode");function Yi(n,e){try{let t=/v\d+(-\d+)?/g,o=Xi(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}s(Yi,"devPortalBaseURL");var Qi="/__zuplo/dev-portal",Ka="dev-portal-id",Ja="dev-portal-host",Xa="zp-account",Ya="zp-project",Qa="dev-portal-build",eu=`
|
|
25
|
+
import{a as Ue,d as Re,e as Ca,f as qn,g as Hn,h as Oa,i as Aa}from"./chunk-IOKNFUPG.js";import{a as Qe,b as J,c as L,d as m,e as si,f as F,g as ai}from"./chunk-23DATJ57.js";import{a as h}from"./chunk-UTQUSNMK.js";import{a as s,c as Je}from"./chunk-4DUPDUSC.js";Function.prototype.toString=function(){return"[native code]"};var Jt=globalThis,ui=Jt.caches;if(ui){let n=ui.open;Jt.caches.open=function(e){let t=h.instance.deploymentName??h.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete Jt.caches.default,Object.freeze(Jt.caches)}var ci=new Map,Un=class{static{s(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#o=[];get(e){let t=this.#n.get(e);if(!t)return;let o=Date.now();if(o>t.expiresAt){this.#n.delete(e);return}return t.lastUsed=o,this.#r(),t?.data}put(e,t,o){if(o<=0)return;if(this.#n.size>=this.#e){let a=this.#o.shift();a&&this.#n.delete(a)}let r=Date.now(),i={created:r,lastUsed:r,expiresAt:r+o*1e3,data:t};this.#o.push(e),this.#n.set(e,i)}delete(e){let t=this.#o.indexOf(e);t>=0&&this.#o.slice(t,1),this.#n.delete(e)}get size(){return this.#n.size}#r(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#n.forEach((t,o)=>{t.expiresAt>=e&&this.#n.delete(o)})}},Ze=class{static{s(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let o=ci.get(e);o||(o=new Un(t),ci.set(e,o)),this.#e=o}name;#e;get(e){return this.#e.get(e)}put(e,t,o){return this.#e.put(e,t,o)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var Zn="__zuplo-expiry-header",vt=class{static{s(this,"ZoneCache")}constructor(e,t){this.#t=e,this.#e=t}#e;#t;#n;async#o(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#r(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let t=await this.#o(),o=this.#r(e),r=await t.match(o);if(!r)return;let i=r.headers.get(Zn);if(!i){try{await t.delete(o)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(i);if(Date.now()>=a){try{await t.delete(o)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),await this.deleteFallback(e)}return}return await r.json()}catch(t){this.logDebug(t)}}async put(e,t,o){let r=new Headers({"cache-control":`s-maxage=${o}, must-revalidate`,"content-type":"application/json"});r.set(Zn,`${Date.now()+o*1e3}`);let i=await this.#o(),a=this.#r(e),u=new Response(JSON.stringify(t),{headers:r});await i.put(a,u)}async delete(e){let t=await this.#o(),o=this.#r(e);try{await t.delete(o)}catch(r){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",r),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});t.set(Zn,`${Date.now()}`);let o=await this.#o(),r=this.#r(e),i=new Response("",{headers:t});await o.put(r,i)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var oe=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,t){let o=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Ze(o),this.#n=new vt(o,t),this.#o=t}#e;#t;#n;#o;async get(e){let t=this.#t.get(e);if(t)return t;let o=await this.#n.get(e);if(o){let r=Math.floor((o.expires-Date.now())/1e3);if(r>0)return this.#t.put(e,o.data,r),o.data}}put(e,t,o){this.#t.put(e,t,o);let r={data:t,expires:Date.now()+o*1e3},i=this.#n.put(e,r,o).catch(a=>{this.#o.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#o.waitUntil(i)}};var li="zuplo-request-id",Xe="zp-rid",Fn="zp-body-removed",Ye="cf-ray",di="x-real-ip",$n="cf-ipcity",jn="cf-ipcontinent",zn="cf-ipcountry",Bn="cf-iplongitude",Gn="cf-iplatitude",pi="cf-region",mi="cf-region-code",gi="cf-metro-code",fi="cf-postal-code",hi="cf-timezone",yi="zp-ipcity",bi="zp-ipcontinent",wi="zp-ipcountry",Ri="zp-iplongitude",Pi="zp-iplatitude",Ii="true-client-ip",Vn="zp-asn",Wn="zp-asorg",Kn="zp-colo",Jn="zp-postalcode",Qn="zp-metrocode",Xn="zp-region",Yn="zp-regioncode",eo="zp-timezone",Ei=[$n,jn,zn,Bn,Gn,Vn,Wn,Kn,Jn,Qn,Xn,Yn,eo],xi=["zp-","cf-"],Ti=[Xe,Ye,Fn];var St=Symbol("zuplo_meters"),Ct=Symbol("zuplo_dynamic_meters"),Qt="system-logger";var gs=Je(Qe());import{trace as gu}from"@opentelemetry/api";import{SpanStatusCode as ka,trace as La}from"@opentelemetry/api";import{SpanStatusCode as ro,trace as io}from"@opentelemetry/api";var vi=s(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function Si(n){vi=n}s(Si,"setTelemetryInitFunction");var Ci=s(n=>vi(n),"proxyHandler");var Fe=class{static{s(this,"RuntimePlugin")}},Me=class extends Fe{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},Xt=class extends Me{static{s(this,"MeteringPlugin")}},Ot=class extends Fe{static{s(this,"TelemetryPlugin")}};var Yt=new Set,Oi=new Set;function g(n){Oi.has(n)||(Oi.add(n),Yt.add(n))}s(g,"trackFeature");function Ai(){let n=[...Yt];return Yt.clear(),n}s(Ai,"getUnsentFeatures");function ki(n){for(let e of n)Yt.add(e)}s(ki,"restoreFeatures");var At=class n{static{s(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let t=e.problem,o=JSON.stringify(t,null,2);return new Response(o,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(g("runtime.problem-response-formatter"),n.problemResponseFormat=(t,o,r)=>{try{return e(t,o,r)}catch(i){throw new L("Error in custom 'problemResponseFormat'",{cause:i})}})}},et=class{static{s(this,"ProblemResponseFormatter")}static async format(e,t,o){return await At.problemResponseFormat(e,t,o)}};function en(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&en(t)}return Object.freeze(n)}s(en,"deepFreeze");var te=class n extends Request{static{s(this,"ZuploRequest")}#e=void 0;#t;constructor(e,t){super(e,t);let o=t?.params;o?this.#t=o:e instanceof n?this.#t=e.#t:this.#t={};let r=t?.user;r?this.user=r:e instanceof n&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},t=new URL(this.url).searchParams;for(let[o,r]of t.entries())e[o]=r;this.#e=e}return en(this.#e)}get params(){return en(this.#t)}user};var kt={},qe=[],to=[],no=[],oo=[];var tn={addPlugin(n){qe.push(n)},addRequestHook(n){to.push(n)},addResponseSendingHook(n){no.push(n)},addResponseSendingFinalHook(n){oo.push(n)}},_i=s(async(n,e)=>{if(to.length===0)return n;let t=io.getTracer("extension");return t.startActiveSpan("hook:onRequest",async o=>{try{let r=n;for(let i of to){let a=await t.startActiveSpan(i.name,async u=>{let c=await i(r,e);if(c instanceof te||c instanceof Response)return u.end(),c;{let l=new m(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof r}.`);throw u.end(),u.recordException(l),u.setStatus({code:ro.ERROR}),l}});if(a instanceof te)r=a;else return a}return r}finally{o.end()}})},"invokeOnRequestExtensions"),Ni=s(async(n,e,t)=>{if(no.length===0)return n;let o=io.getTracer("extension");return o.startActiveSpan("hook:onResponseSending",async r=>{try{let i=n;for(let a of no)await o.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)i=c,u.end();else{let l=new m(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof i}.`);throw u.recordException(l),u.setStatus({code:ro.ERROR}),u.end(),l}});return i}finally{r.end()}})},"invokeOnResponseSendingExtensions"),Di=s(async(n,e,t)=>{if(oo.length===0)return;let o=io.getTracer("extension");return o.startActiveSpan("hook:onResponseSendingFinal",async r=>{try{for(let i of oo)await o.startActiveSpan(i.name,async a=>{try{await i(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:ro.ERROR}),a.end(),u}a.end()})}finally{r.end()}})},"invokeOnResponseSendingFinalExtensions"),Li=!1;async function Mi(n){if(!Li){n&&(g("runtime.extensions"),await n(tn)),kt.value=tn;for(let e of qe)if(e instanceof Ot){let{requestHandlerProxy:t}=e.instrument({accountName:h.instance.build.ACCOUNT_NAME,projectName:h.instance.build.PROJECT_NAME,buildId:h.instance.build.BUILD_ID,zuploVersion:h.instance.build.ZUPLO_VERSION,compatibilityDate:h.instance.build.COMPATIBILITY_DATE,instanceId:h.instance.instanceId,environmentType:h.instance.loggingEnvironmentType,environmentStage:h.instance.loggingEnvironmentStage,deploymentName:h.instance.deploymentName});Si(t)}for(let e of qe)e instanceof Me&&await e.initialize(tn);At.setProblemResponseFormat(tn.problemResponseFormat),Li=!0}}s(Mi,"initializeRuntime");var so={Json:"application/json",Form:"application/x-www-form-urlencoded"};function ao(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(so.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(so.Json)||!e?JSON.stringify(n):n}s(ao,"serialize");function ut(n){return he.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(he.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}s(ut,"isSystemRoute");var me=class{static{s(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,t)=>async(o,r)=>La.getTracer("pipeline").startActiveSpan(`handler:${r.route.handler.export}`,async a=>{try{return await e(o,r)}catch(u){r.log.error("Error executing request handler.",u);let c=t.errorHandler(o,r,u);return a.setStatus({code:ka.ERROR}),c}finally{a.end()}});#t=({processors:e,gateway:t,handler:o})=>async(r,i)=>{let a=[...e],u=s(async P=>{let v=a.pop();return v?v(r,i,t,u):await this.#e(async j=>{let q=await o(j,i);return _a(q)},t)(P,i)},"nextPipe"),l=await u(r),d=new URL(r.url);if(ut(d)&&h.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new Lt(r,l);i.dispatchEvent(p);let f=ye.getContextExtensions(i),y=f.latestRequest,O;try{O=await p.mutableResponse}catch(P){return i.log.error(P),t.errorHandler(r,i,P)}try{O=await f.onResponseSending(O,y,i)}catch(P){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(r,i,P)}try{O=await Ni(O,y,i)}catch(P){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(r,i,P)}i.dispatchEvent(new _t(r,O));try{await f.onResponseSendingFinal(l,y,i)}catch(P){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}try{await Di(l,y,i)}catch(P){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}return O}};function _a(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(ao(n),{headers:{"content-type":"application/json"}})}s(_a,"resultToResponse");var nn=(w=>(w[w.CONTINUE=100]="CONTINUE",w[w.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",w[w.PROCESSING=102]="PROCESSING",w[w.EARLY_HINTS=103]="EARLY_HINTS",w[w.OK=200]="OK",w[w.CREATED=201]="CREATED",w[w.ACCEPTED=202]="ACCEPTED",w[w.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",w[w.NO_CONTENT=204]="NO_CONTENT",w[w.RESET_CONTENT=205]="RESET_CONTENT",w[w.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",w[w.MULTI_STATUS=207]="MULTI_STATUS",w[w.ALREADY_REPORTED=208]="ALREADY_REPORTED",w[w.IM_USED=226]="IM_USED",w[w.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",w[w.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",w[w.FOUND=302]="FOUND",w[w.SEE_OTHER=303]="SEE_OTHER",w[w.NOT_MODIFIED=304]="NOT_MODIFIED",w[w.USE_PROXY=305]="USE_PROXY",w[w.SWITCH_PROXY=306]="SWITCH_PROXY",w[w.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",w[w.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",w[w.BAD_REQUEST=400]="BAD_REQUEST",w[w.UNAUTHORIZED=401]="UNAUTHORIZED",w[w.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",w[w.FORBIDDEN=403]="FORBIDDEN",w[w.NOT_FOUND=404]="NOT_FOUND",w[w.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",w[w.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",w[w.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",w[w.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",w[w.CONFLICT=409]="CONFLICT",w[w.GONE=410]="GONE",w[w.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",w[w.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",w[w.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",w[w.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",w[w.URI_TOO_LONG=414]="URI_TOO_LONG",w[w.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",w[w.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",w[w.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",w[w.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",w[w.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",w[w.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",w[w.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",w[w.LOCKED=423]="LOCKED",w[w.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",w[w.TOO_EARLY=425]="TOO_EARLY",w[w.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",w[w.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",w[w.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",w[w.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",w[w.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",w[w.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",w[w.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",w[w.BAD_GATEWAY=502]="BAD_GATEWAY",w[w.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",w[w.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",w[w.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",w[w.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",w[w.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",w[w.LOOP_DETECTED=508]="LOOP_DETECTED",w[w.NOT_EXTENDED=510]="NOT_EXTENDED",w[w.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",w))(nn||{}),qi={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 Na={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"},uo=Na;function Da(n){return`${new URL(n.url).pathname}`}s(Da,"instance");function Ma(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:h.instance.build.BUILD_ID},o=n.headers.get(Ye);return o&&(t.rayId=o),t}s(Ma,"trace");var qa=s((n,e,t,o,r)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:Da(e),trace:Ma(e,t),...o},additionalHeaders:r,statusText:uo[n.status]}),"merge"),co=class{static{s(this,"HttpProblemsBase")}static format=(e,t,o)=>"problem"in e?et.format(e,t,o):et.format({problem:e},t,o);static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:qi[e],...t}}},x=class extends co{static{s(this,"HttpProblems")}static#e(e,t,o,r,i){let a=qa(this.getProblemFromStatus(e),t,o,r,i);return et.format(a,t,o)}static continue=(e,t,o,r)=>this.#e(200,e,t,o,r);static switchingProtocols=(e,t,o,r)=>this.#e(101,e,t,o,r);static processing=(e,t,o,r)=>this.#e(102,e,t,o,r);static earlyHints=(e,t,o,r)=>this.#e(103,e,t,o,r);static ok=(e,t,o,r)=>this.#e(200,e,t,o,r);static created=(e,t,o,r)=>this.#e(201,e,t,o,r);static accepted=(e,t,o,r)=>this.#e(202,e,t,o,r);static nonAuthoritativeInformation=(e,t,o,r)=>this.#e(203,e,t,o,r);static noContent=(e,t,o,r)=>this.#e(204,e,t,o,r);static resetContent=(e,t,o,r)=>this.#e(205,e,t,o,r);static partialContent=(e,t,o,r)=>this.#e(206,e,t,o,r);static multiStatus=(e,t,o,r)=>this.#e(207,e,t,o,r);static alreadyReported=(e,t,o,r)=>this.#e(208,e,t,o,r);static imUsed=(e,t,o,r)=>this.#e(226,e,t,o,r);static multipleChoices=(e,t,o,r)=>this.#e(300,e,t,o,r);static movedPermanently=(e,t,o,r)=>this.#e(301,e,t,o,r);static found=(e,t,o,r)=>this.#e(302,e,t,o,r);static seeOther=(e,t,o,r)=>this.#e(303,e,t,o,r);static notModified=(e,t,o,r)=>this.#e(304,e,t,o,r);static useProxy=(e,t,o,r)=>this.#e(305,e,t,o,r);static switchProxy=(e,t,o,r)=>this.#e(306,e,t,o,r);static temporaryRedirect=(e,t,o,r)=>this.#e(307,e,t,o,r);static permanentRedirect=(e,t,o,r)=>this.#e(308,e,t,o,r);static badRequest=(e,t,o,r)=>this.#e(400,e,t,o,r);static unauthorized=(e,t,o,r)=>this.#e(401,e,t,o,r);static paymentRequired=(e,t,o,r)=>this.#e(402,e,t,o,r);static forbidden=(e,t,o,r)=>this.#e(403,e,t,o,r);static notFound=(e,t,o,r)=>this.#e(404,e,t,o,r);static methodNotAllowed=(e,t,o,r)=>this.#e(405,e,t,o,r);static notAcceptable=(e,t,o,r)=>this.#e(406,e,t,o,r);static proxyAuthenticationRequired=(e,t,o,r)=>this.#e(407,e,t,o,r);static requestTimeout=(e,t,o,r)=>this.#e(408,e,t,o,r);static conflict=(e,t,o,r)=>this.#e(409,e,t,o,r);static gone=(e,t,o,r)=>this.#e(410,e,t,o,r);static lengthRequired=(e,t,o,r)=>this.#e(411,e,t,o,r);static preconditionFailed=(e,t,o,r)=>this.#e(412,e,t,o,r);static contentTooLarge=(e,t,o,r)=>this.#e(413,e,t,o,r);static uriTooLong=(e,t,o,r)=>this.#e(414,e,t,o,r);static unsupportedMediaType=(e,t,o,r)=>this.#e(415,e,t,o,r);static rangeNotSatisfiable=(e,t,o,r)=>this.#e(416,e,t,o,r);static expectationFailed=(e,t,o,r)=>this.#e(417,e,t,o,r);static imATeapot=(e,t,o,r)=>this.#e(418,e,t,o,r);static misdirectedRequest=(e,t,o,r)=>this.#e(421,e,t,o,r);static unprocessableContent=(e,t,o,r)=>this.#e(422,e,t,o,r);static locked=(e,t,o,r)=>this.#e(423,e,t,o,r);static failedDependency=(e,t,o,r)=>this.#e(424,e,t,o,r);static tooEarly=(e,t,o,r)=>this.#e(425,e,t,o,r);static upgradeRequired=(e,t,o,r)=>this.#e(426,e,t,o,r);static preconditionRequired=(e,t,o,r)=>this.#e(428,e,t,o,r);static tooManyRequests=(e,t,o,r)=>this.#e(429,e,t,o,r);static requestHeaderFieldsTooLarge=(e,t,o,r)=>this.#e(431,e,t,o,r);static unavailableForLegalReasons=(e,t,o,r)=>this.#e(451,e,t,o,r);static internalServerError=(e,t,o,r)=>this.#e(500,e,t,o,r);static notImplemented=(e,t,o,r)=>this.#e(501,e,t,o,r);static badGateway=(e,t,o,r)=>this.#e(502,e,t,o,r);static serviceUnavailable=(e,t,o,r)=>this.#e(503,e,t,o,r);static gatewayTimeout=(e,t,o,r)=>this.#e(504,e,t,o,r);static httpVersionNotSupported=(e,t,o,r)=>this.#e(505,e,t,o,r);static variantAlsoNegotiates=(e,t,o,r)=>this.#e(506,e,t,o,r);static insufficientStorage=(e,t,o,r)=>this.#e(507,e,t,o,r);static loopDetected=(e,t,o,r)=>this.#e(508,e,t,o,r);static notExtended=(e,t,o,r)=>this.#e(510,e,t,o,r);static networkAuthenticationRequired=(e,t,o,r)=>this.#e(511,e,t,o,r)};var $e=class extends Fe{static{s(this,"MetricsPlugin")}};var Q=class n{static{s(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let t=n.#e.get(e);if(!t){let o=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(o),new J(o)}return t}static addLogger(e,t){n.#e.set(e,t)}};var X=class{static{s(this,"BatchDispatch")}constructor(e,t,o,r){this.#t=e,this.#i=t,this.#o=o,this.#n=r??console}#e=void 0;#t;#n;#o;#r=[];#i;enqueue=e=>{this.#r.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#r.length>0){let o=[...this.#r];this.#r.length=0,this.#e=void 0,this.#o(o).catch(r=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,r.message,r.stack)}).finally(()=>{t()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var on=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=h.instance.loggingId,this.#e=e,this.#t=new X("ellie-metrics-transport",10,this.dispatchFunction,Q.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let{remoteLogURL:t,deploymentName:o}=h.instance,{ACCOUNT_NAME:r,PROJECT_NAME:i}=h.instance.build,a=e.map(d=>{let p=Object.assign({},d);return delete p.requestContentLength,delete p.responseContentLength,p}),u=Ai(),c={metadata:{timestamp:new Date,accountName:r,projectName:i,deploymentName:o},metrics:a,features:u},l=await F.fetch(`${t}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(c),headers:{"content-type":"application/json","zp-dn":h.instance.deploymentName??"unknown","user-agent":h.instance.systemUserAgent}});if(!l.ok){let d=await l.text();Q.getLogger(this.#e).error(`Metrics POST responded ${l.status}: ${l.statusText}`,d),ki(u)}}};var ce=class{static{s(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:o,systemRouteName:r,corsPolicy:i="none"}){this.label=e,this.path=t,this.methods=o,this.corsPolicy=i,this.version=Nt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=r}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Nt={name:"__system-no-version",pathPrefix:""};var be=s(async(n,e,t,o)=>{let r=new Date,i=Date.now(),a=await o(n),u=n.headers.get(Ye)??void 0,c=n.headers.get(Ii)??void 0,l=e.incomingRequestProperties,d;e.route instanceof ce&&(d=e.route.systemRouteName);let p=ye.getContextExtensions(e).latestRequest,f={timestamp:r,statusCode:a.status,durationMs:Date.now()-i,requestContentLength:n.headers.get("content-length")?Number(n.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:n.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:h.instance.instanceId,userSub:p.user?.sub,clientIp:c},y=[];return y.push(new on(e)),qe.forEach(O=>{if(O instanceof $e){let P=O.getTransport();y.push(P)}}),y.forEach(O=>{O.pushMetrics(f,e)}),a},"metricsProcessor");var lo=s((n,e)=>{let t=s(async(i,a)=>{let c=new URL(i.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return x.notFound(i,a);let l=h.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,compatibilityDate:l.COMPATIBILITY_DATE,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=i.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&Q.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),o=new me({processors:[be],handler:t,gateway:e}),r=new ce({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(r,o.execute)},"registerBuildRoute");var{toString:Ha}=Object.prototype,{propertyIsEnumerable:Ua}=Object.prototype;function po(n){return Ha.call(n)}s(po,"toString");function Ee(n){return typeof n=="string"}s(Ee,"isString");function ct(n){return Ee(n)&&n!==""}s(ct,"isNonEmptyString");function Hi(n){return po(n)==="[object RegExp]"}s(Hi,"isRegexp");function Ui(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>Ua.call(n,e))]}s(Ui,"getOwnEnumerableKeys");function tt(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}s(tt,"isObject");function mo(n){return typeof n=="number"&&!isNaN(n)}s(mo,"isNumber");function go(n){return n===!0||n===!1}s(go,"isBoolean");function Zi(n){return typeof n>"u"}s(Zi,"isUndefined");function Fi(n){return Zi(n)||n===null}s(Fi,"isUndefinedOrNull");function Dt(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}s(Dt,"isErrorLike");var $i=new Map;function je(n){if(Array.isArray(n)&&!n.some(r=>typeof r!="number"))return n;if(typeof n!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(n))throw new Error("Malformed input string");let e=$i.get(n);if(e)return e;let t=n.split(","),o=[];for(let r of t){let i=r.split("-");if(i.length===2){let a=parseInt(i[0],10),u=parseInt(i[1],10);for(let c=a;c<=u;c++)o.push(c)}else o.push(parseInt(r,10))}return $i.set(n,o),o}s(je,"statusCodesStringToNumberArray");function nt(n,e,t){if(!e.startsWith("."))throw new m(`Invalid ${t} - must start with '.' - '${e}' does not`);let o=e.split(".").splice(1),r=n;return o.forEach(i=>{if(r===void 0)throw new L(`Error applying ${t} '${e}', reading '${i}'`);r=r[i]}),`${r}`}s(nt,"getValueFromRequestUser");function ot(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new m("Received an array that contains non-string values.");return n}if(Ee(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new m(`Expected type of string, received type '${typeof n}'`)}s(ot,"parseValueToStringArray");function ji(n){if(n==null)return[];if(!Array.isArray(n))throw new m(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!tt(t))throw new m(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!ct(t.name))throw new m("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!mo(t.maxAge))throw new m(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!go(t.allowCredentials))throw new m("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let o=fo(t,"allowedHeaders"),r=fo(t,"allowedMethods"),i=fo(t,"exposeHeaders"),a;try{a=ot(t.allowedOrigins)}catch(c){throw new m(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:t.name,allowCredentials:typeof t.allowCredentials=="boolean"?String(t.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:o?o.join(", "):void 0,allowedMethods:r?r.join(", "):void 0,exposeHeaders:i?i.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}s(ji,"parseCorsPolicies");function fo(n,e){let t;if(n[e]!==void 0)try{t=ot(n[e])}catch(o){throw new m(`Value of '${e}' on custom cors policies is invalid. ${o.message} If using an environment variable, check that it is set correctly.`)}return t}s(fo,"parseOptionalProperty");var rn=s((n,e)=>{if(e===null)return;if(n.find(a=>a==="*"))return e;let o=n.map(a=>a.trim().toLowerCase()),r=e.toLowerCase();return o.find(a=>a===r)},"findMatchingOrigin"),sn=s((n,e)=>{let t={"access-control-allow-origin":e};n.allowedHeaders&&(t["access-control-allow-headers"]=n.allowedHeaders),n.allowedMethods&&(t["access-control-allow-methods"]=n.allowedMethods),n.exposeHeaders&&(t["access-control-expose-headers"]=n.exposeHeaders);let o=n.allowCredentials;o&&(t["access-control-allow-credentials"]=o);let r=n.maxAge?.toString()??void 0;return r&&(t["access-control-max-age"]=r),t},"generateCorsHeaders");var ho=s((n,e)=>{let t=e.routeData.corsPolicies,o=s(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return x.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let f=n.lookup(l,c);if(!f)return x.notFound(a,u);let y=f.routeConfiguration,O=Za(l,d,p,y,t);return O.isValid?new Response(void 0,{status:200,statusText:"OK",headers:O.headers}):(O.error&&u.log.warn(O.error),x.notFound(a,u))},"optionsHandler"),r=new me({processors:[be],handler:o,gateway:e}),i=new ce({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(i,r.execute)},"registerCorsRoute"),Za=s((n,e,t,o,r)=>{let i={isValid:!1,headers:{}};if(o.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":t,"access-control-allow-methods":n,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(o.corsPolicy==="none")return{...i,error:`No CORS policy set for the route '${o.pathPattern}'`};let a=r?.find(l=>l.name===o.corsPolicy);if(!a)throw new m(`Invalid Configuration - corsPolicy '${o.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=rn(a.allowedOrigins,t);return u?{isValid:!0,headers:sn(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var zi=s((n,e)=>{let t=s(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),o=new me({processors:[be],handler:t,gateway:e}),r=new ce({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});n.addRoute(r,o.execute)},"registerNoRoutes");var yo=new ce({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Bi=s((n,e)=>{let t=s(async(r,i)=>{let a=kt.value?.notFoundHandler;if(a){let u=ye.getContextExtensions(i);return a(r,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return x.notFound(r,i)},"notFoundHandler"),o=new me({processors:[be],handler:t,gateway:e});n.addRoute(yo,o.execute)},"registerNotMatchedHandler");var Fa=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Gi=s(n=>{Fa.forEach(e=>n.delete(e))},"stripCorsHeaders"),an=s(async(n,e,t,o)=>{let r=e.route;if(!r.corsPolicy||r.corsPolicy==="none"){let d=await o(n),p=new Headers(d.headers);return Gi(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let i=await o(n);if(!(i instanceof Response))throw new J(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=$a(r,t.routeData.corsPolicies),u=ja(n,a),c=new Headers(i.headers);return Gi(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(i.body,{status:i.status,statusText:i.statusText,headers:c,webSocket:i.webSocket})},"corsProcessor"),$a=s((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(o=>o.name===n.corsPolicy);if(t===void 0)throw new m(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),ja=s((n,e)=>{let t=rn(e.allowedOrigins,n.headers.get("origin"));return t?sn(e,t):{}},"getCorsHeaders");var bo=s((n,e)=>{let t=s(async()=>new Response(JSON.stringify({buildId:h.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),o=new me({processors:[an],handler:t,gateway:e}),r=new ce({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(r,o.execute)},"registerPingRoute");import{SpanStatusCode as Vi,trace as Wi}from"@opentelemetry/api";var Le={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var un=class{static{s(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!Ee(t))throw new L(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},ae=class extends un{static{s(this,"InboundPolicy")}},ze=class extends un{static{s(this,"OutboundPolicy")}};var Po=class extends ae{static{s(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,t,o){super(t,o),this.policyType=e.name,this.#e=e}handler(e,t){return this.#e(e,t,this.options,this.policyName)}},Io=class extends ze{static{s(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,t,o){super(t,o),this.policyType=e.name,this.#e=e}handler(e,t,o){return this.#e(e,t,o,this.options,this.policyName)}},wo=new Map;function Mt(n,e){let t,o;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],o=n.path),t.filter(i=>!wo.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new m(`Invalid state - no Policy with the name '${i}' ${o&&`on route '${o}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new m(`Invalid state - invalid policy '${i}' on route '${o}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new m(`Invalid state - invalid policy '${i}' on route '${o}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new m(`Invalid state - invalid policy '${i}' on route '${o}' (typeof module '${typeof u}')`);if(u.prototype instanceof ae)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new Po(u,a.handler.options,a.name);else throw new m(`Invalid state - invalid policy '${i}' on route '${o}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${i}' on route '${o}' (typeof handler '${typeof c.handler}')`);wo.set(a.name,c)}),t.map(i=>{let a=wo.get(i);if(a===void 0)throw new L("Internal error. Policy not found in cache.");return a})}s(Mt,"getInboundPolicyInstances");var Ro=new Map;function za(n,e){let t=n.policies?.outbound??[];return t.filter(r=>!Ro.has(r)).forEach(r=>{let i=e?.find(c=>c.name===r);if(!i)throw new m(`Invalid state - no Policy with the name '${r}' on route '${n.path}' was found in the policies configuration (check case).`);if(typeof i.handler?.module!="object")throw new m(`Invalid state - invalid policy '${r}' on route '${n.path}' (typeof policy '${typeof i.handler?.module}')`);let a=i.handler?.module[i.handler.export],u;if(typeof a!="function")throw new m(`Invalid state - invalid policy '${r}' on route '${n.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof ze)u=new a(i.handler.options??{},i.name);else if(typeof a=="function")u=new Io(a,i.handler.options??{},i.name);else throw new m(`Invalid state - invalid policy '${r}' on route '${n.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new m(`Invalid state - invalid handler on policy '${r}' on route '${n.path}'`);Ro.set(i.name,u)}),t.map(r=>{let i=Ro.get(r);if(i===void 0)throw new L("Internal error. Policy not found in cache.");return i})}s(za,"getOutboundPolicyInstances");var Eo=s(n=>async(e,t)=>{let o=ye.getContextExtensions(t),r=Wi.getTracer("pipeline");return await r.startActiveSpan("policies:inbound",async i=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;let l=await r.startActiveSpan(`policy:${c.policyName}`,async d=>{let p=await c.handler(u,t);if(p instanceof Request||p instanceof te||p instanceof Response)return d.end(),p;{let f=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${t.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:Vi.ERROR}),d.recordException(f),f}});if(l instanceof te)u=l;else if(l instanceof Request)u=new te(l);else if(l instanceof Response)return l;o.latestRequest=u}return u}finally{i.end()}})},"toStackedInboundHandler"),Ba=s(n=>async(e,t,o)=>{let r=Wi.getTracer("pipeline");return await r.startActiveSpan("policies:outbound",async i=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await r.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(Le.PolicyName,c.policyName),d.setAttribute(Le.PolicyType,c.policyType);let p=await c.handler(u,t,o);if(p instanceof Response)return p;{let f=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${o.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:Vi.ERROR}),d.recordException(f),f}}finally{d.end()}})}return u}finally{i.end()}})},"toStackedOutboundHandler"),cn=s(async(n,e,t,o)=>{let r=Mt(e.route,t.routeData.policies),i=za(e.route,t.routeData.policies);return Ji({request:n,context:e,inboundPolicies:r,outboundPolicies:i,gateway:t,next:o})},"policyProcessor");function Ki({inboundPolicies:n=[],outboundPolicies:e=[]}){return s(async(o,r,i,a)=>Ji({request:o,context:r,inboundPolicies:n,outboundPolicies:e,gateway:i,next:a}),"policyProcessor")}s(Ki,"createInternalPolicyProcessor");async function Ji({request:n,context:e,inboundPolicies:t,outboundPolicies:o,gateway:r,next:i}){let a=Eo(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await i(u),l=Ba(o),d;return h.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,n,e):d=c.ok?l(c,n,e):c,d}catch(u){return e.log.error(u),r.errorHandler(n,e,u)}}s(Ji,"executePolicyProcessor");function Qi(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},r=(e||{}).decode||Ga,i=0;for(;i<n.length;){let a=n.indexOf("=",i);if(a===-1)break;let u=n.indexOf(";",i);if(u===-1)u=n.length;else if(u<a){i=n.lastIndexOf(";",a-1)+1;continue}let c=n.slice(i,a).trim();if(t[c]===void 0){let l=n.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),t[c]=Va(l,r)}i=u+1}return t}s(Qi,"parse");function Ga(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}s(Ga,"decode");function Va(n,e){try{return e(n)}catch{return n}}s(Va,"tryDecode");function Xi(n,e){try{let t=/v\d+(-\d+)?/g,r=Qi(e.get("Cookie")||"")["zp-dev-portal"];return r!==null&&r&&t.test(r)?`https://dev-portal-${r}.zuplo.com`:n}catch{}return n}s(Xi,"devPortalBaseURL");var Yi="/__zuplo/dev-portal",Wa="dev-portal-id",Ka="dev-portal-host",Ja="zp-account",Qa="zp-project",Xa="dev-portal-build",Ya=`
|
|
26
26
|
<!DOCTYPE html>
|
|
27
27
|
<html lang="en">
|
|
28
28
|
<head>
|
|
@@ -36,20 +36,20 @@ import{a as qe,d as Re,e as Oa,f as Fn,g as $n,h as Aa,i as ka}from"./chunk-IOKN
|
|
|
36
36
|
<p>For more information, see <a href="https://zuplo.com/docs/articles/developer-portal">https://zuplo.com/docs/articles/developer-portal</a>.</p>
|
|
37
37
|
</body>
|
|
38
38
|
</html>
|
|
39
|
-
`,es=s((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,
|
|
40
|
-
`).filter(e=>!e.trim().startsWith("at async file")).map((e,t)=>{let
|
|
41
|
-
`)}s(
|
|
39
|
+
`,es=s((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,o=h.instance.deploymentName,r=h.instance.devPortalBaseUrl,i=s(async(c,l)=>{if(h.instance.isLocalDevelopment)return new Response(Ya,{headers:{"content-type":"text/html"}});if(!o)return x.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=Xi(r,c.headers),f=new URL(`${d.pathname}${d.search}`,p),{headers:y,method:O,body:P}=c;return h.instance.build.ACCOUNT_NAME&&y.set(Ja,h.instance.build.ACCOUNT_NAME),h.instance.build.PROJECT_NAME&&y.set(Qa,h.instance.build.PROJECT_NAME),y.set(Wa,o),y.set(Ka,d.host),y.set(Xa,h.instance.build.BUILD_ID),await F.fetch(f.toString(),{headers:y,method:O,body:P,redirect:"manual"})},"devPortalRoute"),a=new me({processors:[be,cn],handler:i,gateway:e}),u=new ce({label:"SYSTEM_API_DOCS_V3_ROUTE",methods:["GET","PUT","POST","DELETE","PATCH","HEAD"],path:`(${t}|/_next)(.*)`,systemRouteName:"developer-portal"});n.addRoute(u,a.execute)},"registerDevPortalV3Route"),ts=s((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,o=s(async a=>{let u=new URL(a.url);return u.pathname=`${t}${u.pathname.substring(Yi.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),r=new me({processors:[be],handler:o,gateway:e}),i=new ce({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${Yi}(.*)`,systemRouteName:"developer-portal-legacy"});n.addRoute(i,r.execute)},"registerDevPortalLegacyRedirectRoute");var ds=Je(Qe());var xo=0,qt=class{static{s(this,"CoreLogger")}constructor(e,t,o,r,i){this.#n=t,this.#o=o??"local",this.#r=r,this.#i=i,this.#e(e)}#e=e=>{let t=["error","warn","info","debug"],o=!1,r=s(()=>{},"emptyFunction"),i=s((a,u)=>{this.#i.forEach(c=>{c.log(a,u)})},"pushFunction");t.forEach(a=>{this.#t[a]=o?r:i,a==e&&(o=!0)})};#t={};#n;#o;#r;#i;log(e,t,o,r,i,a){xo>=Number.MAX_SAFE_INTEGER&&(xo=0);let u={requestId:o,rayId:r,level:e,logSource:t,messages:i,timestamp:new Date,logOwner:this.#n,loggingId:this.#o,buildId:this.#r,vectorClock:xo++};this.#t[e](u,a)}};var ge=class extends Fe{static{s(this,"LogPlugin")}};var ln=class{static{s(this,"LoggingContext")}constructor(e,t,o){this.#e=e,this.custom=t,this.originalRequest=o}#e;custom;originalRequest;waitUntil=e=>{this.#e.waitUntil(e)}};var Ht=class{static{s(this,"RequestLogger")}constructor(e,t,o,r){this.#t=e,this.#n=t,this.#o=o,this.#r=r}#e="request";#t;#n;#o;#r;debug=(...e)=>{this.#o.log("debug",this.#e,this.#t,this.#n,e,this.#r)};info=(...e)=>{this.#o.log("info",this.#e,this.#t,this.#n,e,this.#r)};log=(...e)=>{this.#o.log("info",this.#e,this.#t,this.#n,e,this.#r)};warn=(...e)=>{this.#o.log("warn",this.#e,this.#t,this.#n,e,this.#r)};error=(...e)=>{this.#o.log("error",this.#e,this.#t,this.#n,e,this.#r)}};var eu=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(n=>[n.name,n]),tu=new Map(eu);var nu=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],To=Symbol(".toJSON was called"),ou=s(n=>{n[To]=!0;let e=n.toJSON();return delete n[To],e},"toJSON"),ru=s(n=>tu.get(n)??Error,"getErrorConstructor"),ns=s(({from:n,seen:e,to:t,forceEnumerable:o,maxDepth:r,depth:i,useToJSON:a,serialize:u})=>{if(!t)if(Array.isArray(n))t=[];else if(!u&&Dt(n)){let l=ru(n.name);t=new l}else t={};if(e.push(n),i>=r)return t;if(a&&typeof n.toJSON=="function"&&n[To]!==!0)return ou(n);let c=s(l=>ns({from:l,seen:[...e],forceEnumerable:o,maxDepth:r,depth:i,useToJSON:a,serialize:u}),"continueDestroyCircular");for(let[l,d]of Object.entries(n)){if(typeof Buffer=="function"&&Buffer.isBuffer(d)){t[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){t[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){t[l]=d;continue}if(!e.includes(n[l])){i++,t[l]=c(n[l]);continue}t[l]="[Circular]"}}for(let{property:l,enumerable:d}of nu)typeof n[l]<"u"&&n[l]!==null&&Object.defineProperty(t,l,{value:Dt(n[l])?c(n[l]):n[l],enumerable:o?!0:d,configurable:!0,writable:!0});return t},"destroyCircular");function Pe(n,e){let t=e?.maxDepth??Number.POSITIVE_INFINITY,o=e?.useToJSON??!0;return typeof n=="object"&&n!==null?ns({from:n,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:o,serialize:!0}):typeof n=="function"?`[Function: ${n.name??"anonymous"}]`:n}s(Pe,"serializeError");var iu=/file:\/\/\/(.*?)\/dist\//g,su="at async Event.respondWith";function os(n){return typeof n!="string"?n:n.split(`
|
|
40
|
+
`).filter(e=>!e.trim().startsWith("at async file")).map((e,t)=>{let o=e.replaceAll(iu,"").replaceAll(su,"").trim();return t===0||o.length===0?o:` ${o}`}).filter(e=>e.length>0).join(`
|
|
41
|
+
`)}s(os,"cleanStack");function dn(n,e,t=""){let o=[],r=e?.maxDepth??3;return s(function i(a,u={},c,l){let d=u.indent||" ",p;u.inlineCharacterLimit===void 0?p={newline:`
|
|
42
42
|
`,newlineOrSpace:`
|
|
43
|
-
`,pad:c,indent:c+d}:p={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let
|
|
44
|
-
`).replace(new RegExp(p.pad,"g"),c).replace(new RegExp(p.indent,"g"),c+d)},"expandWhiteSpace");if(
|
|
45
|
-
`?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}s(
|
|
46
|
-
`)}s(os,"messagesToMultilineText");function Ue(n){return typeof n=="string"?n:JSON.stringify(n)}s(Ue,"stringifyNonString");function Or(n){return typeof n=="string"?n:n===null?"null":typeof n>"u"?"undefined":typeof n=="number"||typeof n=="boolean"||typeof n=="bigint"||typeof n=="symbol"?n.toString():typeof n=="function"?`[function ${n.name}]`:typeof n=="object"&&Array.isArray(n)?`[array ${n.length}]`:n instanceof Error?`${n.name??"Error"}: ${n.message??"unknown"}`:typeof n=="object"?fr(n):"unknown"}s(Or,"stringifyNonStringToText");import{importPKCS8 as uu,SignJWT as cu}from"jose";async function fe(n,e,t){for(let r=0;r<=n.retries;r++){let o=F.fetch(e,t);if(r===n.retries)return o;let i=await o;if(i.status<500&&i.status!==429)return i;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:i.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,r)))}throw new m("An unknown error occurred, ensure retries is not negative")}s(fe,"fetchRetry");async function _e({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:i,privateKey:a}=n;return await new cu(r).setProtectedHeader({alg:"RS256",kid:i}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}s(_e,"getTokenFromGcpServiceAccount");async function is(n,e,t){if(!n.startsWith("projects/"))throw new m(`The provided audience is invalid: ${n}. It must start with 'projects/'.`);return Ar("https://sts.googleapis.com/v1/token",{audience:`//iam.googleapis.com/${n}`,grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token_type:"urn:ietf:params:oauth:token-type:jwt",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,scope:"https://www.googleapis.com/auth/cloud-platform"},t)}s(is,"exchangeIDTokenForGcpWorkloadToken");async function ss({serviceAccountEmailOrIdentifier:n,audience:e,accessToken:t},r){let o={audience:e,includeEmail:!0};return us(`https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${encodeURIComponent(n)}:generateIdToken`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},redirect:"follow",body:JSON.stringify(o)},r)}s(ss,"generateServiceAccountIDToken");async function as(n,e,t){return Ar(n,{token:e,returnSecureToken:!0},t)}s(as,"exchangeFirebaseJwtForIdToken");async function dn(n,e,t){return Ar(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}s(dn,"exchangeGgpJwtForIdToken");async function Ar(n,e,t){let r={method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)};return us(n,r,t)}s(Ar,"fetchTokenFromBody");async function us(n,e,t){let r=await fe(t,n,e);if(r.status!==200){let i;try{let a=await r.text(),u=JSON.parse(a);i={cause:u.error_description??u.error??u}}catch{}throw new k({message:"Could not get token from Google Identity",extensionMembers:i})}return await r.json()}s(us,"fetchToken");var xe=class n{static{s(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),r=await uu(t.private_key.trim(),"RS256");return new n({serviceAccount:t,privateKey:r})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};async function ue(n){if(n.level==="error"&&console.error(n.messages),!f.instance.remoteLogURL||!f.instance.loggingId||!f.instance.remoteLogToken){console.warn("Remote logger is not configured. Skipping log entry.");return}try{let e={logOwner:"user",logSource:"runtime",rayId:null,requestId:`global-${crypto.randomUUID()}`,timestamp:new Date,buildId:f.instance.build.BUILD_ID,loggingId:f.instance.loggingId,...n,vectorClock:0};await cs({loggingUrl:f.instance.remoteLogURL,loggingId:f.instance.loggingId,loggingToken:f.instance.remoteLogToken},[e])}catch(e){console.error(e)}}s(ue,"sendRemoteGlobalLog");async function cs({loggingUrl:n,loggingId:e,loggingToken:t},r){try{await F.fetch(`${n}/publish/${e}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:r.map(o=>({...o,messages:ze(o.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${t}`,"user-agent":f.instance.systemUserAgent,"zp-dn":f.instance.deploymentName??"unknown"}})}catch(o){console.error(o)}}s(cs,"sendRemoteLogs");var lu=s(({url:n,remoteLogToken:e,loggingId:t,sendOnlyErrors:r})=>async o=>{let i;r===!0?i=o.filter(a=>a.level==="error"):i=o,i.length!==0&&await cs({loggingUrl:n,loggingId:t,loggingToken:e},i)},"dispatchFunction"),pn,mn=class{static{s(this,"RemoteLogTransport")}constructor(e){pn||(pn=new J("remote-log-transport",1,lu(e)))}log(e,t){pn.enqueue(e),t.waitUntil(pn.waitUntilFlushed())}};var kr=class extends me{constructor(t){super();this.options=t}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Mt(this.options)}},du="https://logging.googleapis.com/v2/entries:write?alt=json",Lr={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Mt=class{static{s(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=f.instance.loggingEnvironmentType,this.#i=f.instance.loggingEnvironmentStage,this.#r=f.instance.deploymentName,g("logging.google-cloud")}#e;#t;#n;#r;#o;#i;async init(){this.#t=await xe.init(this.#e)}log(e,t){if(!this.#t)throw new W("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:ze(e.messages)},o=this.#t.projectId??"zuplo-production",i={logName:this.#n,resource:{type:"global"},severity:Lr[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(i.labels.rayId=e.rayId);let a=at(r.allMessages);i.jsonPayload={...r,message:a},this.batcher.enqueue(i),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await xe.init(this.#e));let t=await _e({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"});try{let r=await F.fetch(du,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});if(!r.ok){let o="";try{o=await r.text()}catch{}await ue({level:"error",messages:[`Failed to send logs to Google: ${r.status} - ${r.statusText}`,o]})}}catch{await ue({level:"error",messages:["Failed to connect to Google logging service. Check that the URL is correct."]})}};batcher=new J("google-log-transport",1,this.dispatchFunction)};var gn="gcp";function fn(n){let e={allMessages:ze(n.messages)},t="zuplo-production",r=at(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:Lr[n.level],timestamp:n.timestamp,"logging.googleapis.com/labels":{buildId:n.buildId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${n.requestId}`,allMessages:e.allMessages};return n.rayId&&(o["logging.googleapis.com/labels"].rayId=n.rayId),o}s(fn,"gcpLogFormat");var Ht=class{static{s(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===gn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[fn(e)])}else this.#e.log(JSON.stringify(e))}};var Mr=class extends me{constructor(t){super();this.options=t}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new Ut(this.options)}},_r="__ddtags",Nr="__ddattr",Dr=s(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),pu=s(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(Dr(r)):t.push(`${Dr(r)}:${Dr(o.toString())}`)}),t.join(",")},"formatTags"),Ut=class{static{s(this,"DataDogTransport")}constructor(e){g("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=f.instance.loggingEnvironmentType,this.#o=f.instance.loggingEnvironmentStage,this.#n=f.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[_r];o&&typeof o=="object"&&Object.assign(r,o);let i=[...e.messages],a=e.messages.findIndex(y=>y[_r]!==void 0);a>-1&&(Object.assign(r,i[a][_r]),i.splice(a,1));let u={},c=t.custom[Nr];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(y=>y[Nr]!==void 0);l>-1&&(Object.assign(u,i[l][Nr]),i.splice(l,1));let d=ze(i),h={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:at(d),service:e.loggingId,ddtags:pu(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(h,u),this.batcher.enqueue(h),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length!==0)try{let t=await F.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!t.ok){let r="";try{r=await t.text()}catch{}await ue({level:"error",messages:[`Failed to send logs to DataDog: ${t.status} - ${t.statusText}`,r]})}}catch{await ue({level:"error",messages:["Failed to connect to DataDog logging service. Check that the URL is correct."]})}};batcher=new J("data-dog-transport",10,this.dispatchFunction)};var qt=class{static{s(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===gn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[fn(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId,vectorClock:e.vectorClock}])}};var mu={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},ls=s((n,e)=>t=>{let r={};return r.deploymentName=n,r.labels={requestId:t.requestId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},r.rayId=t.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=t.vectorClock,{timestamp:t.timestamp,observerdTimestamp:t.timestamp,traceId:t.requestId,severityText:t.level,severityNumber:mu[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var gu=s(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let i=ls(t,r);try{await F.fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(i)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":f.instance.systemUserAgent,"zp-dn":f.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),hn,yn=class{static{s(this,"UnifiedLogTransport")}constructor(e){hn||(hn=new J("unified-log-transport",1,gu(e)))}async log(e,t){hn.enqueue(e),t.waitUntil(hn.waitUntilFlushed())}};var Hr=(0,ds.debug)("zuplo:logging"),bn=class n{static{s(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(f.instance,e),r=await n.setupUserCoreLogger(f.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;Hr("Gateway.setupSystemCoreLogger");let o=[],i=t.getService(Jt);return i?o.push(new qt(i.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new Ht(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new yn({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new Nt(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){Hr("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:i}=e,a=t.getService(Jt);if(a&&a.captureUserLogs===!0?r.push(new qt(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new Ht(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new mn({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:!e.isWorkingCopy})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&(g("logging.google.legacy-initialization"),r.push(new Mt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME}))),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){g("logging.datadog.legacy-initialization");let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new Ut({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return He.forEach(u=>{u instanceof me&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new Nt(e.userLogLevel,"user",e.loggingId,i.BUILD_ID,r)}createRequestLoggers(e,t,r,o,i){Hr("Gateway.createRequestLoggers");let a=new cn(r,o,i),u=new Dt(e,t,this.systemCoreLogger,a);return{userRequestLogger:new Dt(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var tt=class{static{s(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};var Ur=class{static{s(this,"RouterEntry")}constructor(e,t,r,o){this.fullPath=e,this.urlPattern=t,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},Zt=class{static{s(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},qr=class extends Error{static{s(this,"RouterError")}constructor(e,t){super(e,t)}},Ft=class{static{s(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof tt||e instanceof ae))throw new W("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(i=>i.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let i=new URLPattern({pathname:o}),a=new Ur(o,i,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(i){throw new qr(`addRoute-error: Invalid path '${o}'. '${i.message}'`,{cause:i})}}lookup(e,t){if(typeof e>"u")throw new m(`Invalid request - Method was undefined. Path: '${t}'`);let r=this.routeEntries.filter(o=>o.config.methods.includes(e));if(r.length!==0)for(let o=0;o<r.length;o++){let i=r[o],u=i.urlPattern.exec({pathname:t});if(u!==null)return new Zt(i.config,i.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],a=o.urlPattern.exec({pathname:e});if(a!==null){let u=new Zt(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var Zr;function ps(n){Zr=n}s(ps,"setGlobalZuploEventContext");function wn(){if(Zr===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return Zr}s(wn,"getGlobalZuploEventContext");function ms({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);xi.includes(o.toLowerCase())&&!Ti.includes(r.toLowerCase())&&t.delete(r)}t.delete(di)}else Ei.forEach(r=>{t.delete(r)});return t}s(ms,"normalizeIncomingRequestHeaders");var Ne=(0,gs.debug)("zuplo:runtime"),hu=s(n=>{let e=n.findIndex(t=>t.name===kt.name);return e>-1?[...n.splice(e),kt]:[...n,kt]},"setupSystemNoVersion"),he=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;Ne("Gateway.constructor"),Le,this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{s(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(Ne("Gateway.initialize"),!n.#e){let i=await bn.init(r),a=e(),u={...a,corsPolicies:ji(a.corsPolicies)},c=new n(u,t,i,o);n.#e=c}if(!n.#e)throw new W("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){Ne("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new W("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[un,sn,be];#o;setupRoutes=()=>{Ne("Gateway.setupRoutes");let e=this.routeData,t=hu(e.versions),r=new Ft(t);if(e.routes.length===0)return gr(r,this),Pr(r,this),wr(r,this),zi(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(ts(r,this),es(r,this)),gr(r,this),Pr(r,this),wr(r,this);for(let i of He)i instanceof Me&&i.registerRoutes(r,this);return e.routes.forEach(i=>{let a;if(typeof i.handler?.module=="object"&&(a=i.handler?.module[i.handler.export]),typeof a!="function")throw new m(`Invalid state - No handler on route for path '${i.path}'`);let u=new pe({processors:this.#r,handler:a,gateway:this}),c=new tt(i);r.addRoute(c,u.execute)}),Bi(r,this),r};setupErrorHandler=()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new m("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=s((t,r,o)=>this.#i(t,r,o),"errorHandler");return e};errorHandler(e,t,r){try{return this.#o(e,t,r)}catch(o){return Ne("An error occurred in the user's errorHandler",o),this.#i(e,t,o)}}#i(e,t,r){Ne("Gateway.internalErrorResponse");let o={};if(f.instance.isLocalDevelopment||f.instance.isWorkingCopy){if(r instanceof k&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let i=Pe(r.cause);"stack"in i&&(i.stack=rs(i.stack)),o={cause:i}}}return x.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t,r){let{requestId:o,rayId:i}=t;ps(r);let a=ms({headers:e.headers,removeAllVendorHeadersExceptListed:f.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(Ke,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let j=new Headers(u.headers);j.set(Bn,"true"),u=new Request(u,{headers:j,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(o,i,r,c,u),p=new URL(u.url),h=p.pathname,y=this.#n.lookup(u.method,h);if(!y)throw new W(`Invalid state - no route match - should have been picked up by the not found handler, path: '${h}'`);let O=new Rn(e.headers),P=new te(u,{params:y.params}),C=new Pn({logger:l,route:y.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:O}),H=y.routeConfiguration.raw();fu.getActiveSpan()?.setAttributes({"http.route":C.route.path??C.route.pathPattern,"cloud.region":C.incomingRequestProperties.colo,[Le.RoutePathPattern]:C.route.pathPattern,[Le.RouteOperationId]:H.operationId,[Le.RouteTrace]:H["x-zuplo-trace"],[Le.RouteSystem]:ot(p)?!0:void 0});let _=ye.initialize(C,P);if(y.routeConfiguration===Rr&&St.value?.notFoundHandler!==void 0){let j=this.#n.lookupByPathOnly(h);_.pathOnlyMatches=j.map(q=>q.routeConfiguration).filter(q=>q instanceof tt)}try{if(Y.addLogger(C,d),f.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!ot(p):!p.pathname.startsWith("/__zuplo")){let E=await _i(P,C);if(E instanceof Response)return E;{let M=ye.getContextExtensions(C);P=E,M.latestRequest=P}}ot(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:y.routeConfiguration.path});let j=y.executableHandler;yu(j,y,u),Ne("Gateway.handleRequest - call user handler");let q=await j(P,C);if(Ne("Gateway.handleRequest - user handler"),!(q instanceof Response))throw new k(`Invalid Response type from the request handler: ${typeof q}`);if(q.bodyUsed)throw new k("The response object has already been used. Return a new response instead.");let $;if(q.headers.get(Ke)===null&&!q.webSocket){let E=new Headers(q.headers);E.set(Ke,o),$=new Response(q.body,{status:q.status,statusText:q.statusText,headers:E,cf:q.cf})}else $=q;return $}catch(j){return Ne("Gateway - error executing handler",j),j instanceof k?(l.error(j),d.warn(j)):d.error(j),await this.#i(P,C,j)}}};function yu(n,e,t){if(Ne("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new m(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new m(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}s(yu,"checkHandler");var fs=s(async(n,e,t)=>{let r=he.instance.routeData.policies,o=_t([n],r);if(o.length===0)throw new k(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy");var Rn=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Xn);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Yn)??void 0}get city(){return this.#e.get(Gn)??this.#e.get(yi)??void 0}get continent(){return this.#e.get(Vn)??this.#e.get(bi)??void 0}get country(){return this.#e.get(Wn)??this.#e.get(wi)??void 0}get latitude(){return this.#e.get(Jn)??this.#e.get(Pi)??void 0}get longitude(){return this.#e.get(Kn)??this.#e.get(Ri)??void 0}get colo(){return this.#e.get(Qn)??void 0}get postalCode(){return this.#e.get(fi)??this.#e.get(er)??void 0}get metroCode(){return this.#e.get(gi)??this.#e.get(tr)??void 0}get region(){return this.#e.get(pi)??this.#e.get(nr)??void 0}get regionCode(){return this.#e.get(mi)??this.#e.get(rr)??void 0}get timezone(){return this.#e.get(hi)??this.#e.get(or)??void 0}toJSON(){return{asn:this.asn,asOrganization:this.asOrganization,city:this.city,continent:this.continent,country:this.country,latitude:this.latitude,longitude:this.longitude,colo:this.colo,postalCode:this.postalCode,metroCode:this.metroCode,region:this.region,regionCode:this.regionCode,timezone:this.timezone}}},Ot=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},At=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},ye=class n{static{s(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let r=new n(t);return n.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=n.#e.get(e);if(!t)throw new k(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)};onResponseSending=async(e,t,r)=>{let o=e;for(let i of this.#n)o=await i(e,t,r);return o}},Pn=class extends EventTarget{static{s(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:i,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=i,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>fs(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{ye.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{ye.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=s(i=>{try{typeof t=="function"?t(i):t.handleEvent(i)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var ge=class n{static{s(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,t){n.set(e,this.#t,t)}get(e){return n.get(e,this.#t)}static set(e,t,r){n.#e||(n.#e=new WeakMap);let o=n.#e.get(e);o||(o=new Map),o.set(t,r),n.#e.set(e,o)}static get(e,t){return n.#e||(n.#e=new WeakMap),n.#e.get(e)?.get(t)}};import{AsyncLocalStorage as bu}from"node:async_hooks";var hs={request:new bu};var wu="Error initializing gateway. Check your configuration for errors or contact support.",Ru="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",Fr=class{constructor(e,t,r,o,i,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=i;this.runtimeInit=a}static{s(this,"Handler")}requestHandler=async(e,t,r)=>{let o=e.headers.get(Ke)??e.headers.get(li)??crypto.randomUUID(),i=e.headers.get(Je),a={requestId:o,rayId:i};return hs.request.run(a,async()=>{f.initialize({build:this.buildEnvironment,runtime:t});try{await Mi(this.runtimeInit)}catch(c){this.handleError(c,Ru,e)}return Si(s(async(c,l)=>{let d;try{d=await he.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,wu,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,r)})};handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof m&&(t=e.message);let o={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:t,instance:r.url,trace:{timestamp:Date.now(),rayId:r.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:f.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};var Ts=Ve(We());function Pu(n){for(var e=[],t=0;t<n.length;){var r=n[t];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:t,value:n[t++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:n[t++]});continue}if(r==="{"){e.push({type:"OPEN",index:t,value:n[t++]});continue}if(r==="}"){e.push({type:"CLOSE",index:t,value:n[t++]});continue}if(r===":"){for(var o="",i=t+1;i<n.length;){var a=n.charCodeAt(i);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=n[i++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:o}),t=i;continue}if(r==="("){var u=1,c="",i=t+1;if(n[i]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(i));for(;i<n.length;){if(n[i]==="\\"){c+=n[i++]+n[i++];continue}if(n[i]===")"){if(u--,u===0){i++;break}}else if(n[i]==="("&&(u++,n[i+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(i));c+=n[i++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(t));if(!c)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:c}),t=i;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}s(Pu,"lexer");function $r(n,e){e===void 0&&(e={});for(var t=Pu(n),r=e.prefixes,o=r===void 0?"./":r,i="[^".concat(Eu(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=s(function(E){if(c<t.length&&t[c].type===E)return t[c++].value},"tryConsume"),p=s(function(E){var M=d(E);if(M!==void 0)return M;var G=t[c],V=G.type,v=G.index;throw new TypeError("Unexpected ".concat(V," at ").concat(v,", expected ").concat(E))},"mustConsume"),h=s(function(){for(var E="",M;M=d("CHAR")||d("ESCAPED_CHAR");)E+=M;return E},"consumeText");c<t.length;){var y=d("CHAR"),O=d("NAME"),P=d("PATTERN");if(O||P){var C=y||"";o.indexOf(C)===-1&&(l+=C,C=""),l&&(a.push(l),l=""),a.push({name:O||u++,prefix:C,suffix:"",pattern:P||i,modifier:d("MODIFIER")||""});continue}var H=y||d("ESCAPED_CHAR");if(H){l+=H;continue}l&&(a.push(l),l="");var _=d("OPEN");if(_){var C=h(),j=d("NAME")||"",q=d("PATTERN")||"",$=h();p("CLOSE"),a.push({name:j||(q?u++:""),pattern:j&&!q?i:q,prefix:C,suffix:$,modifier:d("MODIFIER")||""});continue}p("END")}return a}s($r,"parse");function ys(n,e){return Iu($r(n,e),e)}s(ys,"compile");function Iu(n,e){e===void 0&&(e={});var t=xu(e),r=e.encode,o=r===void 0?function(c){return c}:r,i=e.validate,a=i===void 0?!0:i,u=n.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var h=c?c[p.name]:void 0,y=p.modifier==="?"||p.modifier==="*",O=p.modifier==="*"||p.modifier==="+";if(Array.isArray(h)){if(!O)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(h.length===0){if(y)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var P=0;P<h.length;P++){var C=o(h[P],p);if(a&&!u[d].test(C))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(C,'"'));l+=p.prefix+C+p.suffix}continue}if(typeof h=="string"||typeof h=="number"){var C=o(String(h),p);if(a&&!u[d].test(C))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(C,'"'));l+=p.prefix+C+p.suffix;continue}if(!y){var H=O?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(H))}}return l}}s(Iu,"tokensToFunction");function Eu(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(Eu,"escapeString");function xu(n){return n&&n.sensitive?"":"i"}s(xu,"flags");var Ps=Ve(We());var Tu=(0,Ps.debug)("zuplo:runtime"),zr=new TextEncoder,bs={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},vu=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],ut=class{static{s(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:o,region:i,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=r,this.service=o,this.region=i,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,t){let r=new Br(Object.assign({url:e},t,this,t&&t.aws)),o=Object.assign({},t,await r.sign());return delete o.aws,{url:o.url.toString(),request:o}}async fetch(e,t){Tu("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:i}=await this.sign(e,t),a=F.fetch(o,i);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new m("An unknown error occurred, ensure retries is not negative")}},Br=class{static{s(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:r,body:o,accessKeyId:i,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:h,appendSessionToken:y,allHeaders:O,singleEncode:P}){if(t==null)throw new TypeError("url is a required option");if(i==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=i,this.secretAccessKey=a,this.sessionToken=u;let C,H;(!c||!l)&&([C,H]=Cu(this.url,this.headers)),this.service=c||C||"",this.region=l||H||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=h,this.appendSessionToken=y||this.service==="iotdevicegateway",this.headers.delete("Host");let _=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),_.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&_.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(q=>O||!vu.includes(q)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(q=>q+":"+(q==="host"?this.url.host:(this.headers.get(q)||"").replace(/\s+/g," "))).join(`
|
|
47
|
-
`),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!
|
|
43
|
+
`,pad:c,indent:c+d}:p={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let f=s(y=>{if(u.inlineCharacterLimit===void 0)return y;let O=y.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return O.length<=u.inlineCharacterLimit?O:y.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
|
|
44
|
+
`).replace(new RegExp(p.pad,"g"),c).replace(new RegExp(p.indent,"g"),c+d)},"expandWhiteSpace");if(o.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||Hi(a))return String(a);if(a instanceof Date)return`new Date('${a.toISOString()}')`;if(l>r)return"...";if(Array.isArray(a)){if(a.length===0)return"[]";o.push(a);let y="["+p.newline+a.map((O,P)=>{let v=a.length-1===P?p.newline:","+p.newlineOrSpace,N=i(O,u,c+d,l+1);return u.transform&&(N=u.transform(a,P,N)),p.indent+N+v}).join("")+p.pad+"]";return o.pop(),f(y)}if(tt(a)){let y=Ui(a);if(u.filter&&(y=y.filter(P=>u.filter?.(a,P))),y.length===0)return"{}";o.push(a);let O="{"+p.newline+y.map((P,v)=>{let N=y.length-1===v?p.newline:","+p.newlineOrSpace,k=typeof P=="symbol",j=!k&&/^[a-z$_][$\w]*$/i.test(P),q=k||j?P:i(P,u,"",l+1),$=i(a[P],u,c+d,l+1);return u.transform&&($=u.transform(a,P,$)),p.indent+String(q)+": "+$+N}).join("")+p.pad+"}";return o.pop(),f(O)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,y=>y===`
|
|
45
|
+
`?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}s(dn,"stringifyObject");function Be(n){return n.map(e=>Pe(e))}s(Be,"makeErrorsSerializable");function lt(n){if(n.length===0)return"<no data provided to log>";let e=n[0];return typeof e=="string"?e:e instanceof Error?e.message:He(Pe(e))}s(lt,"extractBestMessage");function rs(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(Dt(t))if(t.stack)e.push(t.stack);else{let o=dn(Pe(t));e.push(o)}else if(typeof t=="object"){let o=dn(t);e.push(o)}else{let o=vo(t);e.push(o)}}),e.join(`
|
|
46
|
+
`)}s(rs,"messagesToMultilineText");function He(n){return typeof n=="string"?n:JSON.stringify(n)}s(He,"stringifyNonString");function vo(n){return typeof n=="string"?n:n===null?"null":typeof n>"u"?"undefined":typeof n=="number"||typeof n=="boolean"||typeof n=="bigint"||typeof n=="symbol"?n.toString():typeof n=="function"?`[function ${n.name}]`:typeof n=="object"&&Array.isArray(n)?`[array ${n.length}]`:n instanceof Error?`${n.name??"Error"}: ${n.message??"unknown"}`:typeof n=="object"?po(n):"unknown"}s(vo,"stringifyNonStringToText");import{importPKCS8 as au,SignJWT as uu}from"jose";async function fe(n,e,t){for(let o=0;o<=n.retries;o++){let r=F.fetch(e,t);if(o===n.retries)return r;let i=await r;if(i.status<500&&i.status!==429)return i;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:i.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,o)))}throw new m("An unknown error occurred, ensure retries is not negative")}s(fe,"fetchRetry");async function _e({serviceAccount:n,audience:e,expirationTime:t="1h",payload:o={}}){let{clientEmail:r,privateKeyId:i,privateKey:a}=n;return await new uu(o).setProtectedHeader({alg:"RS256",kid:i}).setIssuer(r).setSubject(r).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}s(_e,"getTokenFromGcpServiceAccount");async function is(n,e,t){if(!n.startsWith("projects/"))throw new m(`The provided audience is invalid: ${n}. It must start with 'projects/'.`);return So("https://sts.googleapis.com/v1/token",{audience:`//iam.googleapis.com/${n}`,grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token_type:"urn:ietf:params:oauth:token-type:jwt",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,scope:"https://www.googleapis.com/auth/cloud-platform"},t)}s(is,"exchangeIDTokenForGcpWorkloadToken");async function ss({serviceAccountEmailOrIdentifier:n,audience:e,accessToken:t},o){let r={audience:e,includeEmail:!0};return us(`https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${encodeURIComponent(n)}:generateIdToken`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},redirect:"follow",body:JSON.stringify(r)},o)}s(ss,"generateServiceAccountIDToken");async function as(n,e,t){return So(n,{token:e,returnSecureToken:!0},t)}s(as,"exchangeFirebaseJwtForIdToken");async function pn(n,e,t){return So(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}s(pn,"exchangeGgpJwtForIdToken");async function So(n,e,t){let o={method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)};return us(n,o,t)}s(So,"fetchTokenFromBody");async function us(n,e,t){let o=await fe(t,n,e);if(o.status!==200){let i;try{let a=await o.text(),u=JSON.parse(a);i={cause:u.error_description??u.error??u}}catch{}throw new L({message:"Could not get token from Google Identity",extensionMembers:i})}return await o.json()}s(us,"fetchToken");var xe=class n{static{s(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),o=await au(t.private_key.trim(),"RS256");return new n({serviceAccount:t,privateKey:o})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};async function le(n){if(n.level==="error"&&console.error(n.messages),!h.instance.remoteLogURL||!h.instance.loggingId||!h.instance.remoteLogToken){console.warn("Remote logger is not configured. Skipping log entry.");return}try{let e={logOwner:"user",logSource:"runtime",rayId:null,requestId:`global-${crypto.randomUUID()}`,timestamp:new Date,buildId:h.instance.build.BUILD_ID,loggingId:h.instance.loggingId,...n,vectorClock:0};await cs({loggingUrl:h.instance.remoteLogURL,loggingId:h.instance.loggingId,loggingToken:h.instance.remoteLogToken},[e])}catch(e){console.error(e)}}s(le,"sendRemoteGlobalLog");async function cs({loggingUrl:n,loggingId:e,loggingToken:t},o){try{await F.fetch(`${n}/publish/${e}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:o.map(r=>({...r,messages:Be(r.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${t}`,"user-agent":h.instance.systemUserAgent,"zp-dn":h.instance.deploymentName??"unknown"}})}catch(r){console.error(r)}}s(cs,"sendRemoteLogs");var cu=s(({url:n,remoteLogToken:e,loggingId:t,sendOnlyErrors:o})=>async r=>{let i;o===!0?i=r.filter(a=>a.level==="error"):i=r,i.length!==0&&await cs({loggingUrl:n,loggingId:t,loggingToken:e},i)},"dispatchFunction"),mn,gn=class{static{s(this,"RemoteLogTransport")}constructor(e){mn||(mn=new X("remote-log-transport",1,cu(e)))}log(e,t){mn.enqueue(e),t.waitUntil(mn.waitUntilFlushed())}};var Co=class extends ge{constructor(t){super();this.options=t}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Ut(this.options)}},lu="https://logging.googleapis.com/v2/entries:write?alt=json",Oo={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Ut=class{static{s(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#r=h.instance.loggingEnvironmentType,this.#i=h.instance.loggingEnvironmentStage,this.#o=h.instance.deploymentName,g("logging.google-cloud")}#e;#t;#n;#o;#r;#i;async init(){this.#t=await xe.init(this.#e)}log(e,t){if(!this.#t)throw new J("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let o={allMessages:Be(e.messages)},r=this.#t.projectId??"zuplo-production",i={logName:this.#n,resource:{type:"global"},severity:Oo[e.level],timestamp:e.timestamp,trace:`projects/${r}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#o,environmentType:this.#r,environmentStage:this.#i}};e.rayId&&(i.labels.rayId=e.rayId);let a=lt(o.allMessages);i.jsonPayload={...o,message:a},this.batcher.enqueue(i),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await xe.init(this.#e));let t=await _e({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"});try{let o=await F.fetch(lu,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});if(!o.ok){let r="";try{r=await o.text()}catch{}await le({level:"error",messages:[`Failed to send logs to Google: ${o.status} - ${o.statusText}`,r]})}}catch{await le({level:"error",messages:["Failed to connect to Google logging service. Check that the URL is correct."]})}};batcher=new X("google-log-transport",1,this.dispatchFunction)};var fn="gcp";function hn(n){let e={allMessages:Be(n.messages)},t="zuplo-production",o=lt(e.allMessages),r={logName:`projects/${t}/logs/runtime-user`,message:o,severity:Oo[n.level],timestamp:n.timestamp,"logging.googleapis.com/labels":{buildId:n.buildId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${n.requestId}`,allMessages:e.allMessages};return n.rayId&&(r["logging.googleapis.com/labels"].rayId=n.rayId),r}s(hn,"gcpLogFormat");var Zt=class{static{s(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===fn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[hn(e)])}else this.#e.log(JSON.stringify(e))}};var _o=class extends ge{constructor(t){super();this.options=t}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new Ft(this.options)}},Ao="__ddtags",ko="__ddattr",Lo=s(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),du=s(n=>{let e=Object.keys(n),t=[];return e.forEach(o=>{let r=n[o];r==null?t.push(Lo(o)):t.push(`${Lo(o)}:${Lo(r.toString())}`)}),t.join(",")},"formatTags"),Ft=class{static{s(this,"DataDogTransport")}constructor(e){g("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#o=h.instance.loggingEnvironmentType,this.#r=h.instance.loggingEnvironmentStage,this.#n=h.instance.deploymentName}#e;#t;#n;#o;#r;log(e,t){let o={},r=t.custom[Ao];r&&typeof r=="object"&&Object.assign(o,r);let i=[...e.messages],a=e.messages.findIndex(y=>y[Ao]!==void 0);a>-1&&(Object.assign(o,i[a][Ao]),i.splice(a,1));let u={},c=t.custom[ko];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(y=>y[ko]!==void 0);l>-1&&(Object.assign(u,i[l][ko]),i.splice(l,1));let d=Be(i),f={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:lt(d),service:e.loggingId,ddtags:du(o),environment:this.#n,environment_type:this.#o,environment_stage:this.#r};Object.assign(f,u),this.batcher.enqueue(f),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length!==0)try{let t=await F.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!t.ok){let o="";try{o=await t.text()}catch{}await le({level:"error",messages:[`Failed to send logs to DataDog: ${t.status} - ${t.statusText}`,o]})}}catch{await le({level:"error",messages:["Failed to connect to DataDog logging service. Check that the URL is correct."]})}};batcher=new X("data-dog-transport",10,this.dispatchFunction)};var $t=class{static{s(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===fn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[hn(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId,vectorClock:e.vectorClock}])}};var pu={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},ls=s((n,e)=>t=>{let o={};return o.deploymentName=n,o.labels={requestId:t.requestId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},o.rayId=t.rayId??"",o.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},o.atomicCounter=t.vectorClock,{timestamp:t.timestamp,observerdTimestamp:t.timestamp,traceId:t.requestId,severityText:t.level,severityNumber:pu[t.level],body:t.messages,attributes:o}},"unifiedFormatter");var mu=s(({url:n,remoteLogToken:e,deploymentName:t,build:o})=>async r=>{if(r.length===0)return;let i=ls(t,o);try{await F.fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:r.map(i)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":h.instance.systemUserAgent,"zp-dn":h.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),yn,bn=class{static{s(this,"UnifiedLogTransport")}constructor(e){yn||(yn=new X("unified-log-transport",1,mu(e)))}async log(e,t){yn.enqueue(e),t.waitUntil(yn.waitUntilFlushed())}};var No=(0,ds.debug)("zuplo:logging"),wn=class n{static{s(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(h.instance,e),o=await n.setupUserCoreLogger(h.instance,e);return new n({systemCoreLogger:t,userCoreLogger:o})}static async setupSystemCoreLogger(e,t){let{build:o}=e;No("Gateway.setupSystemCoreLogger");let r=[],i=t.getService(Qt);return i?r.push(new $t(i.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new Zt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new bn({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(r.map(async a=>{a.init&&await a.init()})),new qt(e.systemLogLevel,"system",e.loggingId,o.BUILD_ID,r)}static async setupUserCoreLogger(e,t){No("Gateway.setupUserCoreLogger");let o=[],{runtime:r,build:i}=e,a=t.getService(Qt);if(a&&a.captureUserLogs===!0?o.push(new $t(a.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new Zt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&o.push(new gn({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:!e.isWorkingCopy})),r.GCP_USER_LOG_NAME&&r.GCP_USER_LOG_SVC_ACCT_JSON&&(g("logging.google.legacy-initialization"),o.push(new Ut({serviceAccountJson:r.GCP_USER_LOG_SVC_ACCT_JSON,logName:r.GCP_USER_LOG_NAME}))),r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){g("logging.datadog.legacy-initialization");let u=r.ZUPLO_USER_LOGGER_DATA_DOG_URL;o.push(new Ft({apiKey:r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return qe.forEach(u=>{u instanceof ge&&o.push(u.getTransport())}),await Promise.all(o.map(async u=>{u.init&&await u.init()})),new qt(e.userLogLevel,"user",e.loggingId,i.BUILD_ID,o)}createRequestLoggers(e,t,o,r,i){No("Gateway.createRequestLoggers");let a=new ln(o,r,i),u=new Ht(e,t,this.systemCoreLogger,a);return{userRequestLogger:new Ht(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var rt=class{static{s(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};var Do=class{static{s(this,"RouterEntry")}constructor(e,t,o,r){this.fullPath=e,this.urlPattern=t,this.config=o,this.executableHandler=r}fullPath;urlPattern;config;executableHandler},jt=class{static{s(this,"LookupResult")}constructor(e,t,o){this.routeConfiguration=e,this.params=o??{},this.executableHandler=t}executableHandler;routeConfiguration;params},Mo=class extends Error{static{s(this,"RouterError")}constructor(e,t){super(e,t)}},zt=class{static{s(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof rt||e instanceof ce))throw new J("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let o=this.versions.find(i=>i.name===e.version)?.pathPrefix,r;"pathPattern"in e&&e.pathPattern?r=`${o??""}${e.pathPattern}`:r=`${o??""}${e.path}`;try{let i=new URLPattern({pathname:r}),a=new Do(r,i,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(i){throw new Mo(`addRoute-error: Invalid path '${r}'. '${i.message}'`,{cause:i})}}lookup(e,t){if(typeof e>"u")throw new m(`Invalid request - Method was undefined. Path: '${t}'`);let o=this.routeEntries.filter(r=>r.config.methods.includes(e));if(o.length!==0)for(let r=0;r<o.length;r++){let i=o[r],u=i.urlPattern.exec({pathname:t});if(u!==null)return new jt(i.config,i.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let t=[];for(let o=0;o<this.routeEntries.length;o++){let r=this.routeEntries[o],a=r.urlPattern.exec({pathname:e});if(a!==null){let u=new jt(r.config,r.executableHandler,a.pathname.groups);t.push(u)}}return t}};var qo;function ps(n){qo=n}s(ps,"setGlobalZuploEventContext");function Rn(){if(qo===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return qo}s(Rn,"getGlobalZuploEventContext");function ms({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[o]of n){let r=o.substring(0,3);xi.includes(r.toLowerCase())&&!Ti.includes(o.toLowerCase())&&t.delete(o)}t.delete(di)}else Ei.forEach(o=>{t.delete(o)});return t}s(ms,"normalizeIncomingRequestHeaders");var Ne=(0,gs.debug)("zuplo:runtime"),fu=s(n=>{let e=n.findIndex(t=>t.name===Nt.name);return e>-1?[...n.splice(e),Nt]:[...n,Nt]},"setupSystemNoVersion"),he=class n{constructor(e,t,o,r){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=r;Ne("Gateway.constructor"),Le,this.#n=this.setupRoutes(),this.#r=this.setupErrorHandler(),this.#t=o}static{s(this,"Gateway")}static#e;static async initialize(e,t,o,r){if(Ne("Gateway.initialize"),!n.#e){let i=await wn.init(o),a=e(),u={...a,corsPolicies:ji(a.corsPolicies)},c=new n(u,t,i,r);n.#e=c}if(!n.#e)throw new J("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){Ne("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new J("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#o=[cn,an,be];#r;setupRoutes=()=>{Ne("Gateway.setupRoutes");let e=this.routeData,t=fu(e.versions),o=new zt(t);if(e.routes.length===0)return lo(o,this),bo(o,this),ho(o,this),zi(o,this),o;let{enabled:r}=this.runtimeSettings.developerPortal;r&&(ts(o,this),es(o,this)),lo(o,this),bo(o,this),ho(o,this);for(let i of qe)i instanceof Me&&i.registerRoutes(o,this);return e.routes.forEach(i=>{let a;if(typeof i.handler?.module=="object"&&(a=i.handler?.module[i.handler.export]),typeof a!="function")throw new m(`Invalid state - No handler on route for path '${i.path}'`);let u=new me({processors:this.#o,handler:a,gateway:this}),c=new rt(i);o.addRoute(c,u.execute)}),Bi(o,this),o};setupErrorHandler=()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new m("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=s((t,o,r)=>this.#i(t,o,r),"errorHandler");return e};errorHandler(e,t,o){try{return this.#r(e,t,o)}catch(r){return Ne("An error occurred in the user's errorHandler",r),this.#i(e,t,r)}}#i(e,t,o){Ne("Gateway.internalErrorResponse");let r={};if(h.instance.isLocalDevelopment||h.instance.isWorkingCopy){if(o instanceof L&&o.extensionMembers)r=o.extensionMembers;else if(o.cause){let i=Pe(o.cause);"stack"in i&&(i.stack=os(i.stack)),r={cause:i}}}return x.internalServerError(e,t,{detail:o.message,...r})}async handleRequest(e,t,o){let{requestId:r,rayId:i}=t;ps(o);let a=ms({headers:e.headers,removeAllVendorHeadersExceptListed:h.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(Xe,r);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let j=new Headers(u.headers);j.set(Fn,"true"),u=new Request(u,{headers:j,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(r,i,o,c,u),p=new URL(u.url),f=p.pathname,y=this.#n.lookup(u.method,f);if(!y)throw new J(`Invalid state - no route match - should have been picked up by the not found handler, path: '${f}'`);let O=new Pn(e.headers),P=new te(u,{params:y.params}),v=new In({logger:l,route:y.routeConfiguration,requestId:r,event:o,custom:c,incomingRequestProperties:O}),N=y.routeConfiguration.raw();gu.getActiveSpan()?.setAttributes({"http.route":v.route.path??v.route.pathPattern,"cloud.region":v.incomingRequestProperties.colo,[Le.RoutePathPattern]:v.route.pathPattern,[Le.RouteOperationId]:N.operationId,[Le.RouteTrace]:N["x-zuplo-trace"],[Le.RouteSystem]:ut(p)?!0:void 0});let k=ye.initialize(v,P);if(y.routeConfiguration===yo&&kt.value?.notFoundHandler!==void 0){let j=this.#n.lookupByPathOnly(f);k.pathOnlyMatches=j.map(q=>q.routeConfiguration).filter(q=>q instanceof rt)}try{if(Q.addLogger(v,d),h.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!ut(p):!p.pathname.startsWith("/__zuplo")){let E=await _i(P,v);if(E instanceof Response)return E;{let H=ye.getContextExtensions(v);P=E,H.latestRequest=P}}ut(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:y.routeConfiguration.path});let j=y.executableHandler;hu(j,y,u),Ne("Gateway.handleRequest - call user handler");let q=await j(P,v);if(Ne("Gateway.handleRequest - user handler"),!(q instanceof Response))throw new L(`Invalid Response type from the request handler: ${typeof q}`);if(q.bodyUsed)throw new L("The response object has already been used. Return a new response instead.");let $;if(q.headers.get(Xe)===null&&!q.webSocket){let E=new Headers(q.headers);E.set(Xe,r),$=new Response(q.body,{status:q.status,statusText:q.statusText,headers:E,cf:q.cf})}else $=q;return $}catch(j){return Ne("Gateway - error executing handler",j),j instanceof L?(l.error(j),d.warn(j)):d.error(j),await this.#i(P,v,j)}}};function hu(n,e,t){if(Ne("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new m(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new m(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}s(hu,"checkHandler");var fs=s(async(n,e,t)=>{let o=he.instance.routeData.policies,r=Mt([n],o);if(r.length===0)throw new L(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return r[0].handler(e,t)},"invokeInboundPolicy");var Pn=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Vn);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Wn)??void 0}get city(){return this.#e.get($n)??this.#e.get(yi)??void 0}get continent(){return this.#e.get(jn)??this.#e.get(bi)??void 0}get country(){return this.#e.get(zn)??this.#e.get(wi)??void 0}get latitude(){return this.#e.get(Gn)??this.#e.get(Pi)??void 0}get longitude(){return this.#e.get(Bn)??this.#e.get(Ri)??void 0}get colo(){return this.#e.get(Kn)??void 0}get postalCode(){return this.#e.get(fi)??this.#e.get(Jn)??void 0}get metroCode(){return this.#e.get(gi)??this.#e.get(Qn)??void 0}get region(){return this.#e.get(pi)??this.#e.get(Xn)??void 0}get regionCode(){return this.#e.get(mi)??this.#e.get(Yn)??void 0}get timezone(){return this.#e.get(hi)??this.#e.get(eo)??void 0}toJSON(){return{asn:this.asn,asOrganization:this.asOrganization,city:this.city,continent:this.continent,country:this.country,latitude:this.latitude,longitude:this.longitude,colo:this.colo,postalCode:this.postalCode,metroCode:this.metroCode,region:this.region,regionCode:this.regionCode,timezone:this.timezone}}},Lt=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},_t=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},ye=class n{static{s(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let o=new n(t);return n.#e.set(e,o),o}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=n.#e.get(e);if(!t)throw new L(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,t,o)=>{for(let r of this.#t)await r(e,t,o)};onResponseSending=async(e,t,o)=>{let r=e;for(let i of this.#n)r=await i(e,t,o);return r}},In=class extends EventTarget{static{s(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:o,event:r,custom:i,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=o,this.custom=i,this.incomingRequestProperties=a,this.#e=r,this.invokeInboundPolicy=(u,c)=>fs(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{ye.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{ye.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,o){let r=s(i=>{try{typeof t=="function"?t(i):t.handleEvent(i)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,r,o)}};var se=class n{static{s(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,t){n.set(e,this.#t,t)}get(e){return n.get(e,this.#t)}static set(e,t,o){n.#e||(n.#e=new WeakMap);let r=n.#e.get(e);r||(r=new Map),r.set(t,o),n.#e.set(e,r)}static get(e,t){return n.#e||(n.#e=new WeakMap),n.#e.get(e)?.get(t)}};import{AsyncLocalStorage as yu}from"node:async_hooks";var hs={request:new yu};var bu="Error initializing gateway. Check your configuration for errors or contact support.",wu="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",Ho=class{constructor(e,t,o,r,i,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=o;this.serviceProvider=r;this.schemaValidations=i;this.runtimeInit=a}static{s(this,"Handler")}requestHandler=async(e,t,o)=>{let r=e.headers.get(Xe)??e.headers.get(li)??crypto.randomUUID(),i=e.headers.get(Ye),a={requestId:r,rayId:i};return hs.request.run(a,async()=>{h.initialize({build:this.buildEnvironment,runtime:t});try{await Mi(this.runtimeInit)}catch(c){this.handleError(c,wu,e)}return Ci(s(async(c,l)=>{let d;try{d=await he.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,bu,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,o)})};handleError(e,t,o){console.error("Error initializing gateway.",e),e instanceof m&&(t=e.message);let r={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:t,instance:o.url,trace:{timestamp:Date.now(),rayId:o.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:h.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(r,null,2),{status:500,headers:{"content-type":"application/json"}})}};var Ts=Je(Qe());function Ru(n){for(var e=[],t=0;t<n.length;){var o=n[t];if(o==="*"||o==="+"||o==="?"){e.push({type:"MODIFIER",index:t,value:n[t++]});continue}if(o==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:n[t++]});continue}if(o==="{"){e.push({type:"OPEN",index:t,value:n[t++]});continue}if(o==="}"){e.push({type:"CLOSE",index:t,value:n[t++]});continue}if(o===":"){for(var r="",i=t+1;i<n.length;){var a=n.charCodeAt(i);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){r+=n[i++];continue}break}if(!r)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:r}),t=i;continue}if(o==="("){var u=1,c="",i=t+1;if(n[i]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(i));for(;i<n.length;){if(n[i]==="\\"){c+=n[i++]+n[i++];continue}if(n[i]===")"){if(u--,u===0){i++;break}}else if(n[i]==="("&&(u++,n[i+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(i));c+=n[i++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(t));if(!c)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:c}),t=i;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}s(Ru,"lexer");function Uo(n,e){e===void 0&&(e={});for(var t=Ru(n),o=e.prefixes,r=o===void 0?"./":o,i="[^".concat(Iu(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=s(function(E){if(c<t.length&&t[c].type===E)return t[c++].value},"tryConsume"),p=s(function(E){var H=d(E);if(H!==void 0)return H;var G=t[c],V=G.type,S=G.index;throw new TypeError("Unexpected ".concat(V," at ").concat(S,", expected ").concat(E))},"mustConsume"),f=s(function(){for(var E="",H;H=d("CHAR")||d("ESCAPED_CHAR");)E+=H;return E},"consumeText");c<t.length;){var y=d("CHAR"),O=d("NAME"),P=d("PATTERN");if(O||P){var v=y||"";r.indexOf(v)===-1&&(l+=v,v=""),l&&(a.push(l),l=""),a.push({name:O||u++,prefix:v,suffix:"",pattern:P||i,modifier:d("MODIFIER")||""});continue}var N=y||d("ESCAPED_CHAR");if(N){l+=N;continue}l&&(a.push(l),l="");var k=d("OPEN");if(k){var v=f(),j=d("NAME")||"",q=d("PATTERN")||"",$=f();p("CLOSE"),a.push({name:j||(q?u++:""),pattern:j&&!q?i:q,prefix:v,suffix:$,modifier:d("MODIFIER")||""});continue}p("END")}return a}s(Uo,"parse");function ys(n,e){return Pu(Uo(n,e),e)}s(ys,"compile");function Pu(n,e){e===void 0&&(e={});var t=Eu(e),o=e.encode,r=o===void 0?function(c){return c}:o,i=e.validate,a=i===void 0?!0:i,u=n.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var f=c?c[p.name]:void 0,y=p.modifier==="?"||p.modifier==="*",O=p.modifier==="*"||p.modifier==="+";if(Array.isArray(f)){if(!O)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(f.length===0){if(y)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var P=0;P<f.length;P++){var v=r(f[P],p);if(a&&!u[d].test(v))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(v,'"'));l+=p.prefix+v+p.suffix}continue}if(typeof f=="string"||typeof f=="number"){var v=r(String(f),p);if(a&&!u[d].test(v))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(v,'"'));l+=p.prefix+v+p.suffix;continue}if(!y){var N=O?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(N))}}return l}}s(Pu,"tokensToFunction");function Iu(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(Iu,"escapeString");function Eu(n){return n&&n.sensitive?"":"i"}s(Eu,"flags");var Ps=Je(Qe());var xu=(0,Ps.debug)("zuplo:runtime"),Fo=new TextEncoder,bs={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},Tu=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],dt=class{static{s(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:o,service:r,region:i,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=o,this.service=r,this.region=i,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,t){let o=new $o(Object.assign({url:e},t,this,t&&t.aws)),r=Object.assign({},t,await o.sign());return delete r.aws,{url:r.url.toString(),request:r}}async fetch(e,t){xu("AWS fetch",e);for(let o=0;o<=this.retries;o++){let{url:r,request:i}=await this.sign(e,t),a=F.fetch(r,i);if(o===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,o)))}throw new m("An unknown error occurred, ensure retries is not negative")}},$o=class{static{s(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:o,body:r,accessKeyId:i,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:f,appendSessionToken:y,allHeaders:O,singleEncode:P}){if(t==null)throw new TypeError("url is a required option");if(i==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(r?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(o||{}),this.body=r,this.accessKeyId=i,this.secretAccessKey=a,this.sessionToken=u;let v,N;(!c||!l)&&([v,N]=vu(this.url,this.headers)),this.service=c||v||"",this.region=l||N||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=f,this.appendSessionToken=y||this.service==="iotdevicegateway",this.headers.delete("Host");let k=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),k.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&k.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(q=>O||!Tu.includes(q)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(q=>q+":"+(q==="host"?this.url.host:(this.headers.get(q)||"").replace(/\s+/g," "))).join(`
|
|
47
|
+
`),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!k.has("X-Amz-Expires")&&k.set("X-Amz-Expires","86400"),k.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),k.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),k.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");P||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=Rs(this.encodedPath);let j=new Set;this.encodedSearch=[...this.url.searchParams].filter(([q])=>{if(!q)return!1;if(this.service==="s3"){if(j.has(q))return!1;j.add(q)}return!0}).map(q=>q.map($=>Rs(encodeURIComponent($)))).sort(([q,$],[E,H])=>q<E?-1:q>E?1:$<H?-1:$>H?1:0).map(q=>q.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),t=[this.secretAccessKey,e,this.region,this.service].join(),o=this.cache.get(t);if(!o){let r=await Bt("AWS4"+this.secretAccessKey,e),i=await Bt(r,this.region),a=await Bt(i,this.service);o=await Bt(a,"aws4_request"),this.cache.set(t,o)}return Zo(await Bt(o,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Zo(await ws(await this.canonicalString()))].join(`
|
|
48
48
|
`)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
|
|
49
49
|
`,this.signedHeaders,await this.hexBodyHash()].join(`
|
|
50
|
-
`)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new k("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=jr(await ws(this.body||""))}return e}};async function $t(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?zr.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,zr.encode(e))}s($t,"hmac");async function ws(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?zr.encode(n):n)}s(ws,"hash");function jr(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}s(jr,"buf2hex");function Rs(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}s(Rs,"encodeRfc3986");function Cu(n,e){let{hostname:t,pathname:r}=n,o=t.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[i,a]=(o||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",i="s3";else if(i==="iot")t.startsWith("iot.")?i="execute-api":t.startsWith("data.jobs.iot.")?i="iot-jobs-data":i=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(i==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?i="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(i="autoscaling-plans")}else a==null&&i.startsWith("s3-")?(a=i.slice(3).replace(/^fips-|^external-1/,""),i="s3"):i.endsWith("-fips")?i=i.slice(0,-5):a&&/-\d$/.test(i)&&!/-\d$/.test(a)&&([i,a]=[a,i]);return i in bs?[bs[i],a]:[i,a]}s(Cu,"guessServiceRegion");function Su(n){return n>64&&n<91?n-65:n>96&&n<123?n-71:n>47&&n<58?n+4:n===43?62:n===47?63:0}s(Su,"b64ToUint6");function Is(n,e){let t=n.replace(/[^A-Za-z0-9+/]/g,""),r=t.length,o=e?Math.ceil((r*3+1>>2)/e)*e:r*3+1>>2,i=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=Su(t.charCodeAt(d))<<6*(3-u),u===3||r-d===1){for(a=0;a<3&&l<o;)i[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return i}s(Is,"base64Decode");function In(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}s(In,"uint6ToB64");function Es(n){let e=2,t="",r=n.length,o=0;for(let i=0;i<r;i++)e=i%3,o|=n[i]<<(16>>>e&24),(e===2||n.length-i===1)&&(t+=String.fromCodePoint(In(o>>>18&63),In(o>>>12&63),In(o>>>6&63),In(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}s(Es,"base64Encode");function ct(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}s(ct,"numberToString");function Ou(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=ct(Math.floor(t/60)),i=ct(t%60);return`${r}${o}${i}`}s(Ou,"getCLFOffset");function Gr(n=new Date){if(!(n instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],t=ct(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),i=ct(n.getHours()),a=ct(n.getMinutes()),u=ct(n.getSeconds()),c=Ou(n);return`${t}/${r}/${o}:${i}:${a}:${u} ${c}`}s(Gr,"toCLFDate");var xs=(0,Ts.debug)("zuplo:runtime"),Au="X-Amzn-Trace-Id",ku="x-amzn-errortype",vs=[],Lu=s(async(n,e,t)=>{let r=t;for await(let o of vs)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),Te=class extends k{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(Au)??void 0,this.errorType=t.get(ku)??void 0}},_u={addSendingAwsLambdaEventHook:n=>{vs.push(n)}};async function Nu(n,e){g("handler.aws-lambda");let{accessKeyId:t,secretAccessKey:r,region:o,functionName:i,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!t)throw new m("awsAccessKeyId is not set in the handler options");if(!r)throw new m("secretAccessKey is not set in the handler options");if(!o)throw new m("region is not set in the handler options");if(!i)throw new m("functionName is not set in the handler options");let l=new ut({accessKeyId:t,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(xs(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,h]=await Uu(n,{binaryMediaTypes:c}),{options:y}=e.route.handler,O;y&&typeof y=="object"&&"payloadFormatVersion"in y&&y.payloadFormatVersion==="2.0"?O=Hu(n,e):O=await Mu(n,e,{useAwsResourcePathStyle:u}),xs("Calling onSendingAwsLambdaEvent hook");let P=await Lu(n,e,O);P.body=p,P.isBase64Encoded=h;let C=await l.fetch(d,{body:JSON.stringify(P)});try{return Du(C)}catch(H){if(H instanceof Te){let _=y&&typeof y=="object"&&"returnAmazonTraceIdHeader"in y&&y.returnAmazonTraceIdHeader&&H.traceId?{AMZN_TRACE_ID_HEADER:H.traceId}:void 0;return x.internalServerError(n,e,void 0,_)}throw H}}s(Nu,"awsLambdaHandler");async function Du(n){let e;try{e=await n.json()}catch{throw new Te("Lambda response did not contain valid JSON",n.headers)}if(n.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new Te(e.message,n.headers):new Te(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new Te(e.errorMessage,n.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:n.status,headers:{"content-type":"application/json"}});let t=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new Te(`Response headers must be an object. Received ${typeof e.headers}`,n.headers);for(let[o,i]of Object.entries(e.headers))t.set(o,i)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new Te(`Response cookies must be an array. Received ${typeof e.cookies}`,n.headers);t.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new Te(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,n.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new Te("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new Te("Response was set to base64 encoded but body was not a string",n.headers);r=Is(e.body)}else"body"in e&&typeof e.body=="string"?r=e.statusCode===204&&e.body===""?null:e.body:"body"in e&&e.body!==null&&e.body!==void 0?r=JSON.stringify(e.body):r=null;if(r!==null&&"bodyEncoding"in e){if(typeof e.bodyEncoding!="string"||!(e.bodyEncoding==="gzip"||e.bodyEncoding==="deflate"))throw new Te(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,n.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:t,status:e.statusCode})}s(Du,"getResponse");async function Mu(n,e,{useAwsResourcePathStyle:t}){let r={},o={};n.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let i=n.query,a={};for(let[l,d]of Object.entries(i))a[l]=[d];let u=new URL(n.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:n.method,headers:r,multiValueHeaders:o,queryStringParameters:i,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:n.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:n.headers.get("CF-Connecting-IP"),user:null,userAgent:n.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:Gr(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Zu(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}s(Mu,"buildEventVersion1");function Hu(n,e){let t={};n.headers.forEach((i,a)=>{t[a]=i});let r=new URL(n.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:t,queryStringParameters:n.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:r.hostname,domainPrefix:null,http:{method:n.method,path:r.pathname,protocol:"HTTP/1.1",sourceIp:n.headers.get("CF-Connecting-IP"),userAgent:n.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:Gr(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}s(Hu,"buildEventVersion2");async function Uu(n,{binaryMediaTypes:e}){let t,r=!1,o=n.headers.get("content-type");if(n.method==="GET"||n.method==="HEAD")t=null;else if(e&&o&&qu(e,o)){let i=await n.arrayBuffer();t=Es(new Uint8Array(i)),r=!0}else t=await n.clone().text();return[t,r]}s(Uu,"getBodyResult");function qu(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}s(qu,"matchesContentType");function Zu(n,e=!1){if(!e)return n;let t=$r(n),r=ys(n),o={};return t.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),r(o)}s(Zu,"getResourcePath");var Fu=[502,503,504];async function lt(n,e){if(Fu.includes(n.status)){let t=Y.getLogger(e),o=await n.clone().text(),i={};for(let[a,u]of n.headers)i[a]=u;t.warn(`BadGatewayResponse ${n.status}`,{status:n.status,statusText:n.statusText,body:o,headers:i})}}s(lt,"logBadGatewayResponses");var Vr;function Be(n){if(Vr===void 0){let t=f.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),Vr=t}return n.log[Vr]}s(Be,"getHandlerUserLogFunction");async function $u(n,e){g("handler.open-api");let t=f.instance.build.BUILD_ID,{buildAssetsUrl:r}=f.instance,o=e.route.handler.options,{openApiFilePath:i}=o;if(!i)throw new m("Open API Spec Handler must have 'openApiFilePath' specified");let a=ju(i);if(!a.isValid)throw new m(a.error);let u;f.instance.isLocalDevelopment?u=`${r}/${i.substring(1)}`:u=`${r}/${t}${i.substring(1)}`;let c=await F.fetch(u,{method:n.method,body:n.body,headers:n.headers});if(c.status!==200)return x.notFound(n,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return lt(l,e),l}s($u,"openApiSpecHandler");var ju=s(n=>n.startsWith("./")?n.startsWith("./config")?n.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function zu(n,e){g("handler.redirect");let t=e.route.handler.options;if(!t.location)throw new m("Redirect Handler must have 'location' specified");let r=t.status??302;return new Response(null,{status:r,headers:{location:t.location}})}s(zu,"redirectHandler");function Bu(n,e){let t=n.endsWith("/"),r=e.startsWith("/");return t&&r?`${n.substring(0,n.length-1)}${e}`:!t&&!r?`${n}/${e}`:`${n}${e}`}s(Bu,"join");async function Gu(n,e){g("handler.url-forward");let t=Be(e),r=e.route.handler.options,o=r.forwardSearch!==!1;if(!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new m("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(n.url),u=r.__rewriteFunction(n,i),c=Bu(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();t(`URL Forwarding to '${l}'`);let p=await F.fetch(l,{method:n.method,body:n.body,headers:n.headers}),h=Date.now()-d;return t(`URL Forward received response ${p.status} - ${p.statusText} in ${h}ms`),lt(p,e),p}s(Gu,"urlForwardHandler");var Vu=s((n,e)=>{let t=new URL(n),r=new URL(e);for(let[o,i]of r.searchParams.entries())t.searchParams.append(o,i);return t.toString()},"addQuery");async function Wu(n,e){g("handler.url-rewrite");let t=Be(e),r=e.route.handler.options,o=r.forwardSearch!==!1,i=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new m("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(n,a),c=o?Vu(u,n.url):u,l=Date.now();t(`URL Rewriting to '${c}'`);let d=await F.fetch(c.toString(),{method:n.method,body:n.body,headers:n.headers,redirect:i?"follow":"manual"}),p=Date.now()-l;return t(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),lt(d,e),d}s(Wu,"urlRewriteHandler");async function Ku(n,e){g("handler.websocket");let t=e.route.handler.options,r=Be(e);if(!t||!t.rewritePattern)throw new m("WebSocket Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return x.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new m("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,i),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await F.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let d=await c.text(),p=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${d}'`;throw new Error(p)}let l=Date.now()-u;return r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${l}ms`),new Response(null,{status:101,webSocket:c.webSocket})}s(Ku,"webSocketHandler");var Wr=s((n,e)=>n.map((r,o)=>{let i;if(typeof r.module=="object"&&(i=r.module[r.export]),!i||typeof i!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${o+1}, export name: ${r.export}`;throw new m(`${a} - Websocket policy must be a valid function (${u})`)}return i}),"getWebSocketPolicyFunctions"),Cs=s(async(n,e,t,r,o,i)=>{let a=n.data;if(i&&i.length>0){let u=[...i];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,t,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function Ss(n,e,t,r,o){n.addEventListener("close",()=>{e.close()}),n.addEventListener("error",i=>{r.log.error("WebSocket error: ",i),e.send(JSON.stringify(i))}),n.addEventListener("message",i=>{try{let u=s(async c=>{let l=await Cs(c,n,e,t,r,o);l!==void 0&&e.send(l)},"innerPipeline")(i).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}s(Ss,"wireUpListeners");async function Ju(n,e){g("handler.websocket-pipeline");let t=e.route.handler.options,r=Be(e);if(!t||!t.rewritePattern)throw new m("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return x.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new m("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,i),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await F.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let C=await c.text(),H=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${C}'`;throw new Error(H)}let l=new WebSocketPair,[d,p]=Object.values(l),h=Date.now()-u;r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${h}ms`);let y=c.webSocket;y.accept(),p.accept();let O=t.policies&&t.policies.inbound?Wr(t.policies.inbound,"inbound"):[],P=t.policies&&t.policies.outbound?Wr(t.policies.outbound,"outbound"):[];return Ss(p,y,n,e,O),Ss(y,p,n,e,P),new Response(null,{status:101,webSocket:d})}s(Ju,"webSocketPipelineHandler");var Kr=class extends me{constructor(t){super();this.options=t}static{s(this,"DynaTraceLoggingPlugin")}getTransport(){return new Jr(this.options)}},Jr=class{static{s(this,"DynaTraceTransport")}constructor(e){g("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#r=f.instance.loggingEnvironmentType,this.#o=f.instance.loggingEnvironmentStage,this.#n=f.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Ue(Pe(r)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{if(e.length!==0)try{let t=await F.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}});if(!t.ok){let r="";try{r=await t.text()}catch{}await ue({level:"error",messages:[`Failed to send logs to Dynatrace: ${t.status} - ${t.statusText}`,r]})}}catch{await ue({level:"error",messages:["Failed to connect to Dynatrace logging service. Check that the URL is correct."]})}};batcher=new J("dyna-trace-log-transport",10,this.#i)};var Xr=class extends me{constructor(t){super();this.options=t}static{s(this,"LokiLoggingPlugin")}getTransport(){return new Qr(this.options)}},Yr=class{static{s(this,"LokiStream")}constructor(e,t,r,o,i,a){this.level=e,this.environment=t,this.environmentType=r,this.environmentStage=o,this.requestId=a,this.job=i}job;level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function Xu(n,e){return btoa(`${n}:${e}`)}s(Xu,"createBasicDigest");var Qr=class{static{s(this,"LokiTransport")}constructor(e){g("logging.loki"),this.#n=e.url,this.#r=Xu(e.username,e.password),this.#i=f.instance.loggingEnvironmentType,this.#s=f.instance.loggingEnvironmentStage,this.#o=f.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo"}#e;#t;#n;#r;#o;#i;#s;log(e,t){let r=new Yr(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(o=>{let i={stream:r,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:Ue(Pe(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(i)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=e=>{let t={streams:[]};return e.forEach(r=>{let o=t.streams.find(i=>i.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},t.streams.push(o)),o.values.push(this.#e>1?[r.nanoSecondEpoch,r.message,{requestId:r.requestId,rayId:r.rayId,atomicCounter:JSON.stringify(r.atomicCounter)}]:[r.nanoSecondEpoch,r.message])}),t};#u=async e=>{if(e.length===0)return;let t=this.#a(e);try{let r=await F.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}});if(!r.ok){let o="";try{o=await r.text()}catch{}await ue({level:"error",messages:[`Failed to send logs to Loki: ${r.status} - ${r.statusText}`,o]})}}catch{await ue({level:"error",messages:["Failed to connect to Loki logging service. Check that the URL is correct."]})}};batcher=new J("loki-log-transport",10,this.#u)};var eo=class extends me{constructor(t){super();this.options=t}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new to(this.options)}},to=class{static{s(this,"SumoLogicTransport")}constructor(e){g("logging.sumologic"),this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=f.instance.loggingEnvironmentType,this.#r=f.instance.loggingEnvironmentStage,this.#t=f.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Ue(Pe(r)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let t=e.map(o=>JSON.stringify(o)).join(`
|
|
51
|
-
`),
|
|
52
|
-
`),
|
|
50
|
+
`)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new L("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Zo(await ws(this.body||""))}return e}};async function Bt(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?Fo.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,Fo.encode(e))}s(Bt,"hmac");async function ws(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?Fo.encode(n):n)}s(ws,"hash");function Zo(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}s(Zo,"buf2hex");function Rs(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}s(Rs,"encodeRfc3986");function vu(n,e){let{hostname:t,pathname:o}=n,r=t.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[i,a]=(r||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",i="s3";else if(i==="iot")t.startsWith("iot.")?i="execute-api":t.startsWith("data.jobs.iot.")?i="iot-jobs-data":i=o==="/mqtt"?"iotdevicegateway":"iotdata";else if(i==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?i="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(i="autoscaling-plans")}else a==null&&i.startsWith("s3-")?(a=i.slice(3).replace(/^fips-|^external-1/,""),i="s3"):i.endsWith("-fips")?i=i.slice(0,-5):a&&/-\d$/.test(i)&&!/-\d$/.test(a)&&([i,a]=[a,i]);return i in bs?[bs[i],a]:[i,a]}s(vu,"guessServiceRegion");function Su(n){return n>64&&n<91?n-65:n>96&&n<123?n-71:n>47&&n<58?n+4:n===43?62:n===47?63:0}s(Su,"b64ToUint6");function Is(n,e){let t=n.replace(/[^A-Za-z0-9+/]/g,""),o=t.length,r=e?Math.ceil((o*3+1>>2)/e)*e:o*3+1>>2,i=new Uint8Array(r),a,u,c=0,l=0;for(let d=0;d<o;d++)if(u=d&3,c|=Su(t.charCodeAt(d))<<6*(3-u),u===3||o-d===1){for(a=0;a<3&&l<r;)i[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return i}s(Is,"base64Decode");function En(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}s(En,"uint6ToB64");function Es(n){let e=2,t="",o=n.length,r=0;for(let i=0;i<o;i++)e=i%3,r|=n[i]<<(16>>>e&24),(e===2||n.length-i===1)&&(t+=String.fromCodePoint(En(r>>>18&63),En(r>>>12&63),En(r>>>6&63),En(r&63)),r=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}s(Es,"base64Encode");function pt(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}s(pt,"numberToString");function Cu(n){let e=n.getTimezoneOffset(),t=Math.abs(e),o=e>0?"-":"+",r=pt(Math.floor(t/60)),i=pt(t%60);return`${o}${r}${i}`}s(Cu,"getCLFOffset");function jo(n=new Date){if(!(n instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],t=pt(n.getDate()),o=e[n.getMonth()],r=n.getFullYear(),i=pt(n.getHours()),a=pt(n.getMinutes()),u=pt(n.getSeconds()),c=Cu(n);return`${t}/${o}/${r}:${i}:${a}:${u} ${c}`}s(jo,"toCLFDate");var xs=(0,Ts.debug)("zuplo:runtime"),Ou="X-Amzn-Trace-Id",Au="x-amzn-errortype",vs=[],ku=s(async(n,e,t)=>{let o=t;for await(let r of vs)o=await r(n,e,t);return o},"onSendingAwsLambdaEvent"),Te=class extends L{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(Ou)??void 0,this.errorType=t.get(Au)??void 0}},Lu={addSendingAwsLambdaEventHook:n=>{vs.push(n)}};async function _u(n,e){g("handler.aws-lambda");let{accessKeyId:t,secretAccessKey:o,region:r,functionName:i,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!t)throw new m("awsAccessKeyId is not set in the handler options");if(!o)throw new m("secretAccessKey is not set in the handler options");if(!r)throw new m("region is not set in the handler options");if(!i)throw new m("functionName is not set in the handler options");let l=new dt({accessKeyId:t,secretAccessKey:o}),d=`https://lambda.${r}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(xs(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,f]=await qu(n,{binaryMediaTypes:c}),{options:y}=e.route.handler,O;y&&typeof y=="object"&&"payloadFormatVersion"in y&&y.payloadFormatVersion==="2.0"?O=Mu(n,e):O=await Du(n,e,{useAwsResourcePathStyle:u}),xs("Calling onSendingAwsLambdaEvent hook");let P=await ku(n,e,O);P.body=p,P.isBase64Encoded=f;let v=await l.fetch(d,{body:JSON.stringify(P)});try{return Nu(v)}catch(N){if(N instanceof Te){let k=y&&typeof y=="object"&&"returnAmazonTraceIdHeader"in y&&y.returnAmazonTraceIdHeader&&N.traceId?{AMZN_TRACE_ID_HEADER:N.traceId}:void 0;return x.internalServerError(n,e,void 0,k)}throw N}}s(_u,"awsLambdaHandler");async function Nu(n){let e;try{e=await n.json()}catch{throw new Te("Lambda response did not contain valid JSON",n.headers)}if(n.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new Te(e.message,n.headers):new Te(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new Te(e.errorMessage,n.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:n.status,headers:{"content-type":"application/json"}});let t=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new Te(`Response headers must be an object. Received ${typeof e.headers}`,n.headers);for(let[r,i]of Object.entries(e.headers))t.set(r,i)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new Te(`Response cookies must be an array. Received ${typeof e.cookies}`,n.headers);t.set("cookie",e.cookies.join(";"))}let o;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new Te(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,n.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new Te("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new Te("Response was set to base64 encoded but body was not a string",n.headers);o=Is(e.body)}else"body"in e&&typeof e.body=="string"?o=e.statusCode===204&&e.body===""?null:e.body:"body"in e&&e.body!==null&&e.body!==void 0?o=JSON.stringify(e.body):o=null;if(o!==null&&"bodyEncoding"in e){if(typeof e.bodyEncoding!="string"||!(e.bodyEncoding==="gzip"||e.bodyEncoding==="deflate"))throw new Te(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,n.headers);let r=new Blob([o]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));o=await new Response(r).arrayBuffer()}return new Response(o,{headers:t,status:e.statusCode})}s(Nu,"getResponse");async function Du(n,e,{useAwsResourcePathStyle:t}){let o={},r={};n.headers.forEach((l,d)=>{o[d]=l,r[d]=[l]});let i=n.query,a={};for(let[l,d]of Object.entries(i))a[l]=[d];let u=new URL(n.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:n.method,headers:o,multiValueHeaders:r,queryStringParameters:i,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:n.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:n.headers.get("CF-Connecting-IP"),user:null,userAgent:n.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:jo(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Uu(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}s(Du,"buildEventVersion1");function Mu(n,e){let t={};n.headers.forEach((i,a)=>{t[a]=i});let o=new URL(n.url);return{version:"2.0",routeKey:null,rawPath:o.pathname,rawQueryString:o.search,cookies:[],headers:t,queryStringParameters:n.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:o.hostname,domainPrefix:null,http:{method:n.method,path:o.pathname,protocol:"HTTP/1.1",sourceIp:n.headers.get("CF-Connecting-IP"),userAgent:n.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:jo(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}s(Mu,"buildEventVersion2");async function qu(n,{binaryMediaTypes:e}){let t,o=!1,r=n.headers.get("content-type");if(n.method==="GET"||n.method==="HEAD")t=null;else if(e&&r&&Hu(e,r)){let i=await n.arrayBuffer();t=Es(new Uint8Array(i)),o=!0}else t=await n.clone().text();return[t,o]}s(qu,"getBodyResult");function Hu(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(o=>o==="*/*"?!0:o.toLowerCase()===t)>-1}s(Hu,"matchesContentType");function Uu(n,e=!1){if(!e)return n;let t=Uo(n),o=ys(n),r={};return t.forEach(i=>{typeof i=="string"?r[i]=`{${i}}`:r[i.name]=`{${i.name}}`}),o(r)}s(Uu,"getResourcePath");var Zu=[502,503,504];async function mt(n,e){if(Zu.includes(n.status)){let t=Q.getLogger(e),r=await n.clone().text(),i={};for(let[a,u]of n.headers)i[a]=u;t.warn(`BadGatewayResponse ${n.status}`,{status:n.status,statusText:n.statusText,body:r,headers:i})}}s(mt,"logBadGatewayResponses");var zo;function Ge(n){if(zo===void 0){let t=h.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),zo=t}return n.log[zo]}s(Ge,"getHandlerUserLogFunction");async function Fu(n,e){g("handler.open-api");let t=h.instance.build.BUILD_ID,{buildAssetsUrl:o}=h.instance,r=e.route.handler.options,{openApiFilePath:i}=r;if(!i)throw new m("Open API Spec Handler must have 'openApiFilePath' specified");let a=$u(i);if(!a.isValid)throw new m(a.error);let u;h.instance.isLocalDevelopment?u=`${o}/${i.substring(1)}`:u=`${o}/${t}${i.substring(1)}`;let c=await F.fetch(u,{method:n.method,body:n.body,headers:n.headers});if(c.status!==200)return x.notFound(n,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return mt(l,e),l}s(Fu,"openApiSpecHandler");var $u=s(n=>n.startsWith("./")?n.startsWith("./config")?n.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function ju(n,e){g("handler.redirect");let t=e.route.handler.options;if(!t.location)throw new m("Redirect Handler must have 'location' specified");let o=t.status??302;return new Response(null,{status:o,headers:{location:t.location}})}s(ju,"redirectHandler");function zu(n,e){let t=n.endsWith("/"),o=e.startsWith("/");return t&&o?`${n.substring(0,n.length-1)}${e}`:!t&&!o?`${n}/${e}`:`${n}${e}`}s(zu,"join");async function Bu(n,e){g("handler.url-forward");let t=Ge(e),o=e.route.handler.options,r=o.forwardSearch!==!1;if(!o.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!o||typeof o.__rewriteFunction!="function")throw new m("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(n.url),u=o.__rewriteFunction(n,i),c=zu(u,a.pathname),l=r?`${c}${a.search}`:c.toString(),d=Date.now();t(`URL Forwarding to '${l}'`);let p=await F.fetch(l,{method:n.method,body:n.body,headers:n.headers}),f=Date.now()-d;return t(`URL Forward received response ${p.status} - ${p.statusText} in ${f}ms`),mt(p,e),p}s(Bu,"urlForwardHandler");var Gu=s((n,e)=>{let t=new URL(n),o=new URL(e);for(let[r,i]of o.searchParams.entries())t.searchParams.append(r,i);return t.toString()},"addQuery");async function Vu(n,e){g("handler.url-rewrite");let t=Ge(e),o=e.route.handler.options,r=o.forwardSearch!==!1,i=o.followRedirects??!1;if(!o||typeof o.__rewriteFunction!="function")throw new m("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=o.__rewriteFunction(n,a),c=r?Gu(u,n.url):u,l=Date.now();t(`URL Rewriting to '${c}'`);let d=await F.fetch(c.toString(),{method:n.method,body:n.body,headers:n.headers,redirect:i?"follow":"manual"}),p=Date.now()-l;return t(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),mt(d,e),d}s(Vu,"urlRewriteHandler");async function Wu(n,e){g("handler.websocket");let t=e.route.handler.options,o=Ge(e);if(!t||!t.rewritePattern)throw new m("WebSocket Handler must have option 'rewritePattern' specified");let r=n.headers.get("Upgrade");if(!r||r!=="websocket")return x.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new m("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,i),u=Date.now();o(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await F.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let d=await c.text(),p=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${d}'`;throw new Error(p)}let l=Date.now()-u;return o(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${l}ms`),new Response(null,{status:101,webSocket:c.webSocket})}s(Wu,"webSocketHandler");var Bo=s((n,e)=>n.map((o,r)=>{let i;if(typeof o.module=="object"&&(i=o.module[o.export]),!i||typeof i!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${r+1}, export name: ${o.export}`;throw new m(`${a} - Websocket policy must be a valid function (${u})`)}return i}),"getWebSocketPolicyFunctions"),Ss=s(async(n,e,t,o,r,i)=>{let a=n.data;if(i&&i.length>0){let u=[...i];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,t,e,o,r),a===void 0)return}}return a},"webSocketPolicyProcessor");function Cs(n,e,t,o,r){n.addEventListener("close",()=>{e.close()}),n.addEventListener("error",i=>{o.log.error("WebSocket error: ",i),e.send(JSON.stringify(i))}),n.addEventListener("message",i=>{try{let u=s(async c=>{let l=await Ss(c,n,e,t,o,r);l!==void 0&&e.send(l)},"innerPipeline")(i).catch(o.log.error);o.waitUntil(u)}catch(a){o.log.error(a)}})}s(Cs,"wireUpListeners");async function Ku(n,e){g("handler.websocket-pipeline");let t=e.route.handler.options,o=Ge(e);if(!t||!t.rewritePattern)throw new m("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let r=n.headers.get("Upgrade");if(!r||r!=="websocket")return x.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new m("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,i),u=Date.now();o(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await F.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let v=await c.text(),N=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${v}'`;throw new Error(N)}let l=new WebSocketPair,[d,p]=Object.values(l),f=Date.now()-u;o(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${f}ms`);let y=c.webSocket;y.accept(),p.accept();let O=t.policies&&t.policies.inbound?Bo(t.policies.inbound,"inbound"):[],P=t.policies&&t.policies.outbound?Bo(t.policies.outbound,"outbound"):[];return Cs(p,y,n,e,O),Cs(y,p,n,e,P),new Response(null,{status:101,webSocket:d})}s(Ku,"webSocketPipelineHandler");var Go=class extends ge{constructor(t){super();this.options=t}static{s(this,"DynaTraceLoggingPlugin")}getTransport(){return new Vo(this.options)}},Vo=class{static{s(this,"DynaTraceTransport")}constructor(e){g("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#o=h.instance.loggingEnvironmentType,this.#r=h.instance.loggingEnvironmentStage,this.#n=h.instance.deploymentName}#e;#t;#n;#o;#r;log(e,t){e.messages.forEach(o=>{let r={timestamp:new Date().toISOString(),message:He(Pe(o)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#r,"custom.environmentType":this.#o,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(r)}),t.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{if(e.length!==0)try{let t=await F.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}});if(!t.ok){let o="";try{o=await t.text()}catch{}await le({level:"error",messages:[`Failed to send logs to Dynatrace: ${t.status} - ${t.statusText}`,o]})}}catch{await le({level:"error",messages:["Failed to connect to Dynatrace logging service. Check that the URL is correct."]})}};batcher=new X("dyna-trace-log-transport",10,this.#i)};var Wo=class extends ge{constructor(t){super();this.options=t}static{s(this,"LokiLoggingPlugin")}getTransport(){return new Jo(this.options)}},Ko=class{static{s(this,"LokiStream")}constructor(e,t,o,r,i,a){this.level=e,this.environment=t,this.environmentType=o,this.environmentStage=r,this.requestId=a,this.job=i}job;level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function Ju(n,e){return btoa(`${n}:${e}`)}s(Ju,"createBasicDigest");var Jo=class{static{s(this,"LokiTransport")}constructor(e){g("logging.loki"),this.#n=e.url,this.#o=Ju(e.username,e.password),this.#i=h.instance.loggingEnvironmentType,this.#s=h.instance.loggingEnvironmentStage,this.#r=h.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo"}#e;#t;#n;#o;#r;#i;#s;log(e,t){let o=new Ko(e.level,this.#r,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(r=>{let i={stream:o,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:He(Pe(r)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(i)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=e=>{let t={streams:[]};return e.forEach(o=>{let r=t.streams.find(i=>i.stream.equals(o.stream));r||(r={stream:o.stream,values:[]},t.streams.push(r)),r.values.push(this.#e>1?[o.nanoSecondEpoch,o.message,{requestId:o.requestId,rayId:o.rayId,atomicCounter:JSON.stringify(o.atomicCounter)}]:[o.nanoSecondEpoch,o.message])}),t};#u=async e=>{if(e.length===0)return;let t=this.#a(e);try{let o=await F.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#o}`}});if(!o.ok){let r="";try{r=await o.text()}catch{}await le({level:"error",messages:[`Failed to send logs to Loki: ${o.status} - ${o.statusText}`,r]})}}catch{await le({level:"error",messages:["Failed to connect to Loki logging service. Check that the URL is correct."]})}};batcher=new X("loki-log-transport",10,this.#u)};var Qo=class extends ge{constructor(t){super();this.options=t}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new Xo(this.options)}},Xo=class{static{s(this,"SumoLogicTransport")}constructor(e){g("logging.sumologic"),this.#e=e.url,this.#r=e.category,this.#i=e.name,this.#n=h.instance.loggingEnvironmentType,this.#o=h.instance.loggingEnvironmentStage,this.#t=h.instance.deploymentName}#e;#t;#n;#o;#r;#i;log(e,t){e.messages.forEach(o=>{let r={timestamp:new Date().toISOString(),message:He(Pe(o)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#o,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(r)}),t.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let t=e.map(r=>JSON.stringify(r)).join(`
|
|
51
|
+
`),o=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&o.set("X-Sumo-Name",this.#i),this.#r&&o.set("X-Sumo-Category",this.#r);try{let r=await F.fetch(this.#e,{method:"POST",body:t,headers:o});if(!r.ok){let i="";try{i=await r.text()}catch{}await le({level:"error",messages:[`Failed to send logs to Sumologic: ${r.status} - ${r.statusText}`,i]})}}catch{await le({level:"error",messages:["Failed to connect to Sumologic logging service. Check that the URL is correct."]})}};batcher=new X("sumo-logic-log-transport",10,this.#s)};var Qu="d3a5b78f823648f5b1df4fe269d41172",Yo=class extends ge{constructor(t){super();this.options=t}static{s(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new er(this.options)}},er=class{static{s(this,"VMWareLogInsightTransport")}constructor(e){g("logging.vmware-loginsight");let t;try{t=new URL(e.url),t.pathname==="/"&&(t.pathname=`/api/v1/events/ingest/${e.agentId??Qu}`)}catch{throw new m(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=t.toString(),this.#o=h.instance.loggingEnvironmentType,this.#r=h.instance.loggingEnvironmentStage,this.#n=h.instance.deploymentName,this.#i=e.onMessageSending,this.#t=e.textReplacements,e.fields&&(this.#s=Object.entries(e.fields).map(([o,r])=>({name:o,content:r})))}#e;#t;#n;#o;#r;#i;#s;log(e,t){let o=this.buildEntry(e,t);this.batcher.enqueue(o),t.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,t){let o=rs(e.messages);this.#t?.forEach(i=>{o=o.replaceAll(i[0],i[1])});let r={timestamp:Date.now(),text:o,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#o},{name:"environment_stage",content:this.#r},{name:"log_source",content:e.logSource},{name:"atomic_counter",content:e.vectorClock}]};return e.rayId&&r.fields.push({name:"request_ray_id",content:e.rayId}),this.#n&&r.fields.push({name:"environment",content:this.#n}),this.#s&&r.fields.push(...this.#s),t.custom&&Object.entries(t.custom).forEach(([i,a])=>{let u=vo(a);u&&r.fields.push({name:i,content:u})}),this.#i&&(r=this.#i(r)),r}#a=async e=>{if(e.length!==0)try{let t=await F.fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});if(!t.ok){let o="";try{o=await t.text()}catch{}await le({level:"error",messages:[`Failed to send logs to Log Insight: ${t.status} - ${t.statusText}`,o]})}}catch{await le({level:"error",messages:["Failed to connect to Log Insight logging service. Check that the URL is correct."]})}};batcher=new X("vmware-log-insights-log-transport",10,this.#a)};var tr=class extends ge{constructor(t){super();this.options=t}static{s(this,"AWSLoggingPlugin")}getTransport(){return new nr(this.options)}},nr=class{static{s(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new X("aws-log-transport",10,async e=>{if(e.length===0)return;let t=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});try{let o=await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:t,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}});if(!o.ok){let r="";try{r=await o.text()}catch{}await le({level:"error",messages:[`Failed to send logs to AWS: ${o.status} - ${o.statusText}`,r]})}}catch{await le({level:"error",messages:["Failed to connect to AWS logging service. Check that the URL is correct."]})}});constructor({accessKeyId:e,logStreamName:t,logGroupName:o,secretAccessKey:r,region:i}){g("logging.aws"),this.awsClient=new dt({accessKeyId:e,secretAccessKey:r,service:"logs",region:i}),this.logGroupName=o,this.logStreamName=t,this.region=i,this.environmentType=h.instance.loggingEnvironmentType,this.environment=h.instance.deploymentName}log(e,t){e.messages.forEach(o=>{let r={timestamp:new Date().getTime(),message:JSON.stringify({data:He(Pe(o)),severity:e.level,source:e.logSource,environment:this.environment,requestId:e.requestId,environmentType:this.environmentType,rayId:e.rayId===null?void 0:e.rayId})};this.batcher.enqueue(r)}),t.waitUntil(this.batcher.waitUntilFlushed())}};var or=new WeakMap,Xu={tags:[]},rr=class extends $e{constructor(t){super();this.options=t;g("metrics.datadog")}static{s(this,"DataDogMetricsPlugin")}getTransport(){return new ir(this.options)}static setContext(t,o){let r=or.get(t);r||(r=Xu);let i=Object.assign({...r},o);or.set(t,i)}},ir=class{static{s(this,"DataDogMetricsTransport")}#e;#t;#n;#o;#r;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://api.datadoghq.com/api/v2/series",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#r=e.include??{},this.#o=e.tags??[]}pushMetrics(e,t){this.#i===void 0&&(this.#i=new X("data-dog-metrics-transport",10,this.dispatchFunction,Q.getLogger(t)));let o=Math.floor(e.timestamp.getTime()/1e3),r=this.#o.concat(or.get(t)?.tags??[]);if(this.#r.country&&r.push(`country:${e.country}`),this.#r.httpMethod&&r.push(`httpMethod:${e.method}`),this.#r.statusCode&&r.push(`statusCode:${e.statusCode}`),this.#r.path){let i=e.systemRouteName||e.routePath;r.push(`path:${i}`)}this.#n.latency&&this.#i.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:o,value:e.durationMs}],tags:r}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:o,value:e.requestContentLength}],tags:r}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:o,value:e.responseContentLength}],tags:r}),t.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let t=JSON.stringify({series:e}),o=await F.fetch(this.#t,{method:"POST",body:t,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!o.ok)throw new sr(await o.text())}},sr=class n extends Error{static{s(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var ar=new WeakMap,Yu={dimensions:[]},ur=class extends $e{constructor(t){super();this.options=t;g("metrics.dynatrace")}static{s(this,"DynatraceMetricsPlugin")}getTransport(){return new cr(this.options)}static setContext(t,o){let r=ar.get(t);r||(r=Yu);let i=Object.assign({...r},o);ar.set(t,i)}},cr=class{static{s(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#n;#o=void 0;constructor(e){this.apiToken=e.apiToken,this.#e=e.url,this.#t=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#n=e.include??{},this.dimensions=e.dimensions??[]}pushMetrics(e,t){this.#o===void 0&&(this.#o=new X("dynatrace-metrics-transport",10,this.dispatchFunction,Q.getLogger(t)));let o=Math.floor(e.timestamp.getTime()),r=this.dimensions.concat(ar.get(t)?.dimensions??[]);if(this.#n.country&&r.push(`country="${e.country}"`),this.#n.httpMethod&&r.push(`http_method="${e.method}"`),this.#n.statusCode&&r.push(`status_code="${e.statusCode}"`),this.#n.path){let a=e.systemRouteName||e.routePath;r.push(`path="${a}"`)}let i=r.join(",");this.#t.latency&&this.#o.enqueue(`zuplo.request.latency,${i} ${e.durationMs} ${o}`),this.#t.requestContentLength&&e.requestContentLength&&this.#o.enqueue(`zuplo.request.content_length,${i} ${e.requestContentLength} ${o}`),this.#t.responseContentLength&&e.responseContentLength&&this.#o.enqueue(`zuplo.response.content_length,${i} ${e.responseContentLength} ${o}`),t.waitUntil(this.#o.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let t=e.join(`
|
|
52
|
+
`),o=await F.fetch(this.#e,{method:"POST",body:t,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!o.ok)throw new lr(await o.text())}},lr=class n extends Error{static{s(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var dr=class{static{s(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e,g("audit-logs.datastax")}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async t=>{await F.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(t)})}))}};var pr=class extends Me{static{s(this,"AuditLogPlugin")}constructor(e,t){super(),this.#e=e,this.#t=t,g("audit-logs")}#e;#t;async initialize(e){new mr(e,this.#e,this.#t)}},Os=s(n=>{let e={};return n.forEach((t,o)=>{e[o]=t}),e},"serializableHeaders"),ec={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},mr=class{static{s(this,"AuditPluginImpl")}constructor(e,t,o){this.#t=t;let r={...ec};o?.requestFilter&&(r.requestFilter=o.requestFilter),o?.include?.request&&Object.assign(r,o.include.request),o?.include?.response&&Object.assign(r,o.include.response),this.#e=r,e.addRequestHook(this.#i),this.#n=new X("audit-log",10,this.#o)}#e;#t;#n;#o=async e=>{await this.#t.writeLogBatch(e)};#r=async(e,t,o,r,i,a)=>{try{let u={timestamp:r,durationMs:i,routePath:o.route.path,requestId:o.requestId,userSub:a,request:{url:t.url,method:t.method,headers:this.#e.include?.request?.headers?Os(t.headers):void 0,body:this.#e.include?.request?.body?await t.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?Os(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(u),o.waitUntil(this.#n.waitUntilFlushed())}catch(u){o.log.error(u)}};#i=async(e,t)=>{try{if(!await this.#e.requestFilter(e,t))return e;let r=new Date,i=Date.now(),a=e.clone();return t.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#r(d,a,t,r,l-i,c.user?.sub).catch(f=>{t.log.error(f)});t.waitUntil(p)}),e}catch(o){return t.log.error(o),e}}};var gr=class extends Error{static{s(this,"StripeError")}message;type;raw;rawType;headers;requestId;code;doc_url;param;detail;statusCode;charge;decline_code;payment_method_type;payment_intent;payment_method;setup_intent;source;constructor(e={}){super(e.message),this.type=this.constructor.name,this.raw=e,this.rawType=e.type,this.code=e.code,this.doc_url=e.doc_url,this.param=e.param,this.detail=e.detail,this.headers=e.headers,this.requestId=e.requestId,this.statusCode=e.statusCode,this.message=e.message,this.charge=e.charge,this.decline_code=e.decline_code,this.payment_intent=e.payment_intent,this.payment_method=e.payment_method,this.payment_method_type=e.payment_method_type,this.setup_intent=e.setup_intent,this.source=e.source}},De=class extends gr{static{s(this,"StripeSignatureVerificationError")}header;payload;constructor(e,t,o={}){super(o),this.header=e,this.payload=t}};var tc="v1",nc=300;async function As(n,e,t,o=nc,r){return await rc(n,e,t,o,r),n instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(n)):JSON.parse(n)}s(As,"constructEventAsync");function oc(n,e){return`${e.timestamp}.${n}`}s(oc,"makeHMACContent");async function rc(n,e,t,o,r){let{decodedHeader:i,decodedPayload:a,details:u,suspectPayloadType:c}=ic(n,e,tc),l=/\s/.test(t),d=await cc(oc(a,u),t);return sc(a,i,u,d,o,c,l,r)}s(rc,"verifyHeaderAsync");function ic(n,e,t){if(!n)throw new De(e,n,{message:"No webhook payload was provided."});let o=typeof n!="string"&&!(n instanceof Uint8Array),r=new TextDecoder("utf8"),i=n instanceof Uint8Array?r.decode(n):n;if(Array.isArray(e))throw new Error("Unexpected: An array was passed as a header, which should not be possible for the stripe-signature header.");if(e==null||e=="")throw new De(e,n,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?r.decode(e):e,u=ac(a,t);if(!u||u.timestamp===-1)throw new De(a,i,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new De(a,i,{message:"No signatures found with expected scheme"});return{decodedPayload:i,decodedHeader:a,details:u,suspectPayloadType:o}}s(ic,"parseEventDetails");function sc(n,e,t,o,r,i,a,u){let c=!!t.signatures.filter(f=>uc(f,o)).length,l=`
|
|
53
53
|
Learn more about webhook signing and explore webhook integration examples for various frameworks at https://github.com/stripe/stripe-node#webhook-signing`,d=a?`
|
|
54
54
|
|
|
55
55
|
Note: The provided signing secret contains whitespace. This often indicates an extra newline or space is in the value`:"";if(!c)throw i?new De(e,n,{message:`Webhook payload must be provided as a string or a Buffer (https://nodejs.org/api/buffer.html) instance representing the _raw_ request body.Payload was provided as a parsed JavaScript object instead.
|
|
@@ -58,8 +58,9 @@ Signature verification is impossible without access to the original signed mater
|
|
|
58
58
|
`+d}):new De(e,n,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
|
|
59
59
|
If a webhook request is being forwarded by a third-party tool, ensure that the exact request body, including JSON formatting and new line style, is preserved.
|
|
60
60
|
`+l+`
|
|
61
|
-
`+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new De(e,n,{message:"Timestamp outside the tolerance zone"});return!0}s(ac,"validateComputedSignature");function uc(n,e){return typeof n!="string"?null:n.split(",").reduce((t,r)=>{let o=r.split("=");return o[0]==="t"&&(t.timestamp=parseInt(o[1],10)),o[0]===e&&t.signatures.push(o[1]),t},{timestamp:-1,signatures:[]})}s(uc,"parseHeader");function cc(n,e){if(n.length!==e.length)return!1;let t=n.length,r=0;for(let o=0;o<t;++o)r|=n.charCodeAt(o)^e.charCodeAt(o);return r===0}s(cc,"secureCompare");async function lc(n,e){let t=new TextEncoder,r=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,t.encode(n)),i=new Uint8Array(o),a=new Array(i.length);for(let u=0;u<i.length;u++)a[u]=wo[i[u]];return a.join("")}s(lc,"computeHMACSignatureAsync");var wo=new Array(256);for(let n=0;n<wo.length;n++)wo[n]=n.toString(16).padStart(2,"0");function X(n,e,t="policy",r){let o=`${t} '${e}'`;if(!Ye(n))throw new m(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let i=s((c,l,d)=>{let p=n[c],h=r?`${r}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new m(`Value of '${h}' on ${o} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"&&Array.isArray(p))throw new m(`Value of '${h}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new m(`Value of '${h}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new m(`Value of '${h}' on ${o} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof p=="number"&&isNaN(p))throw new m(`Value of '${h}' on ${o} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=s((c,l)=>(i(c,l,!0),{optional:a,required:u}),"optional"),u=s((c,l)=>(i(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}s(X,"optionValidator");var jt=class extends de{static{s(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.stripe-webhook-verification")}async handler(e,t){X(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let r=e.headers.get("stripe-signature");try{let o=await e.clone().text();await As(o,r,this.options.signingSecret)}catch(o){let i=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);i=c?c[1].trim():a,i.startsWith("No signatures found matching the expected signature for payload")&&(i="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",i),x.badRequest(e,t,{title:"Webhook Error",detail:i})}return e}};function ks(n){return n!==null&&typeof n=="object"&&"id"in n&&Ee(n.id)&&"type"in n&&Ee(n.type)}s(ks,"isStripeWebhookEvent");var dc={getSubscription:async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving subscription from Stripe API.";throw t.error(i,o),new k(i)}return o},getCustomer:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer from Stripe API.";throw t.error(i,o),new k(i)}return o},getUpcomingInvoice:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(i,o),new k(i)}return o}},En=dc;var Ro="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Ls="My API Key";async function _s({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:i,context:a}){let{authApiJWT:u}=f.instance,c=new URL(`/v1/buckets/${n}/consumers`,Ro);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Ls,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:i,email:o}]},p=await fe({retryDelayMs:5,retries:2,logger:Y.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),h=await p.json();if(p.status!==200){let y="Error creating API Key Consumer";throw a.log.error(y,h),new k(y)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}s(_s,"createConsumer");async function Ns({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:i}){let{authApiJWT:a}=f.instance,u=new URL(`/v1/buckets/${n}/consumers`,Ro);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:Ls,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await fe({retryDelayMs:5,retries:2,logger:Y.getLogger(i)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let h="Error creating API Key Consumer";throw i.log.error(h,p),new k(h)}return i.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}s(Ns,"createConsumerInvite");async function Ds({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=f.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,Ro);o.searchParams.set("with-api-key","true");let i=await fe({retryDelayMs:5,retries:2,logger:Y.getLogger(t)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(i.status!==204){let a=await i.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new k(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}s(Ds,"deleteConsumer");async function Ms({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:r,meteringBucketId:o,meteringBucketRegion:i,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:i,subscriptionExternalId:e,planExternalIds:[t],customerKey:r,customerExternalId:a,metadata:c,trialEndDate:l?l.trialEndDate:void 0,trialStartDate:l?l.trialStartDate:void 0,trialEndStatus:l?l.trialEndStatus:void 0},{authApiJWT:p,meteringServiceUrl:h}=f.instance;if(!it(p))throw new W("No Zuplo JWT token set.");let y=await fe({retryDelayMs:5,retries:2,logger:Y.getLogger(n)},`${h}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!y.ok){let O=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,P,C="";try{P=await y.json(),C=P.detail??P.title}catch{P={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:y.status,detail:y.statusText}}throw n.log.error(O,P),new k(`${O} ${C}`)}n.log.info("Successfully created monetization subscription.",d)}s(Ms,"createSubscription");async function dt({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:i}=f.instance;if(!it(o))throw new W("No Zuplo JWT token set.");let a=await fe({retryDelayMs:5,retries:2,logger:Y.getLogger(n)},`${i}/internal/v1/metering/${t}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Unable to update monetization subscription with: '${JSON.stringify(r)}'.`,c,l="";try{c=await a.json(),l=c.detail??c.title}catch{c={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(u,c),new k(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}s(dt,"updateSubscription");async function pt({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:i}=f.instance;if(!it(o))throw new W("No Zuplo JWT token set.");let a=await fe({retryDelayMs:5,retries:2,logger:Y.getLogger(n)},`${i}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":n.requestId},method:"GET"});if(!a.ok){let c=`Unable to retrieve the monetization subscription for Stripe subscription '${e}'.`,l,d="";try{l=await a.json(),d=l.detail??l.title}catch{l={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(c,l),new k(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(c),new k(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(c),new k(c)}return u.data[0]}s(pt,"getSubscription");var oe="Skipping since we're unable to process the webhook event.",Ge="Successfully processed the webhook event",Ie="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function xn(n){return n.replaceAll("_","-")}s(xn,"stripeStatusToMeteringStatus");function nt(n){return new Date(n*1e3).toISOString()}s(nt,"unixTimestampToISOString");async function Po(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),x.ok(n,e,{title:oe,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.plan;if(!i||!i.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),x.ok(n,e,{title:oe,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=t.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:oe,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==f.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),x.ok(n,e,{title:oe,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ie});let u=i.product,c,l,d;try{if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_email&&t.data.object.metadata.zuplo_created_by_sub)l=t.data.object.metadata.zuplo_created_by_email,d=t.data.object.metadata.zuplo_created_by_sub,c=await _s({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await En.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),x.ok(n,e,{title:oe,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Ns({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}}catch(p){return e.log.warn(`Failed to create API Key Consumer. Error: ${p.message}`),x.ok(n,e,{title:oe,detail:p.message})}if(!c)return x.ok(n,e,{title:oe,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=xn(t.data.object.status),h;l&&d&&(h={subscriber:{sub:d,email:l}});let y;t.data.object.trial_end!==null&&t.data.object.trial_start!==null&&t.data.object.trial_settings&&t.data.object.trial_settings.end_behavior&&(t.data.object.trial_settings.end_behavior.missing_payment_method==="cancel"||t.data.object.trial_settings.end_behavior.missing_payment_method==="pause")&&(y={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:nt(t.data.object.trial_end),trialStartDate:nt(t.data.object.trial_start)}),await Ms({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:h,trial:y})}catch(p){return await Ds({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),x.ok(n,e,{title:oe,detail:p.message})}return x.ok(n,e,{title:Ge})}s(Po,"onCustomerSubscriptionCreated");async function Io(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),x.ok(n,e,{title:oe,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:oe,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==f.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),x.ok(n,e,{title:oe,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ie});try{let a=await pt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId});await dt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return x.ok(n,e,{title:oe,detail:`The event 'customer.subscription.deleted' could not be processed. ${a.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. `+Ie})}return x.ok(n,e,{title:Ge})}s(Io,"onCustomerSubscriptionDeleted");async function Eo(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to include '.data.object.id' as the subscription ID.`),x.ok(n,e,{title:oe,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:oe,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==f.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),x.ok(n,e,{title:oe,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ie});if(t.data.previous_attributes){let a=t.data.previous_attributes;if(a.status&&a.status!==t.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${t.id}'.`);let u=await pt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=xn(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=nt(t.data.object.trial_end)),await dt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return x.ok(n,e,{title:oe,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ie})}return x.ok(n,e,{title:Ge})}if(a.plan&&a.plan.product!==t.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${t.id}'.`);let u=await pt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await En.getUpcomingInvoice({customerId:i,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(h=>h.proration&&h.price.product===c),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${t.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await dt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return x.ok(n,e,{title:oe,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ie})}return x.ok(n,e,{title:Ge})}if((a.cancel_at||a.cancel_at===null)&&a.cancel_at!==t.data.object.cancel_at&&a.cancel_at_period_end&&a.cancel_at_period_end!==t.data.object.cancel_at_period_end&&(a.canceled_at||a.canceled_at===null)&&a.canceled_at!==t.data.object.canceled_at||a.cancellation_details&&(a.cancellation_details.comment||a.cancellation_details.comment===null||a.cancellation_details.feedback||a.cancellation_details.feedback===null||a.cancellation_details.reason||a.cancellation_details.reason===null)){try{e.log.debug(`Processing subscription cancellation details from Stripe event '${t.id}'.`);let u=await pt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?nt(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?nt(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await dt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return x.ok(n,e,{title:oe,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ie})}return x.ok(n,e,{title:Ge})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),x.ok(n,e,{title:oe,detail:"This 'customer.subscription.updated' event could not be processed. The Stripe monetization plugin only supports update events for subscription plan changes or subscription status changes."+Ie})}s(Eo,"onCustomerSubscriptionUpdated");var Hs=class extends Xt{constructor(t){super();this.options=t;g("monetization.stripe")}static{s(this,"StripeMonetizationPlugin")}registerRoutes(t,r){let o=s(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(Re.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(Re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=Re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!f.instance.build.ACCOUNT_NAME)throw new W("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let h=this.options.primaryDataRegion??"us-central1";if(!pc(h))throw new m(`StripeMonetizationPlugin - The value '${h}' on the property 'primaryDataRegion' is invalid.`);let y=await c.json();if(!ks(y))return x.ok(c,l,{title:oe,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+Ie});switch(l.log.info(`Received Stripe webhook event of type '${y.type}' with ID '${y.id}'.`),y.type){case"customer.subscription.created":return await Po(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await Eo(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await Io(c,l,y,{meteringBucketId:d});default:return x.ok(c,l,{title:oe,detail:`Event '${y.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ie})}},"stripeWebhookHandler"),i=Ki({inboundPolicies:[new jt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});X(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new pe({processors:[be,i],handler:o,gateway:r}),u=new ae({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function pc(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}s(pc,"isMetricsRegion");var qs=new WeakMap,Us={},xo=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){qs.set(e,t)}};async function mc(n,e,t,r){if(g("policy.inbound.amberflo-metering"),!t.statusCodes)throw new m(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=st(t.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=qs.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new k(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=Qe(n.user,t.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??t.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??t.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(t.dimensions??{},a?.dimensions)},h=Us[t.apiKey];if(!h){let y=t.apiKey,O=n.headers.get("zm-test-id")??"";h=new J("amberflo-ingest-meter",10,async P=>{try{let C=t.url??"https://app.amberflo.io/ingest",H=await F.fetch(C,{method:"POST",body:JSON.stringify(P),headers:{"content-type":"application/json","x-api-key":y,"zm-test-id":O}});H.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${H.status}: ${await H.text()}`)}catch(C){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${C.message}`),C}}),Us[y]=h}h.enqueue(p),e.waitUntil(h.waitUntilFlushed())}}),n}s(mc,"AmberfloMeteringInboundPolicy");async function Tn(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(t)].map(o=>o.toString(16).padStart(2,"0")).join("")}s(Tn,"sha256");var Zs=new Map;async function ie(n,e,t){let r,o=`${n}-${e}`,i=Zs.get(o);return i!==void 0?r=i:(r=`zuplo-policy-${await Tn(JSON.stringify({policyName:n,options:t}))}`,Zs.set(n,r)),r}s(ie,"getPolicyCacheName");var Fs="key-metadata-cache-type";function gc(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}s(gc,"getKeyValue");async function To(n,e,t,r){if(g("policy.inbound.api-key"),!t.bucketName)if(Re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=Re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:t.authHeader??"authorization",authScheme:t.authScheme??"Bearer",bucketName:t.bucketName,cacheTtlSeconds:t.cacheTtlSeconds??60,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:t.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new m(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(C=>o.allowUnauthenticatedRequests?n:x.unauthorized(n,e,{detail:C}),"unauthorizedResponse"),a=n.headers.get(o.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let u=gc(a,o);if(!u||u==="")return i("No key present");let c=await fc(u),l=await ie(r,void 0,o),d=new re(l,e),p=await d.get(c);if(p&&p.isValid===!0)return n.user=p.user,n;if(p&&!p.isValid)return p.typeId!==Fs&&Y.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let h={key:u},y=await fe({retryDelayMs:5,retries:2,logger:Y.getLogger(e)},`${f.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":f.instance.deploymentName??"unknown","User-Agent":f.instance.systemUserAgent},body:JSON.stringify(h)});if(y.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(y.status!==200){try{let C=await y.text(),H=JSON.parse(C);e.log.error("Unexpected response from key service",H)}catch{e.log.error("Invalid response from key service")}throw new k(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${y.status}`)}let O=await y.json(),P={isValid:!0,typeId:Fs,user:{sub:O.name,data:O.metadata}};return n.user=P.user,d.put(c,P,o.cacheTtlSeconds),n}s(To,"ApiKeyInboundPolicy");async function fc(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(fc,"hashValue");var hc=To;import{createRemoteJWKSet as bc,jwtVerify as js}from"jose";import{createLocalJWKSet as yc}from"jose";var vo=class{constructor(e,t,r){this.cache=t;if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.url=new URL(e.href),this.options={agent:r?.agent,headers:r?.headers},this.timeoutDuration=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this.cooldownDuration=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this.cacheMaxAge=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5}static{s(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,t){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,t)}catch(r){if(r instanceof Co&&this.coolingDown()===!1)return await this.reload(),this.local(e,t);throw r}}async reload(){this.pendingFetch&&(this.pendingFetch=void 0);let e=new Headers(this.options.headers);e.has("User-Agent")||(e.set("User-Agent",f.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=yc(t),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(t=>{throw this.pendingFetch=void 0,t}),await this.pendingFetch}async fetchJwks(e,t,r){let o=await this.cache.get(this.url.href);if(o)return o;let i,a,u=!1;typeof AbortController=="function"&&(i=new AbortController,a=setTimeout(()=>{u=!0,i.abort()},t));let c=await F.fetch(e.href,{signal:i?i.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new So("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new mt("Expected 200 OK from the JSON Web Key Set HTTP response");try{let l=await c.json();return this.cache.put(this.url.href,l,this.cacheMaxAge),l}catch{throw new mt("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function $s(n,e,t){let r=new vo(n,e,t);return async(o,i)=>r.getKey(o,i)}s($s,"createRemoteJWKSet");var mt=class extends k{static{s(this,"JWKSError")}},Co=class extends mt{static{s(this,"JWKSNoMatchingKey")}},So=class extends mt{static{s(this,"JWKSTimeout")}};var vn={},wc=s((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");if(!vn[r.jwkUrl]){let i=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(i=r.useExperimentalInMemoryCache),i){let a=await ie(n,void 0,r),u=new re(a,e);vn[r.jwkUrl]=$s(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else vn[r.jwkUrl]=bc(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await js(t,vn[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),Rc=s(async(n,e)=>{let t;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let i=new TextEncoder().encode(e.secret);t=new Uint8Array(i)}else t=e.secret;let{payload:r}=await js(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),we=s(async(n,e,t,r)=>{g("policy.inbound.open-id-jwt-auth");let o=n.headers.get("Authorization"),i="bearer ",a=s(h=>x.unauthorized(n,e,{detail:h}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=t.jwkUrl?wc(r,e):Rc,l=await s(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(i)!==0)return a("Invalid bearer token format for authorization header");let h=o.substring(i.length);if(!h||h.length===0)return a("No bearer token on authorization header");try{return await u(h,t)}catch(y){let O=new URL(n.url);return"code"in y&&y.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${O.pathname} `,y):e.log.warn(`Invalid token on: ${n.method} ${O.pathname}`,y),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return t.allowUnauthenticatedRequests===!0?n:l;let d=t.subPropertyName??"sub",p=l[d];return p?(n.user={sub:p,data:l},n):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var Pc=s(async(n,e,t,r)=>(g("policy.inbound.auth0-jwt-auth"),we(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"Auth0JwtInboundPolicy");var Oo=class n extends de{static{s(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static#e;static setAuthAttributes(e,t){n.#e||(n.#e=new WeakMap),n.#e.set(e,{Request:t})}constructor(e,t){super(e,t),g("policy.inbound.axiomatics-authz"),X(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new ai(e)}async handler(e,t){let r=s(a=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=new URL(e.url),i=n.#e?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1&&e.user){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(i,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(i,"Action",a)}if(this.options.includeDefaultResourceAttributes!==!1){let a=[];a.push({AttributeId:"request.protocol",Value:o.protocol.substring(0,o.protocol.length-1)}),a.push({AttributeId:"request.host",Value:o.host}),a.push({AttributeId:"request.pathname",Value:o.pathname}),Object.entries(e.params).forEach(([u,c])=>{a.push({AttributeId:`request.params.${u}`,Value:c})}),o.searchParams.forEach((u,c)=>{a.push({AttributeId:`request.query.${c}`,Value:u})}),this.addAttributesToCategory(i,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:i,context:t}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:i,context:t}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:i,context:t});try{t.log.debug("PDP Request",i);let a=await this.pdpService.makePdpRequest(i);return t.log.debug("PDP Response",a),a.Response.every(u=>u.Decision==="Permit")?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling PDP service`,a),x.internalServerError(e,t)}}populateOptionAttributes({optionName:e,authzRequestCategory:t,authzRequest:r,context:o}){let i=this.options[e];if(i){let a=[];i.forEach(u=>{u.value?a.push({AttributeId:u.attributeId,Value:u.value}):o.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${u.attributeId} has no value. If using a selector, check that the selector is correct.`)}),this.addAttributesToCategory(r,t,a)}}addAttributesToCategory(e,t,r){e.Request[t]||(e.Request[t]=[]),e.Request[t].length===0?e.Request[t].push({Attribute:[]}):e.Request[t][0].Attribute=e.Request[t][0].Attribute??[],e.Request[t][0].Attribute.push(...r)}};var Ic=s(async(n,e,t)=>{g("policy.inbound.basic-auth");let r=n.headers.get("Authorization"),o="basic ",i=s(l=>x.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await s(async()=>{if(!r)return await i("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await i("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await i("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let h=d.substring(0,p),y=d.substring(p+1),O=t.accounts.find(P=>P.username===h&&P.password===y);return O||await i("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return t.allowUnauthenticatedRequests?n:u;let c=u.username;return n.user={sub:c,data:u.data},n},"BasicAuthInboundPolicy");function Cn(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}s(Cn,"extractDateElements");function zs(n,e){return new Date(n,e+1,0).getDate()}s(zs,"getDaysInMonth");function Ao(n,e){return n<=e?e-n:6-n+e+1}s(Ao,"getDaysBetweenWeekdays");var Sn=class{static{s(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:r,days:o,months:i,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!t||t.size===0)throw new Error("There must be at least one allowed minute.");if(!r||r.size===0)throw new Error("There must be at least one allowed hour.");if(!i||i.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!o||o.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((c,l)=>c-l),this.minutes=Array.from(t).sort((c,l)=>c-l),this.hours=Array.from(r).sort((c,l)=>c-l),this.days=Array.from(o).sort((c,l)=>c-l),this.months=Array.from(i).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=s((c,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${c} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");u("seconds",this.seconds,{min:0,max:59}),u("minutes",this.minutes,{min:0,max:59}),u("hours",this.hours,{min:0,max:23}),u("days",this.days,{min:1,max:31}),u("months",this.months,{min:0,max:11}),u("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(c=>c).reverse(),minutes:this.minutes.map(c=>c).reverse(),hours:this.hours.map(c=>c).reverse(),days:this.days.map(c=>c).reverse(),months:this.months.map(c=>c).reverse(),weekdays:this.weekdays.map(c=>c).reverse()}}findAllowedHour(e,t){return e==="next"?this.hours.find(r=>r>=t):this.reversed.hours.find(r=>r<=t)}findAllowedMinute(e,t){return e==="next"?this.minutes.find(r=>r>=t):this.reversed.minutes.find(r=>r<=t)}findAllowedSecond(e,t){return e==="next"?this.seconds.find(r=>r>t):this.reversed.seconds.find(r=>r<t)}findAllowedTime(e,t){let r=this.findAllowedHour(e,t.hour);if(r!==void 0)if(r===t.hour){let o=this.findAllowedMinute(e,t.minute);if(o!==void 0)if(o===t.minute){let i=this.findAllowedSecond(e,t.second);if(i!==void 0)return{hour:r,minute:o,second:i};if(o=this.findAllowedMinute(e,e==="next"?t.minute+1:t.minute-1),o!==void 0)return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(r=this.findAllowedHour(e,e==="next"?t.hour+1:t.hour-1),r!==void 0)return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,t,r,o){if(o<1)throw new Error("startDay must not be smaller than 1.");let i=zs(t,r),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return o>i?e==="next"?void 0:i:o;let c;a&&(c=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),c!==void 0&&c>i&&(c=void 0));let l;if(u){let d=new Date(t,r,o).getDay(),p=e==="next"?this.weekdays.find(h=>h>=d)??this.weekdays[0]:this.reversed.weekdays.find(h=>h<=d)??this.reversed.weekdays[0];if(p!==void 0){let h=e==="next"?Ao(d,p):Ao(p,d);l=e==="next"?o+h:o-h,(l>i||l<1)&&(l=void 0)}}if(c!==void 0&&l!==void 0)return e==="next"?Math.min(c,l):Math.max(c,l);if(c!==void 0)return c;if(l!==void 0)return l}getNextDate(e=new Date){let t=Cn(e),r=t.year,o=this.months.findIndex(a=>a>=t.month);o===-1&&(o=0,r++);let i=this.months.length*5;for(let a=0;a<i;a++){let u=r+Math.floor((o+a)/this.months.length),c=this.months[(o+a)%this.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("next",u,c,l?t.day:1),p=l&&d===t.day;if(d!==void 0&&p){let h=this.findAllowedTime("next",t);if(h!==void 0)return new Date(u,c,d,h.hour,h.minute,h.second);d=this.findAllowedDayInMonth("next",u,c,d+1),p=!1}if(d!==void 0&&!p)return new Date(u,c,d,this.hours[0],this.minutes[0],this.seconds[0])}throw new Error("No valid next date was found.")}getNextDates(e,t){let r=[],o;for(let i=0;i<e;i++)o=this.getNextDate(o??t),r.push(o);return r}*getNextDatesIterator(e,t){let r;for(;;){if(r=this.getNextDate(e),e=r,t&&t.getTime()<r.getTime())return;yield r}}getPrevDate(e=new Date){let t=Cn(e),r=t.year,o=this.reversed.months.findIndex(a=>a<=t.month);o===-1&&(o=0,r--);let i=this.reversed.months.length*5;for(let a=0;a<i;a++){let u=r-Math.floor((o+a)/this.reversed.months.length),c=this.reversed.months[(o+a)%this.reversed.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("prev",u,c,l?t.day:31),p=l&&d===t.day;if(d!==void 0&&p){let h=this.findAllowedTime("prev",t);if(h!==void 0)return new Date(u,c,d,h.hour,h.minute,h.second);d>1&&(d=this.findAllowedDayInMonth("prev",u,c,d-1),p=!1)}if(d!==void 0&&!p)return new Date(u,c,d,this.reversed.hours[0],this.reversed.minutes[0],this.reversed.seconds[0])}throw new Error("No valid previous date was found.")}getPrevDates(e,t){let r=[],o;for(let i=0;i<e;i++)o=this.getPrevDate(o??t),r.push(o);return r}*getPrevDatesIterator(e,t){let r;for(;;){if(r=this.getPrevDate(e),e=r,t&&t.getTime()>r.getTime())return;yield r}}matchDate(e){let{second:t,minute:r,hour:o,day:i,month:a,weekday:u}=Cn(e);return this.seconds.indexOf(t)===-1||this.minutes.indexOf(r)===-1||this.hours.indexOf(o)===-1||this.months.indexOf(a)===-1?!1:this.days.length!==31&&this.weekdays.length!==7?this.days.indexOf(i)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(i)!==-1&&this.weekdays.indexOf(u)!==-1}};var Ec={min:0,max:59},xc={min:0,max:59},Tc={min:0,max:23},vc={min:1,max:31},Cc={min:1,max:12,aliases:{jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"}},Sc={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},Oc={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 1 *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@hourly":"0 * * * *","@minutely":"* * * * *"};function rt(n,e){let t=new Set;if(n==="*"){for(let d=e.min;d<=e.max;d=d+1)t.add(d);return t}let r=n.split(",");if(r.length>1)return r.forEach(d=>{rt(d,e).forEach(h=>t.add(h))}),t;let o=s(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${n}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${n}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),i=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(i===null)return t.add(o(n)),t;let a=i[1]==="*"?e.min:o(i[3]),u=i[1]==="*"?e.max:o(i[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=i[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}s(rt,"parseElement");function ko(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=Oc[n.toLowerCase()]??n;let e=n.split(" ");if(e.length<5||e.length>6)throw new Error("Invalid cron expression: expected 5 or 6 elements.");let t=e.length===6?e[0]:"0",r=e.length===6?e[1]:e[0],o=e.length===6?e[2]:e[1],i=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],u=e.length===6?e[5]:e[4];return new Sn({seconds:rt(t,Ec),minutes:rt(r,xc),hours:rt(o,Tc),days:rt(i,vc),months:new Set(Array.from(rt(a,Cc)).map(c=>c-1)),weekdays:new Set(Array.from(rt(u,Sc)).map(c=>c%7))})}s(ko,"parseCronExpression");var Lo=class extends de{static{s(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),g("policy.inbound.brownout"),X(e,t).optional("problem","object"),e.problem&&X(e.problem,t,"policy","problem").optional("detail","string").optional("status","string").optional("title","string"),typeof e.cronSchedule!="string"&&!(typeof e.cronSchedule=="object"&&Array.isArray(e.cronSchedule)&&!e.cronSchedule.some(r=>typeof r!="string")))throw new m(`Value of 'cronSchedule' on policy '${t}' must be of type string or string[]. Received type ${typeof e.cronSchedule}.`);typeof this.options.cronSchedule=="string"?this.crons=[ko(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>ko(r))}async handler(e,t){let r=new Date;if(r.setSeconds(0),r.setMilliseconds(0),this.crons.some(i=>i.matchDate(r))){let i=x.getProblemFromStatus(this.options.problem?.status??400,{detail:"This API is performing a scheduled brownout in advance of its pending deprecation. Please upgrade to a later version.",...this.options.problem});return x.format(i,e,t)}return e}};var Ac=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function kc(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(kc,"digestMessage");var Lc=s(async(n,e)=>{let t=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of n.headers.entries())t.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await kc(JSON.stringify(r)),i=new URL(n.url),a=new URLSearchParams(i.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(n.method.toUpperCase())&&n.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",n.method);let c=`${i.origin}${i.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function _c(n,e,t,r){g("policy.inbound.caching");let o=await ie(r,t.cacheId,t),i=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Lc(n,t),c=await i.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=t.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(n.method.toUpperCase()))return;let h=t?.expirationSecondsTtl??60,y=new Response(p.body,p);Ac.forEach(O=>y.headers.delete(O)),y.headers.set("cache-control",`s-maxage=${h}`),e.waitUntil(i.put(u,y))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}s(_c,"CachingInboundPolicy");var Nc=s(async(n,e,t,r)=>{if(g("policy.inbound.change-method"),!t.method)throw new m(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new te(n,{method:t.method})},"ChangeMethodInboundPolicy");var Dc=s(async(n,e,t)=>{g("policy.inbound.clear-headers");let r=[...t.exclude??[]],o=new Headers;return r.forEach(a=>{let u=n.headers.get(a);u&&o.set(a,u)}),new te(n,{headers:o})},"ClearHeadersInboundPolicy");var Mc=s(async(n,e,t,r)=>{g("policy.outbound.clear-headers");let o=[...r.exclude??[]],i=new Headers;return o.forEach(u=>{let c=n.headers.get(u);c&&i.set(u,c)}),new Response(n.body,{headers:i,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var Hc=s(async(n,e,t,r)=>{g("policy.inbound.clerk-jwt-auth");let o=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",we(n,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var Uc=s(async(n,e,t,r)=>{if(g("policy.inbound.cognito-jwt-auth"),!t.userPoolId)throw new m("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new m("region must be set in the options for CognitoJwtInboundPolicy");return we(n,e,{issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,jwkUrl:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var Ws=Ve(We());var On=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},_o=class extends On{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},No=class extends On{static{s(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function qc(n,e){if(Fi(n))throw new _o(e)}s(qc,"throwIfUndefinedOrNull");function zt(n,e){if(qc(n,e),!Ee(n))throw new No(e,"string")}s(zt,"throwIfNotString");var An=class n{static{s(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,t,r,o){this.redisClientUrl=e,this.clientAuthToken=t,this.deploymentName=r,this.userAgent=o}static initialize(e,t,r,o){return zt(e,"redisClientUrl"),zt(t,"clientAuthToken"),n.instance||(n.instance=new n(e,t,r,o)),n.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:t,method:r,requestId:o}){zt(e,"url");let i=await F.fetch(`${this.redisClientUrl}${e}`,{method:r,body:t,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=i.headers.get("Content-Type")?.includes("application/json")?await i.json():await i.text();if(i.ok)return a;throw i.status===401?new W("Rate limiting service failed with 401: Unauthorized"):new W(`Rate limiting service failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},kn=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:t,method:r}){if(zt(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:i,key:a}=JSON.parse(t),u=Date.now()+i*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new W("The in-memory rate limit client does not support this request")}};var Zc=s(n=>{let e=n.headers.get("x-real-ip")??n.headers.get("true-client-ip")??n.headers.get("cf-connecting-ip");if(e)return e;let t=n.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP");function gt(n,e){return{function:zc(e,"RateLimitInboundPolicy",n),user:$c,ip:Fc,all:jc}[e.rateLimitBy??"ip"]}s(gt,"getRateLimitByFunctions");var Fc=s(async n=>({key:`ip-${Zc(n)}`}),"getIP"),$c=s(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),jc=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Ln;function ft(n,e){let t;if(Ln)return Ln;if(!f.instance.authApiJWT)return e.info("Using in-memory rate limit client for local development."),t=new kn,Ln=t,t;let{authApiJWT:r,redisURL:o}=f.instance;if(!Ee(o))throw new W(`RateLimitClient used in policy '${n}' - rate limit service URL not configured`);if(!Ee(r))throw new W(`RateLimitClient used in policy '${n}' - service authentication not configured`);if(o&&(t=An.initialize(o,r,f.instance.deploymentName??"unknown",f.instance.systemUserAgent)),!t||!t.isEnabled())throw new W(`RateLimitClient used in policy '${n}' - no remote rate limiting service enabled`);return Ln=t,t}s(ft,"getRedisClient");async function _n(n,e,t,r){let o=Math.floor(e*60);return await t.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:o,key:n}),requestId:r})}s(_n,"getCountAndUpdateExpiry");async function Bs(n,e,t){return(await e.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:n}),requestId:t})).data}s(Bs,"multiCount");async function Gs(n,e,t){return(await e.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:n}),requestId:t})).data}s(Gs,"multiIncrement");function zc(n,e,t){let r;if(n.rateLimitBy==="function"){if(!n.identifier)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=n.identifier.module[n.identifier.export],!r||typeof r!="function")throw new m(`${e} '${t}' - Custom rate limit function must be a valid function`)}return s(async(i,a,u)=>{let c=await r(i,a,u);if(!c||typeof c!="object"){let l=`${e} '${u}' - Custom rate limit function must return a valid object.`;throw a.log.error(l),new k(l)}if(!("key"in c)){let l=`${e} '${u}' - Custom rate limit function must return a valid key property.`;throw a.log.error(l,c),new k(l)}if(typeof c.key!="string"){let l=`${e} '${u}' - Custom rate limit function must return a valid key property of type string. Received type '${typeof c.key}'`;throw a.log.error(l),new k(l)}return c},"outerFunction")}s(zc,"wrapUserFunction");var ht="Retry-After";var Vs=(0,Ws.debug)("zuplo:policies:ComplexRateLimitInboundPolicy"),Do=Symbol("complex-rate-limit-counters"),Mo=class n extends de{static{s(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let r=ge.get(e,Do)??{};Object.assign(r,t),ge.set(e,Do,t)}static getIncrements(e){return ge.get(e,Do)??{}}constructor(e,t){super(e,t),g("policy.inbound.complex-rate-limit-inbound"),X(e,t).required("rateLimitBy","string").required("timeWindowMinutes","number").required("limits","object").optional("headerMode","string").optional("throwOnFailure","boolean").optional("mode","string").optional("identifier","object"),e.identifier&&X(e.identifier,t,"policy","identifier").required("export","string").required("module","object");for(let[r,o]of Object.entries(e.limits))if(typeof o!="number")throw new m(`ComplexRateLimitInboundPolicy '${this.policyName}' - The value of the limits must be numbers. The limit ${r} is set to type '${typeof e}'.`)}async handler(e,t){let r=Date.now(),o=Y.getLogger(t),i=ft(this.policyName,o),a=s((c,l)=>{if(this.options.throwOnFailure)throw new W(c,{cause:l});o.error(c,l)},"throwOrLog"),u=s((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[ht]=l.toString()),x.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l=await gt(this.policyName,this.options)(e,t,this.policyName),d=f.instance.isTestMode||f.instance.isWorkingCopy?f.instance.build.BUILD_ID:"",p=Object.assign({},this.options.limits,l.limits),h=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;t.addResponseSendingFinalHook(async()=>{try{let C=n.getIncrements(t);Vs(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(C)}`);let H=Object.entries(p).map(([j])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${j}`,ttlSeconds:h,increment:C[j]??0})),_=Gs(H,i,t.requestId);t.waitUntil(_),await _}catch(C){t.log.error(C)}});let y=Object.entries(p).map(([C,H])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${C}`,ttlSeconds:h,limit:H})),O=await Bs(y,i,t.requestId);return Bc(O,y).length>0?u(this.options.headerMode??"retry-after",h):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-r;Vs(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function Bc(n,e){let t=[];for(let r of n){let o=e.find(i=>i.key===r.key)?.limit||0;r.count>=o&&t.push(r)}return t}s(Bc,"findOverLimits");var Gc=s(async(n,e,t,r)=>{if(g("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new m(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=he.instance,i=_t(t.policies,o?.routeData.policies);return vr(i)(n,e)},"CompositeInboundPolicy");var Vc=s(async(n,e,t,r)=>{g("policy.inbound.curity-phantom-token-auth");let o=n.headers.get("Authorization");if(!o)return x.unauthorized(n,e,{detail:"No authorization header"});let i=Wc(o);if(!i)return x.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await ie(r,void 0,t),u=new re(a,e),c=await u.get(i);if(!c){let l=await F.fetch(t.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${t.clientId}:${t.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+i+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(i,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),x.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):x.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function Wc(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}s(Wc,"getToken");var Kc=s(async(n,e,t,r)=>(g("policy.inbound.firebase-jwt-auth"),X(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),we(n,e,{issuer:`https://securetoken.google.com/${t.projectId}`,audience:t.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var Jc=s(async(n,e,t)=>{g("policy.inbound.form-data-to-json");let r="application/x-www-form-urlencoded",o="multipart/form-data",i=n.headers.get("content-type")?.toLowerCase();if(!i||![o,r].includes(i))return t&&t.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):n;let a=await n.formData();if(t&&t.optionalHoneypotName&&a.get(t.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(n.headers);return c.set("content-type","application/json"),c.delete("content-length"),new te(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var yt="__unknown__",Xc=s(async(n,e,t,r)=>{g("policy.inbound.geo-filter");let o={allow:{countries:wt(t.allow?.countries,"allow.countries",r),regionCodes:wt(t.allow?.regionCodes,"allow.regionCode",r),asns:wt(t.allow?.asns,"allow.asOrganization",r)},block:{countries:wt(t.block?.countries,"block.countries",r),regionCodes:wt(t.block?.regionCodes,"block.regionCode",r),asns:wt(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??yt,a=e.incomingRequestProperties.regionCode?.toLowerCase()??yt,u=e.incomingRequestProperties.asn?.toString()??yt,c=o.ignoreUnknown&&i===yt,l=o.ignoreUnknown&&a===yt,d=o.ignoreUnknown&&u===yt,p=o.allow.countries,h=o.allow.regionCodes,y=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||h.length>0&&!h.includes(a)&&!l||y.length>0&&!y.includes(u)&&!d)return bt(n,e,r,i,a,u);let O=o.block.countries,P=o.block.regionCodes,C=o.block.asns;return O.length>0&&O.includes(i)&&!c||P.length>0&&P.includes(a)&&!l||C.length>0&&C.includes(u)&&!d?bt(n,e,r,i,a,u):n},"GeoFilterInboundPolicy");function bt(n,e,t,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),x.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(bt,"blockedResponse");function wt(n,e,t){if(typeof n=="string")return n.split(",").map(r=>r.trim().toLowerCase());if(typeof n>"u")return[];if(Array.isArray(n))return n.map(r=>r.trim().toLowerCase());throw new m(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}s(wt,"toLowerStringArray");var Yc=s(async(n,e,t)=>{g("policy.inbound.jwt-scope-validation");let r=n.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(u=>i.includes(u)),"scopeChecker")(r,t.scopes)){let i={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(i),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var Qc=s(async(n,e,t,r)=>{g("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return Ho(r,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return Ho(r,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(i.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(h=>{a.push({responseName:u,contentName:l,exampleName:h,exampleValue:d[h]})})})}),a=a.filter(u=>!(t.responsePrefixFilter&&!u.responseName.startsWith(t.responsePrefixFilter)||t.contentType&&u.contentName!==t.contentType||t.exampleName&&u.exampleName!==t.exampleName)),t.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return Ks(a[u])}else return a.length>0?Ks(a[0]):Ho(r,n,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function Ks(n){let e=JSON.stringify(n.exampleValue,null,2),t=new Headers;switch(t.set("Content-Type",n.contentName),n.responseName){case"1XX":return new Response(e,{status:100,headers:t});case"2XX":return new Response(e,{status:200,headers:t});case"3XX":return new Response(e,{status:300,headers:t});case"4XX":return new Response(e,{status:400,headers:t});case"5XX":case"default":return new Response(e,{status:500,headers:t});default:return new Response(e,{status:Number(n.responseName),headers:t})}}s(Ks,"generateResponse");var Ho=s((n,e,t,r)=>{let o=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${r}`;return x.internalServerError(e,t,{detail:o})},"getProblemDetailResponse");var el="Incoming",tl={logRequestBody:!0,logResponseBody:!0};function Js(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}s(Js,"headersToObject");function Xs(){return new Date().toISOString()}s(Xs,"timestamp");var Uo=new WeakMap,nl={};function rl(n,e){let t=Uo.get(n);t||(t=nl);let r=Object.assign({...t},e);Uo.set(n,r)}s(rl,"setMoesifContext");async function Ys(n,e){let t=n.headers.get("content-type");if(t&&t.indexOf("json")!==-1)try{return await n.clone().json()}catch(o){e.log.error(o)}let r=await n.clone().text();return e.log.debug({textBody:r}),r}s(Ys,"readBody");var ol={},qo;function Qs(){if(!qo)throw new k("Invalid State - no _lastLogger");return qo}s(Qs,"getLastLogger");function il(n){let e=ol[n];return e||(e=new J("moesif-inbound",100,async t=>{let r=JSON.stringify(t);Qs().debug("posting",r);let o=await F.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||Qs().error({status:o.status,body:await o.text()})})),e}s(il,"getDispatcher");async function sl(n,e,t,r){g("policy.inbound.moesif-analytics"),qo=e.log;let o=Xs(),i=Object.assign(tl,t);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await Ys(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=il(i.applicationId),d=n.headers.get("true-client-ip"),p=Uo.get(e)??{},h={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Js(n.headers)},y=i.logResponseBody?await Ys(u,e):void 0,O={time:Xs(),status:u.status,headers:Js(u.headers),body:y},P={request:h,response:O,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:el};l.enqueue(P),e.waitUntil(l.waitUntilFlushed())}),n}s(sl,"MoesifInboundPolicy");async function ea(n,e,t,r){let o=Y.getLogger(n),{authApiJWT:i,meteringServiceUrl:a}=f.instance,u;try{let l=await F.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":n.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription`,l)}let c=u&&u.data&&u.data.length>0?u.data:void 0;return c&&c.length>1?c.sort((d,p)=>d.createdOn>p.createdOn?-1:1)[0]:c&&c[0]}s(ea,"loadSubscription");async function ta(n,e,t,r,o){let{authApiJWT:i,meteringServiceUrl:a}=f.instance,u=Y.getLogger(n);try{let c=await F.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":n.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`,c)}}s(ta,"consumeSubcriptionQuotas");var al=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function Nn(n,e){try{let t=[];for(let r in n)typeof n[r]!="number"&&!(Number.isInteger(n[r])&&/^-?\d+$/.test(n[r].toString()))&&t.push(r);if(t.length>0)throw new m(t.length>1?`The values found in these properties are not integers : ${t.join(", ")}`:`The value in property '${t[0]}' is not an integer`)}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}s(Nn,"validateMeters");function na(n,e){if(n)try{if(n.length===0)throw new m("Must set valid subscription statuses");let t=et(n),r=[];for(let o of t)al.has(o)||r.push(o);if(r.length>0)throw new m(`Found the following invalid statuses: ${r.join(", ")}`);return n}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}s(na,"parseAllowedSubscriptionStatuses");function ra(n,e){let t={},r={};for(let o in e)n.hasOwnProperty(o)?t[o]=e[o]:r[o]=e[o];return{metersInSubscription:t,metersNotInSubscription:r}}s(ra,"compareMeters");var Zo=class extends de{static{s(this,"MonetizationInboundPolicy")}static getSubscription(e){return ge.get(e,Tt)}static setMeters(e,t){Nn(t,"setMeters"),ge.set(e,Kt,t)}constructor(e,t){super(e,t),g("policy.inbound.monetization")}async handler(e,t){X(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let r=this.options.allowRequestsOverQuota??!1,o=st(this.options.meterOnStatusCodes),i=ge.get(t,Kt),a={...this.options.meters,...i};Nn(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=na(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(P,C,H)=>{let _=ge.get(H,Tt);if((this.options.allowRequestsWithoutSubscription??!1)&&!_){H.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(Re.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let q=ge.get(H,Kt),$={...this.options.meters,...q};if(Nn($,this.policyName),o.includes(P.status)&&_&&$){H.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${_.id}' with meters '${JSON.stringify($)} on response status '${P.status}'`);let{metersInSubscription:E,metersNotInSubscription:M}=ra(_.meters,$);if(M&&Object.keys(M).length>0){let G=Object.keys(M);H.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${G}'`)}await ta(H,_.id,this.policyName,this.options.bucketId,E)}});let l=e.user;if(!l)return u?e:x.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(Re.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await ea(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:x.unauthorized(e,t,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return t.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),x.unauthorized(e,t,{detail:"No valid subscription found"});c.includes(p.status)&&(t.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),ge.set(t,Tt,p));let h=ge.get(t,Tt);if(!h)return u?e:(t.log.warn("Subscription is not available for user"),x.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(h&&Object.keys(h.meters).length===0)return t.log.error(`Quota is not set up for subscription '${h.id}'`),x.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let O=Object.keys(a).filter(P=>!Object.keys(h.meters).includes(P));if(O.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${O.join(", ")}`),x.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${O.join(", ")}`,title:"Quota Exceeded"});for(let P of Object.keys(a))if(h.meters[P].available<=0&&!r)return x.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${P}'`,title:"Quota Exceeded"});return e}};async function Dn(n,e){let t=new URLSearchParams({client_id:n.clientId,client_secret:n.clientSecret,grant_type:"client_credentials"});n.scope&&t.append("scope",n.scope),n.audience&&t.append("audience",n.audience);let r=await fe({retries:n.retries?.maxRetries??3,retryDelayMs:n.retries?.delayMs??10},n.tokenEndpointUrl,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let i=await r.text();e.log.error(`Error getting token from identity provider. Status: ${r.status}`,i)}catch{}throw new k("Error getting token from identity provider.")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new k("Response returned from identity provider is not in the expected format.")}s(Dn,"getClientCredentialsAccessToken");var Rt=class extends Error{constructor(t,r,o){super(r,o);this.code=t}static{s(this,"OpenFGAError")}},Mn=class{static{s(this,"BaseOpenFGAClient")}apiUrl;storeId;authorizationModelId;constructor(e){this.apiUrl=e.apiUrl,this.storeId=e.storeId,this.authorizationModelId=e.authorizationModelId}getStoreId(e={},t=!1){let r=e?.storeId||this.storeId;if(!t&&!r)throw new Error("storeId is required");return r}getAuthorizationModelId(e={}){return e?.authorizationModelId||this.authorizationModelId}async get(e,t){return this.fetch(e,"GET",t)}async put(e,t,r){return this.fetch(e,"PUT",r,t)}post(e,t,r){return this.fetch(e,"POST",r,t)}async fetch(e,t,r,o){let i=new Headers(r.headers||{});i.set("Content-Type","application/json"),i.set("Accept","application/json"),i.set("User-Agent",f.instance.systemUserAgent);let a=`${this.apiUrl}${e}`,u=new Request(a,{method:t,headers:i,body:o?JSON.stringify(o):void 0}),c=await F.fetch(u);if(c.status!==200){let l;try{l=await c.json()}catch{}throw!l||!l.code||!l.message?new Rt("unknown",`Unknown error. Status: ${c.status}`):new Rt(l.code,l.message)}return c.json()}};function Bt(n,e,t){!n[e]&&t&&(n[e]=t)}s(Bt,"setHeaderIfNotSet");var oa="X-OpenFGA-Client-Method",ia="X-OpenFGA-Client-Bulk-Request-Id",Gt=class extends Mn{static{s(this,"OpenFGAClient")}async check(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/check`,{tuple_key:{user:e.user,relation:e.relation,object:e.object},context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]},authorization_model_id:this.getAuthorizationModelId(t)},t)}async batchCheck(e,t={}){let{headers:r={}}=t;return Bt(r,oa,"BatchCheck"),Bt(r,ia,crypto.randomUUID()),{responses:await Promise.all(e.map(async i=>this.check(i,Object.assign({},t,r)).then(a=>(a._request=i,a)).catch(a=>{if(a instanceof Rt)throw a;return{allowed:void 0,error:a,_request:i}})))}}async expand(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/expand`,{authorization_model_id:this.getAuthorizationModelId(t),tuple_key:e},t)}async listObjects(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-objects`,{authorization_model_id:this.getAuthorizationModelId(t),user:e.user,relation:e.relation,type:e.type,context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]}},t)}async listRelations(e,t={}){let{user:r,object:o,relations:i,contextualTuples:a,context:u}=e,{headers:c={}}=t;if(Bt(c,oa,"ListRelations"),Bt(c,ia,crypto.randomUUID()),!i?.length)throw new Error("When calling listRelations, at least one relation must be passed in the relations field");let l=await this.batchCheck(i.map(p=>({user:r,relation:p,object:o,contextualTuples:a,context:u})),Object.assign({},t,c)),d=l.responses.find(p=>p.error);if(d)throw d.error;return{relations:l.responses.filter(p=>p.allowed).map(p=>p._request.relation)}}async listUsers(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-users`,{authorization_model_id:this.getAuthorizationModelId(t),relation:e.relation,object:e.object,user_filters:e.user_filters,context:e.context,contextual_tuples:e.contextualTuples||[]},t)}};var sa=Symbol("openfga-authz-context-data"),Pt=class extends de{static{s(this,"BaseOpenFGAAuthZInboundPolicy")}client;authorizer;cache;static setContextChecks(e,t){let r=Array.isArray(t)?t:[t];ge.set(e,sa,r)}constructor(e,t){if(super(e,t),X(e,t).required("apiUrl","string").optional("storeId","string").optional("authorizationModelId","string"),!e.credentials)throw new m(`${this.policyType} '${this.policyName}' - The 'credentials' option is required.`);if(e.credentials.method==="client-credentials")X(e.credentials,t).required("clientId","string").required("clientSecret","string").required("oauthTokenEndpointUrl","string").optional("apiAudience","string");else if(e.credentials.method==="api-token")X(e.credentials,t).required("token","string").optional("headerName","string").optional("headerValuePrefix","string");else if(e.credentials.method==="header")X(e.credentials,t).optional("headerName","string");else if(e.credentials.method!=="none")throw new m(`${this.policyType} '${this.policyName}' - The 'credentials.type' option is invalid. It must be set to either 'none', 'api-token', 'client-credentials', or 'header'.`);this.authorizer=this.getAuthorizer(e.credentials),this.client=new Gt({apiUrl:e.apiUrl,storeId:e.storeId,authorizationModelId:e.authorizationModelId})}async handler(e,t){if(!this.cache){let a=await ie(this.policyName,void 0,this.options);this.cache=new re(a,t)}let r=s(a=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=ge.get(t,sa);if(!o||o.length===0)throw new k(`${this.policyType} '${this.policyName}' - No checks found in the context.`);let i=await this.authorizer(e,t);try{t.log.debug("OpenFGA checks",o);let a=await this.client.batchCheck(o,{headers:i});return t.log.debug("OpenFGA Response",a),a.responses.every(u=>u.allowed)?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling OpenFGA service`,a),x.internalServerError(e,t)}}getAuthorizer(e){if(e.method==="none")return async()=>({});if(e.method==="header")return async t=>{let r=e.headerName??"Authorization",o=t.headers.get(r);if(!o)throw new W(`${this.policyType} '${this.policyName}' - The header '${r}' is missing.`);return{[r]:o}};if(e.method==="api-token")return async()=>({[e.headerName??"Authorization"]:`${e.headerValuePrefix??"Bearer "} ${e.token}`});if(e.method==="client-credentials")return async(t,r)=>{let o=await this.cache?.get("client_credentials_token");if(o)return{Authorization:`Bearer ${o}`};let i=await Dn({tokenEndpointUrl:e.oauthTokenEndpointUrl,clientId:e.clientId,clientSecret:e.clientSecret,audience:e.apiAudience},r);return this.cache?.put("client_credentials_token",i.access_token,i.expires_in),{Authorization:`Bearer ${i.access_token}`}};throw new k("Invalid state for credentials method is not valid. This should not happen.")}};var aa=["us1","eu1","au1"],Fo=class extends Pt{static{s(this,"OktaFGAAuthZInboundPolicy")}constructor(e,t){if(!aa.includes(e.region))throw new m(`OktaFGAAuthZInboundPolicy '${t}' - The 'region' option is invalid. Must be one of ${aa.join(", ")}.`);let r={...e,apiUrl:`https://api.${e.region}.fga.dev`,credentials:{method:"client-credentials",oauthTokenEndpointUrl:"https://fga.us.auth0.com/oauth/token",clientId:e.credentials.clientId,clientSecret:e.credentials.clientSecret,apiAudience:`https://api.${e.region}.fga.dev/`}};super(r,t),g("policy.inbound.oktafga-authz")}};var ul=s(async(n,e,t,r)=>(g("policy.inbound.okta-jwt-auth"),we(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"OktaJwtInboundPolicy");var $o=class extends Pt{static{s(this,"OpenFGAAuthZInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.openfga-authz")}};import{importSPKI as cl}from"jose";var jo,ll=s(async(n,e,t,r)=>{if(g("policy.inbound.propel-auth-jwt-auth"),!jo)try{jo=await cl(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return we(n,e,{issuer:t.authUrl,secret:jo,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var pa=Ve(We());var ca=Ve(We());var ua=(0,ca.debug)("zuplo:policies:RateLimitInboundPolicy"),la=s(async(n,e,t,r)=>{let o=Y.getLogger(e),i=s(($,E)=>{let M={};return(!$||$==="retry-after")&&(M[ht]=E.toString()),x.tooManyRequests(n,e,void 0,M)},"rateLimited"),u=await gt(r,t)(n,e,r),c=u.key,l=u.requestsAllowed??t.requestsAllowed,d=u.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",h=ft(r,o),O=`rate-limit${f.instance.isTestMode?f.instance.build.BUILD_ID:""}/${r}/${c}`,P=await ie(r,void 0,t),C=new re(P,e),H=_n(O,d,h,e.requestId),_;s(async()=>{let $=await H;if($.count>l){let E=Date.now()+$.ttlSeconds*1e3;C.put(O,E,$.ttlSeconds),ua(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${O}' (async mode)`),_=i(p,$.ttlSeconds)}},"asyncCheck")();let q=await C.get(O);if(q!==void 0&&q>Date.now()){ua(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${O}' (async mode)`);let $=Math.round((q-Date.now())/1e3);return i(p,$)}return e.addResponseSendingHook(async $=>_??$),n},"AsyncRateLimitInboundPolicyImpl");var da=(0,pa.debug)("zuplo:policies:RateLimitInboundPolicy"),dl="strict",ma=s(async(n,e,t,r)=>{if(g("policy.inbound.rate-limit"),(t.mode??dl)==="async")return la(n,e,t,r);let i=Date.now(),a=Y.getLogger(e),u=s((l,d)=>{if(t.throwOnFailure)throw new W(l,{cause:d});a.error(l,d)},"throwOrLog"),c=s((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[ht]=d.toString()),x.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await gt(r,t)(n,e,r),p=d.key,h=d.requestsAllowed??t.requestsAllowed,y=d.timeWindowMinutes??t.timeWindowMinutes,O=t.headerMode??"retry-after",P=ft(r,a),H=`rate-limit${f.instance.isTestMode||f.instance.isWorkingCopy?f.instance.build.BUILD_ID:""}/${r}/${p}`,_=await _n(H,y,P,e.requestId);return _.count>h?(da(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${H}' (strict mode)`),c(O,_.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-i;da(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var zo;function ga(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}s(ga,"headersToNameValuePairs");function pl(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}s(pl,"queryToNameValueParis");function ml(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}s(ml,"parseIntOrUndefined");var fa={};async function gl(n,e,t,r){g("policy.inbound.readme-metrics");let o=new Date,i=Date.now();return zo||(zo={name:"zuplo",version:f.instance.build.ZUPLO_VERSION,comment:`zuplo/${f.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?Qe(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?Qe(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:f.instance.isWorkingCopy||f.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:zo,entries:[{startedDateTime:o.toISOString(),time:Date.now()-i,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:ga(n.headers),queryString:pl(n.query)},response:{status:a.status,statusText:a.statusText,headers:ga(a.headers),content:{size:ml(n.headers.get("content-length"))}}}]}}},d=fa[t.apiKey];if(!d){let p=t.apiKey;d=new J("readme-metering-inbound-policy",10,async h=>{try{let y=t.url??"https://metrics.readme.io/request",O=await F.fetch(y,{method:"POST",body:JSON.stringify(h),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});O.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${O.status}: '${await O.text()}'`)}catch(y){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${y.message}'`),y}}),fa[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}s(gl,"ReadmeMetricsInboundPolicy");var fl=s(async(n,e,t,r)=>{g("policy.inbound.remove-headers");let o=t?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new m(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(n.headers);return o.forEach(u=>{i.delete(u)}),new te(n,{headers:i})},"RemoveHeadersInboundPolicy");var hl=s(async(n,e,t,r,o)=>{g("policy.outbound.remove-headers");let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new m(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(n.headers);return i.forEach(c=>{a.delete(c)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var yl=s(async(n,e,t,r)=>{g("policy.inbound.remove-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length===0)throw new m(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(n.url);return o.forEach(u=>{i.searchParams.delete(u)}),new te(i.toString(),n)},"RemoveQueryParamsInboundPolicy");var bl=s(async(n,e,t,r)=>{g("policy.outbound.replace-string");let o=await n.text(),i=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(i,r.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var ha=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),wl=s(async(n,e,t)=>{g("policy.inbound.request-size-limit");let r=t.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(n.method))return n;let o=n.headers.get("content-length"),i=o!==null?parseInt(o):void 0;return i&&!isNaN(i)&&i>t.maxSizeInBytes?ha():i&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?ha():n},"RequestSizeLimitInboundPolicy");var It=s(n=>{let e=n.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),Et=s((n,e,t,r,o)=>{let i=[],a=!0,u=[];return n.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=Fn(t,r,o,c.name),p=he.instance.schemaValidator[d],h=p(e[c.name]),y=Bo(p.errors);h||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${y.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),Oe=s((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),Ae=s(n=>n==="log-only"||n==="reject-and-log","shouldLog"),ke=s(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),Bo=s(n=>n?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function ya(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(y){let O=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,P=x.badRequest(e,n,{detail:`${O}, see errors property for more details`,errors:`${y}`});if(Ae(t.validateBody)&&Oe(n,t.logLevel??"info",O,[r],y),ke(t.validateBody))return P}if(!e.headers.get("Content-Type")){let y=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,O=x.badRequest(e,n,{detail:y});return Ae(t.validateBody)&&Oe(n,t.logLevel??"info",y,[r],[y]),ke(t.validateBody)?O:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=$n(n.route.path,e.method,o),u=he.instance.schemaValidator[a];if(!u){let y=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,O=x.badRequest(e,n,{detail:y});return Ae(t.validateBody)&&Oe(n,t.logLevel??"info",y,[r],[y]),ke(t.validateBody)?O:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Bo(l),h=x.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(Ae(t.validateBody)&&Oe(n,t.logLevel??"info",d,[r],p),ke(t.validateBody))return h}s(ya,"handleBodyValidation");function ba(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=It(n),i=Et(o.filter(a=>a.location==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=x.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:i.errors});if(Ae(t.validateHeaders)&&Oe(n,t.logLevel??"info",a,i.invalidValues,i.errors),ke(t.validateHeaders))return u}}s(ba,"handleHeadersValidation");function wa(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=It(n),o=Et(r.filter(i=>i.location==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let i="Path parameters validation failed",a=x.badRequest(e,n,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Ae(t.validatePathParameters)&&Oe(n,t.logLevel??"info",i,o.invalidValues,o.errors),ke(t.validatePathParameters))return a}}s(wa,"handlePathParameterValidation");function Ra(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=It(n),o=Et(r.filter(i=>i.location==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let i="Query parameters validation failed",a=x.badRequest(e,n,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Ae(t.validateQueryParameters)&&Oe(n,t.logLevel??"info",i,o.invalidValues,o.errors),ke(t.validateQueryParameters))return a}}s(Ra,"handleQueryParameterValidation");var Pa=s(async(n,e,t)=>{g("policy.inbound.request-validation");let r=Ra(e,n,t);if(r!==void 0||(r=wa(e,n,t),r!==void 0)||(r=ba(e,n,t),r!==void 0))return r;let o=await ya(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),Rl=Pa;var Pl=s(async(n,e,t,r)=>{if(g("policy.inbound.require-origin"),t.origins===void 0||t.origins.length===0)throw new m(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof t.origins=="string"?t.origins.split(","):t.origins;o=o.map(a=>a.trim());let i=n.headers.get("origin");if(!i||!o.includes(i)){let a=t.failureDetail??"Forbidden";return x.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var Il=s(async(n,e,t)=>(g("policy.inbound.set-body"),new te(n,{body:t.body})),"SetBodyInboundPolicy");var El=s(async(n,e,t,r)=>{g("policy.inbound.set-headers");let o=t.headers;if(!o||!Array.isArray(o)||o.length==0)throw new m(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(n.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new te(n,{headers:i})},"SetHeadersInboundPolicy");var xl=s(async(n,e,t,r,o)=>{g("policy.outbound.set-headers");let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new m(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new m(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"SetHeadersOutboundPolicy");var Tl=s(async(n,e,t,r)=>{g("policy.inbound.set-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length==0)throw new m(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(n.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new te(i.toString(),n)},"SetQueryParamsInboundPolicy");var vl=s(async(n,e,t,r,o)=>{if(g("policy.outbound.set-status"),!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(n.body,{headers:n.headers,status:r.status,statusText:r.statusText??n.statusText})},"SetStatusOutboundPolicy");var Cl=s(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),Sl=s(async(n,e,t,r)=>{if(g("policy.inbound.sleep"),!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new m(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await Cl(t.sleepInMs),n},"SleepInboundPolicy");var Ol=s(async(n,e,t,r)=>{g("policy.inbound.supabase-jwt-auth"),X(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},i=await we(n,e,o,r);if(i instanceof Response)return i;if(!(i instanceof te))throw new W("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return i;let u=n.user?.data.app_metadata;if(!u)throw new k(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?x.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var Al=s(async(n,e,t,r)=>{g("policy.inbound.upstream-azure-ad-service-auth"),X(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await ie(r,void 0,t),i=new re(o,e),a=await i.get(r);if(!a){let u=await kl(t,e);i.put(r,u.access_token,u.expires_in-(t.expirationOffsetSeconds??300)),a=u.access_token}return n.headers.set("Authorization",`Bearer ${a}`),n},"UpstreamAzureAdServiceAuthInboundPolicy");async function kl(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await fe({retries:n.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${n.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new k("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new k("Response returned from Azure AD is not in the expected format.")}s(kl,"getAccessToken");var Ia="https://accounts.google.com/o/oauth2/token",Go,Ll=s(async(n,e,t,r)=>{g("policy.inbound.upstream-firebase-admin-auth"),X(t,r).required("serviceAccountJson","string"),Go||(Go=await xe.init(t.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},i=await ie(r,void 0,t),a=new re(i,e),u=await a.get(r);if(!u){let c=await _e({serviceAccount:Go,audience:Ia,payload:o}),l=await dn(Ia,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new k("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var _l="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Nl=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Vo,Dl=s(async(n,e,t,r)=>{if(g("policy.inbound.upstream-firebase-user-auth"),X(t,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!t.userId&&!t.userIdPropertyPath)throw new m(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof t.developerClaims<"u"){for(let p in t.developerClaims)if(Object.prototype.hasOwnProperty.call(t.developerClaims,p)){if(Nl.indexOf(p)!==-1)throw new m(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}Vo||(Vo=await xe.init(t.serviceAccountJson));let i=t.userId;if(!i&&!t.userIdPropertyPath){if(!n.user)throw new k("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");i=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new k(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=Qe(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new k(`Unable to determine user from for the policy ${r}`);let a=await ie(r,void 0,t),u=new re(a,e),c={uid:i,claims:o},l=await Tn(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await _e({serviceAccount:Vo,audience:_l,payload:c}),h=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,y=await as(h,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!y.idToken)throw new k("Invalid token response from Firebase");d=y.idToken,u.put(l,d,(y.expiresIn?parseInt(y.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var Vt=class{static{s(this,"ZuploServices")}static async getIDToken(e,t){let r=new re("0c13603a-a19f-4f03-a04a-50aa393f7ffa-zuplo-tokens",e),o=await ie("zuplo-token",void 0,t),i=await r.get(o);if(i)return i;let{authClientId:a,authClientSecret:u,developerApiUrl:c,zuploClientAuthBucketId:l}=f.instance;if(!a||!u)throw new k("Zuplo service authentication is not enabled for this deployment. Contact support assistance.");let d=await Dn({tokenEndpointUrl:`${c}/v1/client-auth/${l}/oauth/token`,clientId:a,clientSecret:u,audience:t?.audience},e);return r.put(o,d.access_token,d.expires_in-300),d.access_token}};var Ea="workload-access-token",xa="service-account-id-token",Wo=class extends de{static{s(this,"UpstreamGcpFederatedAuthInboundPolicy")}cacheName;normalizedWorkloadIdentityProvider;constructor(e,t){super(e,t),g("policy.inbound.upstream-gcp-federated-auth"),X(e,t).required("audience","string").required("serviceAccountEmail","string").required("workloadIdentityProvider","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number").optional("useMemoryCacheOnly","boolean").optional("tokenLifetime","number"),e.workloadIdentityProvider.startsWith("https://iam.googleapis.com/")?this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider.replace("https://iam.googleapis.com/",""):this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider}async handler(e,t){this.cacheName||(this.cacheName=await ie(this.policyName,void 0,this.options));let r;this.options.useMemoryCacheOnly?r=new Ze(this.cacheName):r=new re(this.cacheName,t);let o=await r.get(Ea);if(!o){let a=`https://iam.googleapis.com/${this.normalizedWorkloadIdentityProvider}`,u=await Vt.getIDToken(t,{audience:a}),c=await is(this.normalizedWorkloadIdentityProvider,u,{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!c.access_token||!c.expires_in)throw new k("Invalid token response from GCP");o=c.access_token,r.put(Ea,o,c.expires_in-(this.options.expirationOffsetSeconds??300))}let i=await r.get(xa);if(!i){let a=await ss({serviceAccountEmailOrIdentifier:this.options.serviceAccountEmail,audience:this.options.audience,accessToken:o},{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!a.token)throw new k("Invalid token response from GCP");i=a.token,r.put(xa,o,3600-(this.options.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${i}`),e}};var Ko,Ml=s(async(n,e,t,r)=>{g("policy.inbound.upstream-gcp-jwt"),X(t,r).required("audience","string").required("serviceAccountJson","string"),Ko||(Ko=await xe.init(t.serviceAccountJson));let o=await _e({serviceAccount:Ko,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var Ta="https://www.googleapis.com/oauth2/v4/token",Jo,Hl=s(async(n,e,t,r)=>{g("policy.inbound.upstream-gcp-service-auth"),X(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Jo||(Jo=await xe.init(t.serviceAccountJson));let o={};if(t.scopes&&t.audience)throw new m("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let c=et(t.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof m?new m(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}t.audience&&(o.target_audience=`${t.audience}`);let i=await ie(r,void 0,t),a;t.useMemoryCacheOnly?a=new Ze(i):a=new re(i,e);let u=await a.get(r);if(!u){let c=await _e({serviceAccount:Jo,audience:Ta,payload:o}),l=await dn(Ta,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new k("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new k("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var Ul=s(async(n,e,t)=>{g("policy.inbound.validate-json-schema");let r=n.clone(),o;try{o=await r.json()}catch{return x.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator(o))return n;let{errors:a}=t.validator;if(!a)throw new W("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return x.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var va=s(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=s((P,C)=>e(P,"name",{value:C,configurable:!0}),"__name"),o=s((P,C)=>s(function(){return C||(0,P[t(P)[0]])((C={exports:{}}).exports,C),C.exports},"__require"),"__commonJS"),i=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(P){var C={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(_,j){return j},attributeValueProcessor:function(_,j){return j},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(_,j,q){return _}},H=r(function(_){return Object.assign({},C,_)},"buildOptions");P.buildOptions=H,P.defaultOptions=C}}),a=o({"node_modules/fast-xml-parser/src/util.js"(P){"use strict";var C=":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",H=C+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",_="["+C+"]["+H+"]*",j=new RegExp("^"+_+"$"),q=r(function(E,M){let G=[],V=M.exec(E);for(;V;){let v=[];v.startIndex=M.lastIndex-V[0].length;let T=V.length;for(let U=0;U<T;U++)v.push(V[U]);G.push(v),V=M.exec(E)}return G},"getAllMatches"),$=r(function(E){let M=j.exec(E);return!(M===null||typeof M>"u")},"isName");P.isExist=function(E){return typeof E<"u"},P.isEmptyObject=function(E){return Object.keys(E).length===0},P.merge=function(E,M,G){if(M){let V=Object.keys(M),v=V.length;for(let T=0;T<v;T++)G==="strict"?E[V[T]]=[M[V[T]]]:E[V[T]]=M[V[T]]}},P.getValue=function(E){return P.isExist(E)?E:""},P.isName=$,P.getAllMatches=q,P.nameRegexp=_}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(P,C){"use strict";var H=class{static{s(this,"XmlNode")}static{r(this,"XmlNode")}constructor(_){this.tagname=_,this.child=[],this[":@"]={}}add(_,j){_==="__proto__"&&(_="#__proto__"),this.child.push({[_]:j})}addChild(_){_.tagname==="__proto__"&&(_.tagname="#__proto__"),_[":@"]&&Object.keys(_[":@"]).length>0?this.child.push({[_.tagname]:_.child,":@":_[":@"]}):this.child.push({[_.tagname]:_.child})}};C.exports=H}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(P,C){var H=a();function _(v,T){let U={};if(v[T+3]==="O"&&v[T+4]==="C"&&v[T+5]==="T"&&v[T+6]==="Y"&&v[T+7]==="P"&&v[T+8]==="E"){T=T+9;let ce=1,K=!1,Q=!1,ve="";for(;T<v.length;T++)if(v[T]==="<"&&!Q){if(K&&$(v,T))T+=7,[entityName,val,T]=j(v,T+1),val.indexOf("&")===-1&&(U[V(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(K&&E(v,T))T+=8;else if(K&&M(v,T))T+=8;else if(K&&G(v,T))T+=9;else if(q)Q=!0;else throw new Error("Invalid DOCTYPE");ce++,ve=""}else if(v[T]===">"){if(Q?v[T-1]==="-"&&v[T-2]==="-"&&(Q=!1,ce--):ce--,ce===0)break}else v[T]==="["?K=!0:ve+=v[T];if(ce!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:U,i:T}}s(_,"readDocType"),r(_,"readDocType");function j(v,T){let U="";for(;T<v.length&&v[T]!=="'"&&v[T]!=='"';T++)U+=v[T];if(U=U.trim(),U.indexOf(" ")!==-1)throw new Error("External entites are not supported");let ce=v[T++],K="";for(;T<v.length&&v[T]!==ce;T++)K+=v[T];return[U,K,T]}s(j,"readEntityExp"),r(j,"readEntityExp");function q(v,T){return v[T+1]==="!"&&v[T+2]==="-"&&v[T+3]==="-"}s(q,"isComment"),r(q,"isComment");function $(v,T){return v[T+1]==="!"&&v[T+2]==="E"&&v[T+3]==="N"&&v[T+4]==="T"&&v[T+5]==="I"&&v[T+6]==="T"&&v[T+7]==="Y"}s($,"isEntity"),r($,"isEntity");function E(v,T){return v[T+1]==="!"&&v[T+2]==="E"&&v[T+3]==="L"&&v[T+4]==="E"&&v[T+5]==="M"&&v[T+6]==="E"&&v[T+7]==="N"&&v[T+8]==="T"}s(E,"isElement"),r(E,"isElement");function M(v,T){return v[T+1]==="!"&&v[T+2]==="A"&&v[T+3]==="T"&&v[T+4]==="T"&&v[T+5]==="L"&&v[T+6]==="I"&&v[T+7]==="S"&&v[T+8]==="T"}s(M,"isAttlist"),r(M,"isAttlist");function G(v,T){return v[T+1]==="!"&&v[T+2]==="N"&&v[T+3]==="O"&&v[T+4]==="T"&&v[T+5]==="A"&&v[T+6]==="T"&&v[T+7]==="I"&&v[T+8]==="O"&&v[T+9]==="N"}s(G,"isNotation"),r(G,"isNotation");function V(v){if(H.isName(v))return v;throw new Error(`Invalid entity name ${v}`)}s(V,"validateEntityName"),r(V,"validateEntityName"),C.exports=_}}),l=o({"../../node_modules/strnum/strnum.js"(P,C){var H=/^[-+]?0x[a-fA-F0-9]+$/,_=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var j={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function q(E,M={}){if(M=Object.assign({},j,M),!E||typeof E!="string")return E;let G=E.trim();if(M.skipLike!==void 0&&M.skipLike.test(G))return E;if(M.hex&&H.test(G))return Number.parseInt(G,16);{let V=_.exec(G);if(V){let v=V[1],T=V[2],U=$(V[3]),ce=V[4]||V[6];if(!M.leadingZeros&&T.length>0&&v&&G[2]!==".")return E;if(!M.leadingZeros&&T.length>0&&!v&&G[1]!==".")return E;{let K=Number(G),Q=""+K;return Q.search(/[eE]/)!==-1||ce?M.eNotation?K:E:G.indexOf(".")!==-1?Q==="0"&&U===""||Q===U||v&&Q==="-"+U?K:E:T?U===Q||v+U===Q?K:E:G===Q||G===v+Q?K:E}}else return E}}s(q,"toNumber"),r(q,"toNumber");function $(E){return E&&E.indexOf(".")!==-1&&(E=E.replace(/0+$/,""),E==="."?E="0":E[0]==="."?E="0"+E:E[E.length-1]==="."&&(E=E.substr(0,E.length-1))),E}s($,"trimZeros"),r($,"trimZeros"),C.exports=q}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(P,C){"use strict";var H=a(),_=u(),j=c(),q=l(),$=class{static{s(this,"OrderedObjParser")}static{r(this,"OrderedObjParser")}constructor(R){this.options=R,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(I,A)=>String.fromCharCode(Number.parseInt(A,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(I,A)=>String.fromCharCode(Number.parseInt(A,16))}},this.addExternalEntities=E,this.parseXml=T,this.parseTextData=M,this.resolveNameSpace=G,this.buildAttributesMap=v,this.isItStopNode=Q,this.replaceEntitiesValue=ce,this.readStopNodeData=B,this.saveTextToParentTag=K,this.addChild=U}};function E(R){let I=Object.keys(R);for(let A=0;A<I.length;A++){let z=I[A];this.lastEntities[z]={regex:new RegExp("&"+z+";","g"),val:R[z]}}}s(E,"addExternalEntities"),r(E,"addExternalEntities");function M(R,I,A,z,L,N,ee){if(R!==void 0&&(this.options.trimValues&&!z&&(R=R.trim()),R.length>0)){ee||(R=this.replaceEntitiesValue(R));let Z=this.options.tagValueProcessor(I,R,A,L,N);return Z==null?R:typeof Z!=typeof R||Z!==R?Z:this.options.trimValues?le(R,this.options.parseTagValue,this.options.numberParseOptions):R.trim()===R?le(R,this.options.parseTagValue,this.options.numberParseOptions):R}}s(M,"parseTextData"),r(M,"parseTextData");function G(R){if(this.options.removeNSPrefix){let I=R.split(":"),A=R.charAt(0)==="/"?"/":"";if(I[0]==="xmlns")return"";I.length===2&&(R=A+I[1])}return R}s(G,"resolveNameSpace"),r(G,"resolveNameSpace");var V=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function v(R,I,A){if(!this.options.ignoreAttributes&&typeof R=="string"){let z=H.getAllMatches(R,V),L=z.length,N={};for(let ee=0;ee<L;ee++){let Z=this.resolveNameSpace(z[ee][1]),D=z[ee][4],se=this.options.attributeNamePrefix+Z;if(Z.length)if(this.options.transformAttributeName&&(se=this.options.transformAttributeName(se)),se==="__proto__"&&(se="#__proto__"),D!==void 0){this.options.trimValues&&(D=D.trim()),D=this.replaceEntitiesValue(D);let ne=this.options.attributeValueProcessor(Z,D,I);ne==null?N[se]=D:typeof ne!=typeof D||ne!==D?N[se]=ne:N[se]=le(D,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(N[se]=!0)}if(!Object.keys(N).length)return;if(this.options.attributesGroupName){let ee={};return ee[this.options.attributesGroupName]=N,ee}return N}}s(v,"buildAttributesMap"),r(v,"buildAttributesMap");var T=r(function(R){R=R.replace(/\r\n?/g,`
|
|
62
|
-
`);let I=new _("!xml"),A=I,z="",L="";for(let N=0;N<R.length;N++)if(R[N]==="<")if(R[N+1]==="/"){let Z=b(R,">",N,"Closing Tag is not closed."),D=R.substring(N+2,Z).trim();if(this.options.removeNSPrefix){let Se=D.indexOf(":");Se!==-1&&(D=D.substr(Se+1))}this.options.transformTagName&&(D=this.options.transformTagName(D)),A&&(z=this.saveTextToParentTag(z,A,L));let se=L.substring(L.lastIndexOf(".")+1);if(D&&this.options.unpairedTags.indexOf(D)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${D}>`);let ne=0;se&&this.options.unpairedTags.indexOf(se)!==-1?(ne=L.lastIndexOf(".",L.lastIndexOf(".")-1),this.tagsNodeStack.pop()):ne=L.lastIndexOf("."),L=L.substring(0,ne),A=this.tagsNodeStack.pop(),z="",N=Z}else if(R[N+1]==="?"){let Z=S(R,N,!1,"?>");if(!Z)throw new Error("Pi Tag is not closed.");if(z=this.saveTextToParentTag(z,A,L),!(this.options.ignoreDeclaration&&Z.tagName==="?xml"||this.options.ignorePiTags)){let D=new _(Z.tagName);D.add(this.options.textNodeName,""),Z.tagName!==Z.tagExp&&Z.attrExpPresent&&(D[":@"]=this.buildAttributesMap(Z.tagExp,L,Z.tagName)),this.addChild(A,D,L)}N=Z.closeIndex+1}else if(R.substr(N+1,3)==="!--"){let Z=b(R,"-->",N+4,"Comment is not closed.");if(this.options.commentPropName){let D=R.substring(N+4,Z-2);z=this.saveTextToParentTag(z,A,L),A.add(this.options.commentPropName,[{[this.options.textNodeName]:D}])}N=Z}else if(R.substr(N+1,2)==="!D"){let Z=j(R,N);this.docTypeEntities=Z.entities,N=Z.i}else if(R.substr(N+1,2)==="!["){let Z=b(R,"]]>",N,"CDATA is not closed.")-2,D=R.substring(N+9,Z);z=this.saveTextToParentTag(z,A,L);let se=this.parseTextData(D,A.tagname,L,!0,!1,!0,!0);se==null&&(se=""),this.options.cdataPropName?A.add(this.options.cdataPropName,[{[this.options.textNodeName]:D}]):A.add(this.options.textNodeName,se),N=Z+2}else{let Z=S(R,N,this.options.removeNSPrefix),D=Z.tagName,se=Z.rawTagName,ne=Z.tagExp,Se=Z.attrExpPresent,oi=Z.closeIndex;this.options.transformTagName&&(D=this.options.transformTagName(D)),A&&z&&A.tagname!=="!xml"&&(z=this.saveTextToParentTag(z,A,L,!1));let ii=A;if(ii&&this.options.unpairedTags.indexOf(ii.tagname)!==-1&&(A=this.tagsNodeStack.pop(),L=L.substring(0,L.lastIndexOf("."))),D!==I.tagname&&(L+=L?"."+D:D),this.isItStopNode(this.options.stopNodes,L,D)){let Ce="";if(ne.length>0&&ne.lastIndexOf("/")===ne.length-1)N=Z.closeIndex;else if(this.options.unpairedTags.indexOf(D)!==-1)N=Z.closeIndex;else{let Zn=this.readStopNodeData(R,se,oi+1);if(!Zn)throw new Error(`Unexpected end of ${se}`);N=Zn.i,Ce=Zn.tagContent}let qn=new _(D);D!==ne&&Se&&(qn[":@"]=this.buildAttributesMap(ne,L,D)),Ce&&(Ce=this.parseTextData(Ce,D,L,!0,Se,!0,!0)),L=L.substr(0,L.lastIndexOf(".")),qn.add(this.options.textNodeName,Ce),this.addChild(A,qn,L)}else{if(ne.length>0&&ne.lastIndexOf("/")===ne.length-1){D[D.length-1]==="/"?(D=D.substr(0,D.length-1),L=L.substr(0,L.length-1),ne=D):ne=ne.substr(0,ne.length-1),this.options.transformTagName&&(D=this.options.transformTagName(D));let Ce=new _(D);D!==ne&&Se&&(Ce[":@"]=this.buildAttributesMap(ne,L,D)),this.addChild(A,Ce,L),L=L.substr(0,L.lastIndexOf("."))}else{let Ce=new _(D);this.tagsNodeStack.push(A),D!==ne&&Se&&(Ce[":@"]=this.buildAttributesMap(ne,L,D)),this.addChild(A,Ce,L),A=Ce}z="",N=oi}}else z+=R[N];return I.child},"parseXml");function U(R,I,A){let z=this.options.updateTag(I.tagname,A,I[":@"]);z===!1||(typeof z=="string"&&(I.tagname=z),R.addChild(I))}s(U,"addChild"),r(U,"addChild");var ce=r(function(R){if(this.options.processEntities){for(let I in this.docTypeEntities){let A=this.docTypeEntities[I];R=R.replace(A.regx,A.val)}for(let I in this.lastEntities){let A=this.lastEntities[I];R=R.replace(A.regex,A.val)}if(this.options.htmlEntities)for(let I in this.htmlEntities){let A=this.htmlEntities[I];R=R.replace(A.regex,A.val)}R=R.replace(this.ampEntity.regex,this.ampEntity.val)}return R},"replaceEntitiesValue");function K(R,I,A,z){return R&&(z===void 0&&(z=Object.keys(I.child).length===0),R=this.parseTextData(R,I.tagname,A,!1,I[":@"]?Object.keys(I[":@"]).length!==0:!1,z),R!==void 0&&R!==""&&I.add(this.options.textNodeName,R),R=""),R}s(K,"saveTextToParentTag"),r(K,"saveTextToParentTag");function Q(R,I,A){let z="*."+A;for(let L in R){let N=R[L];if(z===N||I===N)return!0}return!1}s(Q,"isItStopNode"),r(Q,"isItStopNode");function ve(R,I,A=">"){let z,L="";for(let N=I;N<R.length;N++){let ee=R[N];if(z)ee===z&&(z="");else if(ee==='"'||ee==="'")z=ee;else if(ee===A[0])if(A[1]){if(R[N+1]===A[1])return{data:L,index:N}}else return{data:L,index:N};else ee===" "&&(ee=" ");L+=ee}}s(ve,"tagExpWithClosingIndex"),r(ve,"tagExpWithClosingIndex");function b(R,I,A,z){let L=R.indexOf(I,A);if(L===-1)throw new Error(z);return L+I.length-1}s(b,"findClosingIndex"),r(b,"findClosingIndex");function S(R,I,A,z=">"){let L=ve(R,I+1,z);if(!L)return;let N=L.data,ee=L.index,Z=N.search(/\s/),D=N,se=!0;Z!==-1&&(D=N.substring(0,Z),N=N.substring(Z+1).trimStart());let ne=D;if(A){let Se=D.indexOf(":");Se!==-1&&(D=D.substr(Se+1),se=D!==L.data.substr(Se+1))}return{tagName:D,tagExp:N,closeIndex:ee,attrExpPresent:se,rawTagName:ne}}s(S,"readTagExp"),r(S,"readTagExp");function B(R,I,A){let z=A,L=1;for(;A<R.length;A++)if(R[A]==="<")if(R[A+1]==="/"){let N=b(R,">",A,`${I} is not closed`);if(R.substring(A+2,N).trim()===I&&(L--,L===0))return{tagContent:R.substring(z,A),i:N};A=N}else if(R[A+1]==="?")A=b(R,"?>",A+1,"StopNode is not closed.");else if(R.substr(A+1,3)==="!--")A=b(R,"-->",A+3,"StopNode is not closed.");else if(R.substr(A+1,2)==="![")A=b(R,"]]>",A,"StopNode is not closed.")-2;else{let N=S(R,A,">");N&&((N&&N.tagName)===I&&N.tagExp[N.tagExp.length-1]!=="/"&&L++,A=N.closeIndex)}}s(B,"readStopNodeData"),r(B,"readStopNodeData");function le(R,I,A){if(I&&typeof R=="string"){let z=R.trim();return z==="true"?!0:z==="false"?!1:q(R,A)}else return H.isExist(R)?R:""}s(le,"parseValue"),r(le,"parseValue"),C.exports=$}}),p=o({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(P){"use strict";function C($,E){return H($,E)}s(C,"prettify"),r(C,"prettify");function H($,E,M){let G,V={};for(let v=0;v<$.length;v++){let T=$[v],U=_(T),ce="";if(M===void 0?ce=U:ce=M+"."+U,U===E.textNodeName)G===void 0?G=T[U]:G+=""+T[U];else{if(U===void 0)continue;if(T[U]){let K=H(T[U],E,ce),Q=q(K,E);T[":@"]?j(K,T[":@"],ce,E):Object.keys(K).length===1&&K[E.textNodeName]!==void 0&&!E.alwaysCreateTextNode?K=K[E.textNodeName]:Object.keys(K).length===0&&(E.alwaysCreateTextNode?K[E.textNodeName]="":K=""),V[U]!==void 0&&V.hasOwnProperty(U)?(Array.isArray(V[U])||(V[U]=[V[U]]),V[U].push(K)):E.isArray(U,ce,Q)?V[U]=[K]:V[U]=K}}}return typeof G=="string"?G.length>0&&(V[E.textNodeName]=G):G!==void 0&&(V[E.textNodeName]=G),V}s(H,"compress"),r(H,"compress");function _($){let E=Object.keys($);for(let M=0;M<E.length;M++){let G=E[M];if(G!==":@")return G}}s(_,"propName"),r(_,"propName");function j($,E,M,G){if(E){let V=Object.keys(E),v=V.length;for(let T=0;T<v;T++){let U=V[T];G.isArray(U,M+"."+U,!0,!0)?$[U]=[E[U]]:$[U]=E[U]}}}s(j,"assignAttributes"),r(j,"assignAttributes");function q($,E){let{textNodeName:M}=E,G=Object.keys($).length;return!!(G===0||G===1&&($[M]||typeof $[M]=="boolean"||$[M]===0))}s(q,"isLeafTag"),r(q,"isLeafTag"),P.prettify=C}}),h=o({"node_modules/fast-xml-parser/src/validator.js"(P){"use strict";var C=a(),H={allowBooleanAttributes:!1,unpairedTags:[]};P.validate=function(b,S){S=Object.assign({},H,S);let B=[],le=!1,R=!1;b[0]==="\uFEFF"&&(b=b.substr(1));for(let I=0;I<b.length;I++)if(b[I]==="<"&&b[I+1]==="?"){if(I+=2,I=j(b,I),I.err)return I}else if(b[I]==="<"){let A=I;if(I++,b[I]==="!"){I=q(b,I);continue}else{let z=!1;b[I]==="/"&&(z=!0,I++);let L="";for(;I<b.length&&b[I]!==">"&&b[I]!==" "&&b[I]!==" "&&b[I]!==`
|
|
63
|
-
|
|
64
|
-
`||b==="\r"}s(_,"isWhiteSpace"),r(_,"isWhiteSpace");function j(b,S){let B=S;for(;S<b.length;S++)if(b[S]=="?"||b[S]==" "){let le=b.substr(B,S-B);if(S>5&&le==="xml")return U("InvalidXml","XML declaration allowed only at the start of the document.",Q(b,S));if(b[S]=="?"&&b[S+1]==">"){S++;break}else continue}return S}s(j,"readPI"),r(j,"readPI");function q(b,S){if(b.length>S+5&&b[S+1]==="-"&&b[S+2]==="-"){for(S+=3;S<b.length;S++)if(b[S]==="-"&&b[S+1]==="-"&&b[S+2]===">"){S+=2;break}}else if(b.length>S+8&&b[S+1]==="D"&&b[S+2]==="O"&&b[S+3]==="C"&&b[S+4]==="T"&&b[S+5]==="Y"&&b[S+6]==="P"&&b[S+7]==="E"){let B=1;for(S+=8;S<b.length;S++)if(b[S]==="<")B++;else if(b[S]===">"&&(B--,B===0))break}else if(b.length>S+9&&b[S+1]==="["&&b[S+2]==="C"&&b[S+3]==="D"&&b[S+4]==="A"&&b[S+5]==="T"&&b[S+6]==="A"&&b[S+7]==="["){for(S+=8;S<b.length;S++)if(b[S]==="]"&&b[S+1]==="]"&&b[S+2]===">"){S+=2;break}}return S}s(q,"readCommentAndCDATA"),r(q,"readCommentAndCDATA");var $='"',E="'";function M(b,S){let B="",le="",R=!1;for(;S<b.length;S++){if(b[S]===$||b[S]===E)le===""?le=b[S]:le!==b[S]||(le="");else if(b[S]===">"&&le===""){R=!0;break}B+=b[S]}return le!==""?!1:{value:B,index:S,tagClosed:R}}s(M,"readAttributeStr"),r(M,"readAttributeStr");var G=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function V(b,S){let B=C.getAllMatches(b,G),le={};for(let R=0;R<B.length;R++){if(B[R][1].length===0)return U("InvalidAttr","Attribute '"+B[R][2]+"' has no space in starting.",ve(B[R]));if(B[R][3]!==void 0&&B[R][4]===void 0)return U("InvalidAttr","Attribute '"+B[R][2]+"' is without value.",ve(B[R]));if(B[R][3]===void 0&&!S.allowBooleanAttributes)return U("InvalidAttr","boolean attribute '"+B[R][2]+"' is not allowed.",ve(B[R]));let I=B[R][2];if(!ce(I))return U("InvalidAttr","Attribute '"+I+"' is an invalid name.",ve(B[R]));if(!le.hasOwnProperty(I))le[I]=1;else return U("InvalidAttr","Attribute '"+I+"' is repeated.",ve(B[R]))}return!0}s(V,"validateAttributeString"),r(V,"validateAttributeString");function v(b,S){let B=/\d/;for(b[S]==="x"&&(S++,B=/[\da-fA-F]/);S<b.length;S++){if(b[S]===";")return S;if(!b[S].match(B))break}return-1}s(v,"validateNumberAmpersand"),r(v,"validateNumberAmpersand");function T(b,S){if(S++,b[S]===";")return-1;if(b[S]==="#")return S++,v(b,S);let B=0;for(;S<b.length;S++,B++)if(!(b[S].match(/\w/)&&B<20)){if(b[S]===";")break;return-1}return S}s(T,"validateAmpersand"),r(T,"validateAmpersand");function U(b,S,B){return{err:{code:b,msg:S,line:B.line||B,col:B.col}}}s(U,"getErrorObject"),r(U,"getErrorObject");function ce(b){return C.isName(b)}s(ce,"validateAttrName"),r(ce,"validateAttrName");function K(b){return C.isName(b)}s(K,"validateTagName"),r(K,"validateTagName");function Q(b,S){let B=b.substring(0,S).split(/\r?\n/);return{line:B.length,col:B[B.length-1].length+1}}s(Q,"getLineNumberForPosition"),r(Q,"getLineNumberForPosition");function ve(b){return b.startIndex+b[1].length}s(ve,"getPositionFromMatch"),r(ve,"getPositionFromMatch")}}),y=o({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(P,C){var{buildOptions:H}=i(),_=d(),{prettify:j}=p(),q=h(),$=class{static{s(this,"XMLParser")}static{r(this,"XMLParser")}constructor(E){this.externalEntities={},this.options=H(E)}parse(E,M){if(typeof E!="string")if(E.toString)E=E.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(M){M===!0&&(M={});let v=q.validate(E,M);if(v!==!0)throw Error(`${v.err.msg}:${v.err.line}:${v.err.col}`)}let G=new _(this.options);G.addExternalEntities(this.externalEntities);let V=G.parseXml(E);return this.options.preserveOrder||V===void 0?V:j(V,this.options)}addEntity(E,M){if(M.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(E.indexOf("&")!==-1||E.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");if(M==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[E]=M}};C.exports=$}});let O=y();return new O(n)},"getXmlParser");var Xo=class extends je{static{s(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),g("policy.outbound.xml-to-json"),X(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=e.parseOnStatusCodes?st(e.parseOnStatusCodes):void 0,this.parser=va({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,t,r){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let o;try{let u=await e.text();o=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw r.log.error(c,u),new k(c)}let i=new Headers(e.headers);return i.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:i})}};var Yo=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(e,t){if(this.services.get(e))throw new W(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,t)}getService(e){return this.services.get(e)}};var Qo=class{static{s(this,"BackgroundDispatcher")}#e;constructor(e,t){if(!t||t.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new J(t.name??"",t.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),wn().waitUntil(this.#e.waitUntilFlushed())}};var Ca=10,Sa=3e4,ei=class{static{s(this,"BackgroundLoader")}#e=new Map;#t;#n;#r;#o;#i={};constructor(e,t){if(typeof t=="number"){let r=t;this.#n=r*1e3,this.#o=Sa,this.#r=Ca}else{let r=t;this.#n=r.ttlSeconds*1e3,this.#o=r.loaderTimeoutSeconds?r.loaderTimeoutSeconds*1e3:Sa,this.#r=Ca}this.#t=e}#s(e){return e.expiry<=new Date}#a(e){let t=this.#i[e];return!(t===void 0||t===0)}#u(e){let t=this.#e.get(e);if(t&&!this.#s(t))return t.data}async get(e){let t=this.#u(e);if(t)return this.#l(e),t;if(this.#a(e))try{await ql(()=>this.#u(e)!==void 0||!this.#a,this.#o+this.#r+1,this.#r);let r=this.#u(e);if(r)return r}catch{}return this.#c(e)}#l(e){if(!this.#a(e)){let t=this.#c(e);wn().waitUntil(t)}}async#c(e){try{this.#i[e]===void 0&&(this.#i[e]=0),this.#i[e]++;let t=await Promise.race([this.#t(e),scheduler.wait(this.#o)]);if(t===void 0)throw new Error(`BackgroundLoader: Loader timed out after ${this.#o} ms.`);return this.#e.set(e,{data:t,expiry:new Date(Date.now()+this.#n)}),t}finally{this.#i[e]--}}};async function ql(n,e,t){let r=Date.now();for(;!n();){let o=Date.now()-r;if(o>e)throw new Error(`BackgroundLoader: Timeout waiting for an on-going loader after ${o} ms.`);await scheduler.wait(t)}}s(ql,"waitUntilTrue");var ti=["sha-1","sha-256","sha-384","sha-512"],Hn=class{static{s(this,"BaseCryptoBeta")}};var ni=class extends Hn{static{s(this,"WorkerCryptoBeta")}async digest(e,t){if(!ti.includes(e.toLowerCase()))throw new k(`Algorithm ${e} is not supported. Try using ${ti.join(", ")}`);let r=new TextEncoder().encode(t),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var Un=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var ri=class extends Un{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let t=f.instance.runtime.ZUPLO_KV;if(!t)throw new si("The Key Value Store feature is not enabled for this project.");this.#e=t,g("platform.kv-store")}put(e,t,r){if(typeof e!="string")throw new m("value must be of type string");return this.#e.put(e,t,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,t){return this.#e.get(e,{type:"text",cacheTtl:t?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};export{oo as AWSLoggingPlugin,mc as AmberfloMeteringInboundPolicy,xo as AmberfloMeteringPolicy,hc as ApiAuthKeyInboundPolicy,To as ApiKeyInboundPolicy,fo as AuditLogDataStaxProvider,ho as AuditLogPlugin,Pc as Auth0JwtInboundPolicy,_u as AwsLambdaHandlerExtensions,Oo as AxiomaticsAuthZInboundPolicy,Qo as BackgroundDispatcher,ei as BackgroundLoader,Ic as BasicAuthInboundPolicy,ma as BasicRateLimitInboundPolicy,J as BatchDispatch,Lo as BrownoutInboundPolicy,_c as CachingInboundPolicy,Nc as ChangeMethodInboundPolicy,Dc as ClearHeadersInboundPolicy,Mc as ClearHeadersOutboundPolicy,Hc as ClerkJwtInboundPolicy,Uc as CognitoJwtInboundPolicy,Mo as ComplexRateLimitInboundPolicy,Gc as CompositeInboundPolicy,m as ConfigurationError,lr as ContentTypes,ge as ContextData,ni as CryptoBeta,Vc as CurityPhantomTokenInboundPolicy,Mr as DataDogLoggingPlugin,ao as DataDogMetricsPlugin,Kr as DynaTraceLoggingPlugin,po as DynatraceMetricsPlugin,Kc as FirebaseJwtInboundPolicy,Jc as FormDataToJsonInboundPolicy,Xc as GeoFilterInboundPolicy,kr as GoogleCloudLoggingPlugin,Fr as Handler,x as HttpProblems,tn as HttpStatusCode,de as InboundPolicy,Yc as JWTScopeValidationInboundPolicy,ri as KeyValueStore,Xr as LokiLoggingPlugin,Zt as LookupResult,re as MemoryZoneReadThroughCache,Qc as MockApiInboundPolicy,sl as MoesifInboundPolicy,Zo as MonetizationInboundPolicy,Fo as OktaFGAAuthZInboundPolicy,ul as OktaJwtInboundPolicy,$o as OpenFGAAuthZInboundPolicy,we as OpenIdJwtInboundPolicy,je as OutboundPolicy,Xe as ProblemResponseFormatter,ll as PropelAuthJwtInboundPolicy,ma as RateLimitInboundPolicy,gl as ReadmeMetricsInboundPolicy,fl as RemoveHeadersInboundPolicy,hl as RemoveHeadersOutboundPolicy,yl as RemoveQueryParamsInboundPolicy,bl as ReplaceStringOutboundPolicy,wl as RequestSizeLimitInboundPolicy,Pa as RequestValidationInboundPolicy,Pl as RequireOriginInboundPolicy,Ot as ResponseSendingEvent,At as ResponseSentEvent,Ft as Router,k as RuntimeError,Jt as SYSTEM_LOGGER,Rl as SchemaBasedRequestValidation,Le as SemanticAttributes,Yo as ServiceProviderImpl,Il as SetBodyInboundPolicy,El as SetHeadersInboundPolicy,xl as SetHeadersOutboundPolicy,Tl as SetQueryParamsInboundPolicy,vl as SetStatusOutboundPolicy,Sl as SleepInboundPolicy,Hs as StripeMonetizationPlugin,jt as StripeWebhookVerificationInboundPolicy,eo as SumoLogicLoggingPlugin,Ol as SupabaseJwtInboundPolicy,qe as SystemRouteName,vt as TelemetryPlugin,Al as UpstreamAzureAdServiceAuthInboundPolicy,Ll as UpstreamFirebaseAdminAuthInboundPolicy,Dl as UpstreamFirebaseUserAuthInboundPolicy,Wo as UpstreamGcpFederatedAuthInboundPolicy,Ml as UpstreamGcpJwtInboundPolicy,Hl as UpstreamGcpServiceAuthInboundPolicy,no as VMWareLogInsightLoggingPlugin,Ul as ValidateJsonSchemaInbound,Xo as XmlToJsonOutboundPolicy,xt as ZoneCache,te as ZuploRequest,Vt as ZuploServices,Nu as awsLambdaHandler,Re as environment,Fn as getIdForParameterSchema,Aa as getIdForRefSchema,$n as getIdForRequestBodySchema,Oa as getRawOperationDataIdentifierName,pr as httpStatuses,$u as openApiSpecHandler,zu as redirectHandler,ka as sanitizedIdentifierName,dr as serialize,rl as setMoesifContext,g as trackFeature,Gu as urlForwardHandler,Wu as urlRewriteHandler,Ku as webSocketHandler,Ju as webSocketPipelineHandler};
|
|
61
|
+
`+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(r>0&&p>r)throw new De(e,n,{message:"Timestamp outside the tolerance zone"});return!0}s(sc,"validateComputedSignature");function ac(n,e){return typeof n!="string"?null:n.split(",").reduce((t,o)=>{let r=o.split("=");return r[0]==="t"&&(t.timestamp=parseInt(r[1],10)),r[0]===e&&t.signatures.push(r[1]),t},{timestamp:-1,signatures:[]})}s(ac,"parseHeader");function uc(n,e){if(n.length!==e.length)return!1;let t=n.length,o=0;for(let r=0;r<t;++r)o|=n.charCodeAt(r)^e.charCodeAt(r);return o===0}s(uc,"secureCompare");async function cc(n,e){let t=new TextEncoder,o=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),r=await crypto.subtle.sign("hmac",o,t.encode(n)),i=new Uint8Array(r),a=new Array(i.length);for(let u=0;u<i.length;u++)a[u]=fr[i[u]];return a.join("")}s(cc,"computeHMACSignatureAsync");var fr=new Array(256);for(let n=0;n<fr.length;n++)fr[n]=n.toString(16).padStart(2,"0");function W(n,e,t="policy",o){let r=`${t} '${e}'`;if(!tt(n))throw new m(`Options on ${r} is expected to be an object. Received the type '${typeof n}'.`);let i=s((c,l,d)=>{let p=n[c],f=o?`${o}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new m(`Value of '${f}' on ${r} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"&&Array.isArray(p))throw new m(`Value of '${f}' on ${r} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new m(`Value of '${f}' on ${r} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new m(`Value of '${f}' on ${r} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof p=="number"&&isNaN(p))throw new m(`Value of '${f}' on ${r} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=s((c,l)=>(i(c,l,!0),{optional:a,required:u}),"optional"),u=s((c,l)=>(i(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}s(W,"optionValidator");var Gt=class extends ae{static{s(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.stripe-webhook-verification")}async handler(e,t){W(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let o=e.headers.get("stripe-signature");try{let r=await e.clone().text();await As(r,o,this.options.signingSecret)}catch(r){let i=r.message;if(r.type&&r.type==="StripeSignatureVerificationError"){let a=r.message,c=/Note:(.*)/g.exec(a);i=c?c[1].trim():a,i.startsWith("No signatures found matching the expected signature for payload")&&(i="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",i),x.badRequest(e,t,{title:"Webhook Error",detail:i})}return e}};function ks(n){return n!==null&&typeof n=="object"&&"id"in n&&Ee(n.id)&&"type"in n&&Ee(n.type)}s(ks,"isStripeWebhookEvent");var lc={getSubscription:async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let o=await F.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),r=await o.json();if(o.status!==200){let i="Error retrieving subscription from Stripe API.";throw t.error(i,r),new L(i)}return r},getCustomer:async({customerId:n,stripeSecretKey:e,logger:t})=>{let o=await F.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),r=await o.json();if(o.status!==200){let i="Error retrieving customer from Stripe API.";throw t.error(i,r),new L(i)}return r},getUpcomingInvoice:async({customerId:n,stripeSecretKey:e,logger:t})=>{let o=await F.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),r=await o.json();if(o.status!==200){let i="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(i,r),new L(i)}return r}},xn=lc;var hr="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Ls="My API Key";async function _s({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:o,managerEmail:r,managerSub:i,context:a}){let{authApiJWT:u}=h.instance,c=new URL(`/v1/buckets/${n}/consumers`,hr);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Ls,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:o},managers:[{sub:i,email:r}]},p=await fe({retryDelayMs:5,retries:2,logger:Q.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),f=await p.json();if(p.status!==200){let y="Error creating API Key Consumer";throw a.log.error(y,f),new L(y)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}s(_s,"createConsumer");async function Ns({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:o,managerEmail:r,context:i}){let{authApiJWT:a}=h.instance,u=new URL(`/v1/buckets/${n}/consumers`,hr);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:Ls,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:o},managers:[r]},d=await fe({retryDelayMs:5,retries:2,logger:Q.getLogger(i)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let f="Error creating API Key Consumer";throw i.log.error(f,p),new L(f)}return i.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}s(Ns,"createConsumerInvite");async function Ds({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:o}=h.instance,r=new URL(`/v1/buckets/${n}/consumers/${e}`,hr);r.searchParams.set("with-api-key","true");let i=await fe({retryDelayMs:5,retries:2,logger:Q.getLogger(t)},r.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${o}`,"content-type":"application/json"},body:JSON.stringify({})});if(i.status!==204){let a=await i.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new L(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}s(Ds,"deleteConsumer");async function Ms({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:o,meteringBucketId:r,meteringBucketRegion:i,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:i,subscriptionExternalId:e,planExternalIds:[t],customerKey:o,customerExternalId:a,metadata:c,trialEndDate:l?l.trialEndDate:void 0,trialStartDate:l?l.trialStartDate:void 0,trialEndStatus:l?l.trialEndStatus:void 0},{authApiJWT:p,meteringServiceUrl:f}=h.instance;if(!ct(p))throw new J("No Zuplo JWT token set.");let y=await fe({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${f}/internal/v1/metering/${r}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!y.ok){let O=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,P,v="";try{P=await y.json(),v=P.detail??P.title}catch{P={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:y.status,detail:y.statusText}}throw n.log.error(O,P),new L(`${O} ${v}`)}n.log.info("Successfully created monetization subscription.",d)}s(Ms,"createSubscription");async function gt({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:o}){let{authApiJWT:r,meteringServiceUrl:i}=h.instance;if(!ct(r))throw new J("No Zuplo JWT token set.");let a=await fe({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${i}/internal/v1/metering/${t}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"PATCH",body:JSON.stringify(o)});if(!a.ok){let u=`Unable to update monetization subscription with: '${JSON.stringify(o)}'.`,c,l="";try{c=await a.json(),l=c.detail??c.title}catch{c={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(u,c),new L(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(o)}'.`)}s(gt,"updateSubscription");async function ft({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:o}){let{authApiJWT:r,meteringServiceUrl:i}=h.instance;if(!ct(r))throw new J("No Zuplo JWT token set.");let a=await fe({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${i}/internal/v1/metering/${o}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${r}`,"zp-rid":n.requestId},method:"GET"});if(!a.ok){let c=`Unable to retrieve the monetization subscription for Stripe subscription '${e}'.`,l,d="";try{l=await a.json(),d=l.detail??l.title}catch{l={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(c,l),new L(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(c),new L(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(c),new L(c)}return u.data[0]}s(ft,"getSubscription");var re="Skipping since we're unable to process the webhook event.",Ve="Successfully processed the webhook event",Ie="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function Tn(n){return n.replaceAll("_","-")}s(Tn,"stripeStatusToMeteringStatus");function it(n){return new Date(n*1e3).toISOString()}s(it,"unixTimestampToISOString");async function yr(n,e,t,o){let r=t.data.object.id;if(!r)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),x.ok(n,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.plan;if(!i||!i.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),x.ok(n,e,{title:re,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=t.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==h.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),x.ok(n,e,{title:re,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ie});let u=i.product,c,l,d;try{if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_email&&t.data.object.metadata.zuplo_created_by_sub)l=t.data.object.metadata.zuplo_created_by_email,d=t.data.object.metadata.zuplo_created_by_sub,c=await _s({apiKeyBucketName:o.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:r,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await xn.getCustomer({logger:e.log,stripeSecretKey:o.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),x.ok(n,e,{title:re,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Ns({apiKeyBucketName:o.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:r,stripeCustomerId:a,managerEmail:p.email,context:e})}}catch(p){return e.log.warn(`Failed to create API Key Consumer. Error: ${p.message}`),x.ok(n,e,{title:re,detail:p.message})}if(!c)return x.ok(n,e,{title:re,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=Tn(t.data.object.status),f;l&&d&&(f={subscriber:{sub:d,email:l}});let y;t.data.object.trial_end!==null&&t.data.object.trial_start!==null&&t.data.object.trial_settings&&t.data.object.trial_settings.end_behavior&&(t.data.object.trial_settings.end_behavior.missing_payment_method==="cancel"||t.data.object.trial_settings.end_behavior.missing_payment_method==="pause")&&(y={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:it(t.data.object.trial_end),trialStartDate:it(t.data.object.trial_start)}),await Ms({context:e,stripeProductId:u,stripeSubscriptionId:r,customerKey:c,meteringBucketId:o.meteringBucketId,meteringBucketRegion:o.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:f,trial:y})}catch(p){return await Ds({apiKeyBucketName:o.apiKeyBucketName,consumerId:c,context:e}),x.ok(n,e,{title:re,detail:p.message})}return x.ok(n,e,{title:Ve})}s(yr,"onCustomerSubscriptionCreated");async function br(n,e,t,o){let r=t.data.object.id;if(!r)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),x.ok(n,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==h.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),x.ok(n,e,{title:re,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ie});try{let a=await ft({context:e,stripeSubscriptionId:r,stripeCustomerId:i,meteringBucketId:o.meteringBucketId});await gt({context:e,meteringSubscriptionId:a.id,meteringBucketId:o.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return x.ok(n,e,{title:re,detail:`The event 'customer.subscription.deleted' could not be processed. ${a.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. `+Ie})}return x.ok(n,e,{title:Ve})}s(br,"onCustomerSubscriptionDeleted");async function wr(n,e,t,o){let r=t.data.object.id;if(!r)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to include '.data.object.id' as the subscription ID.`),x.ok(n,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==h.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),x.ok(n,e,{title:re,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ie});if(t.data.previous_attributes){let a=t.data.previous_attributes;if(a.status&&a.status!==t.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${t.id}'.`);let u=await ft({context:e,stripeSubscriptionId:r,stripeCustomerId:i,meteringBucketId:o.meteringBucketId}),c=Tn(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=it(t.data.object.trial_end)),await gt({context:e,meteringSubscriptionId:u.id,meteringBucketId:o.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return x.ok(n,e,{title:re,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ie})}return x.ok(n,e,{title:Ve})}if(a.plan&&a.plan.product!==t.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${t.id}'.`);let u=await ft({context:e,stripeSubscriptionId:r,stripeCustomerId:i,meteringBucketId:o.meteringBucketId}),c=t.data.object.plan.product,d=(await xn.getUpcomingInvoice({customerId:i,logger:e.log,stripeSecretKey:o.stripeSecretKey})).lines.data.filter(f=>f.proration&&f.price.product===c),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${t.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await gt({context:e,meteringSubscriptionId:u.id,meteringBucketId:o.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return x.ok(n,e,{title:re,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ie})}return x.ok(n,e,{title:Ve})}if((a.cancel_at||a.cancel_at===null)&&a.cancel_at!==t.data.object.cancel_at&&a.cancel_at_period_end&&a.cancel_at_period_end!==t.data.object.cancel_at_period_end&&(a.canceled_at||a.canceled_at===null)&&a.canceled_at!==t.data.object.canceled_at||a.cancellation_details&&(a.cancellation_details.comment||a.cancellation_details.comment===null||a.cancellation_details.feedback||a.cancellation_details.feedback===null||a.cancellation_details.reason||a.cancellation_details.reason===null)){try{e.log.debug(`Processing subscription cancellation details from Stripe event '${t.id}'.`);let u=await ft({context:e,stripeSubscriptionId:r,stripeCustomerId:i,meteringBucketId:o.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?it(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?it(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await gt({context:e,meteringSubscriptionId:u.id,meteringBucketId:o.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return x.ok(n,e,{title:re,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ie})}return x.ok(n,e,{title:Ve})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),x.ok(n,e,{title:re,detail:"This 'customer.subscription.updated' event could not be processed. The Stripe monetization plugin only supports update events for subscription plan changes or subscription status changes."+Ie})}s(wr,"onCustomerSubscriptionUpdated");var qs=class extends Xt{constructor(t){super();this.options=t;g("monetization.stripe")}static{s(this,"StripeMonetizationPlugin")}registerRoutes(t,o){let r=s(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(Re.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(Re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=Re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!h.instance.build.ACCOUNT_NAME)throw new J("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let f=this.options.primaryDataRegion??"us-central1";if(!dc(f))throw new m(`StripeMonetizationPlugin - The value '${f}' on the property 'primaryDataRegion' is invalid.`);let y=await c.json();if(!ks(y))return x.ok(c,l,{title:re,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+Ie});switch(l.log.info(`Received Stripe webhook event of type '${y.type}' with ID '${y.id}'.`),y.type){case"customer.subscription.created":return await yr(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:f,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await wr(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:f,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await br(c,l,y,{meteringBucketId:d});default:return x.ok(c,l,{title:re,detail:`Event '${y.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ie})}},"stripeWebhookHandler"),i=Ki({inboundPolicies:[new Gt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});W(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new me({processors:[be,i],handler:r,gateway:o}),u=new ce({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function dc(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}s(dc,"isMetricsRegion");var Us=new WeakMap,Hs={},Rr=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){Us.set(e,t)}};async function pc(n,e,t,o){if(g("policy.inbound.amberflo-metering"),!t.statusCodes)throw new m(`Invalid AmberfloMeterInboundPolicy '${o}': options.statusCodes must be an array of HTTP status code numbers`);let r=je(t.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(r.includes(i.status)){let a=Us.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new L(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=nt(n.user,t.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${o}': customerId cannot be undefined`);return}let l=a?.meterApiName??t.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${o}': meterApiName cannot be undefined`);return}let d=a?.meterValue??t.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${o}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(t.dimensions??{},a?.dimensions)},f=Hs[t.apiKey];if(!f){let y=t.apiKey,O=n.headers.get("zm-test-id")??"";f=new X("amberflo-ingest-meter",10,async P=>{try{let v=t.url??"https://app.amberflo.io/ingest",N=await F.fetch(v,{method:"POST",body:JSON.stringify(P),headers:{"content-type":"application/json","x-api-key":y,"zm-test-id":O}});N.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${o}'. ${N.status}: ${await N.text()}`)}catch(v){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${o}': ${v.message}`),v}}),Hs[y]=f}f.enqueue(p),e.waitUntil(f.waitUntilFlushed())}}),n}s(pc,"AmberfloMeteringInboundPolicy");async function st(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(t)].map(r=>r.toString(16).padStart(2,"0")).join("")}s(st,"sha256");var Zs=new Map;async function ie(n,e,t){let o,r=`${n}-${e}`,i=Zs.get(r);return i!==void 0?o=i:(o=`zuplo-policy-${await st(JSON.stringify({policyName:n,options:t}))}`,Zs.set(n,o)),o}s(ie,"getPolicyCacheName");var Fs="key-metadata-cache-type";function mc(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}s(mc,"getKeyValue");async function Pr(n,e,t,o){if(g("policy.inbound.api-key"),!t.bucketName)if(Re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=Re.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m(`ApiKeyInboundPolicy '${o}' - no bucketName property provided`);let r={authHeader:t.authHeader??"authorization",authScheme:t.authScheme??"Bearer",bucketName:t.bucketName,cacheTtlSeconds:t.cacheTtlSeconds??60,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:t.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(r.cacheTtlSeconds<60)throw new m(`ApiKeyInboundPolicy '${o}' - minimum cacheTtlSeconds value is 60s, '${r.cacheTtlSeconds}' is invalid`);let i=s(v=>r.allowUnauthenticatedRequests?n:x.unauthorized(n,e,{detail:v}),"unauthorizedResponse"),a=n.headers.get(r.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(r.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let u=mc(a,r);if(!u||u==="")return i("No key present");let c=await gc(u),l=await ie(o,void 0,r),d=new oe(l,e),p=await d.get(c);if(p&&p.isValid===!0)return n.user=p.user,n;if(p&&!p.isValid)return p.typeId!==Fs&&Q.getLogger(e).error(`ApiKeyInboundPolicy '${o}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let f={key:u},y=await fe({retryDelayMs:5,retries:2,logger:Q.getLogger(e)},`${h.instance.apiKeyServiceUrl}/v1/$validate/${r.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":h.instance.deploymentName??"unknown","User-Agent":h.instance.systemUserAgent},body:JSON.stringify(f)});if(y.status===401)return e.log.info(`ApiKeyInboundPolicy '${o}' - 401 response from Key Service`),i("Authorization Failed");if(y.status!==200){try{let v=await y.text(),N=JSON.parse(v);e.log.error("Unexpected response from key service",N)}catch{e.log.error("Invalid response from key service")}throw new L(`ApiKeyInboundPolicy '${o}' - unexpected response from Key Service. Status: ${y.status}`)}let O=await y.json(),P={isValid:!0,typeId:Fs,user:{sub:O.name,data:O.metadata}};return n.user=P.user,d.put(c,P,r.cacheTtlSeconds),n}s(Pr,"ApiKeyInboundPolicy");async function gc(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(gc,"hashValue");var fc=Pr;import{createRemoteJWKSet as yc,jwtVerify as js}from"jose";import{createLocalJWKSet as hc}from"jose";var Ir=class{constructor(e,t,o){this.cache=t;if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.url=new URL(e.href),this.options={agent:o?.agent,headers:o?.headers},this.timeoutDuration=typeof o?.timeoutDuration=="number"?o?.timeoutDuration:5e3,this.cooldownDuration=typeof o?.cooldownDuration=="number"?o?.cooldownDuration:3e4,this.cacheMaxAge=typeof o?.cacheMaxAge=="number"?o?.cacheMaxAge:6e5}static{s(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,t){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,t)}catch(o){if(o instanceof Er&&this.coolingDown()===!1)return await this.reload(),this.local(e,t);throw o}}async reload(){this.pendingFetch&&(this.pendingFetch=void 0);let e=new Headers(this.options.headers);e.has("User-Agent")||(e.set("User-Agent",h.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=hc(t),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(t=>{throw this.pendingFetch=void 0,t}),await this.pendingFetch}async fetchJwks(e,t,o){let r=await this.cache.get(this.url.href);if(r)return r;let i,a,u=!1;typeof AbortController=="function"&&(i=new AbortController,a=setTimeout(()=>{u=!0,i.abort()},t));let c=await F.fetch(e.href,{signal:i?i.signal:void 0,redirect:"manual",headers:o.headers}).catch(l=>{throw u?new xr("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new ht("Expected 200 OK from the JSON Web Key Set HTTP response");try{let l=await c.json();return this.cache.put(this.url.href,l,this.cacheMaxAge),l}catch{throw new ht("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function $s(n,e,t){let o=new Ir(n,e,t);return async(r,i)=>o.getKey(r,i)}s($s,"createRemoteJWKSet");var ht=class extends L{static{s(this,"JWKSError")}},Er=class extends ht{static{s(this,"JWKSNoMatchingKey")}},xr=class extends ht{static{s(this,"JWKSTimeout")}};var vn={},bc=s((n,e)=>async(t,o)=>{if(!o.jwkUrl||typeof o.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");if(!vn[o.jwkUrl]){let i=!1;if("useExperimentalInMemoryCache"in o&&typeof o.useExperimentalInMemoryCache=="boolean"&&(i=o.useExperimentalInMemoryCache),i){let a=await ie(n,void 0,o),u=new oe(a,e);vn[o.jwkUrl]=$s(new URL(o.jwkUrl),u,o.headers?{headers:o.headers}:void 0)}else vn[o.jwkUrl]=yc(new URL(o.jwkUrl),o.headers?{headers:o.headers}:void 0)}let{payload:r}=await js(t,vn[o.jwkUrl],{issuer:o.issuer,audience:o.audience});return r},"createJwkVerifier"),wc=s(async(n,e)=>{let t;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let i=new TextEncoder().encode(e.secret);t=new Uint8Array(i)}else t=e.secret;let{payload:o}=await js(n,t,{issuer:e.issuer,audience:e.audience});return o},"secretVerifier"),we=s(async(n,e,t,o)=>{g("policy.inbound.open-id-jwt-auth");let r=n.headers.get("Authorization"),i="bearer ",a=s(f=>x.unauthorized(n,e,{detail:f}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${o}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${o}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=t.jwkUrl?bc(o,e):wc,l=await s(async()=>{if(!r)return a("No authorization header");if(r.toLowerCase().indexOf(i)!==0)return a("Invalid bearer token format for authorization header");let f=r.substring(i.length);if(!f||f.length===0)return a("No bearer token on authorization header");try{return await u(f,t)}catch(y){let O=new URL(n.url);return"code"in y&&y.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${O.pathname} `,y):e.log.warn(`Invalid token on: ${n.method} ${O.pathname}`,y),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return t.allowUnauthenticatedRequests===!0?n:l;let d=t.subPropertyName??"sub",p=l[d];return p?(n.user={sub:p,data:l},n):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var Rc=s(async(n,e,t,o)=>(g("policy.inbound.auth0-jwt-auth"),we(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)),"Auth0JwtInboundPolicy");var Tr=class n extends ae{static{s(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static#e;static setAuthAttributes(e,t){n.#e||(n.#e=new WeakMap),n.#e.set(e,{Request:t})}constructor(e,t){super(e,t),g("policy.inbound.axiomatics-authz"),W(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new ai(e)}async handler(e,t){let o=s(a=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:a}),"forbiddenResponse"),r=new URL(e.url),i=n.#e?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1&&e.user){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(i,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(i,"Action",a)}if(this.options.includeDefaultResourceAttributes!==!1){let a=[];a.push({AttributeId:"request.protocol",Value:r.protocol.substring(0,r.protocol.length-1)}),a.push({AttributeId:"request.host",Value:r.host}),a.push({AttributeId:"request.pathname",Value:r.pathname}),Object.entries(e.params).forEach(([u,c])=>{a.push({AttributeId:`request.params.${u}`,Value:c})}),r.searchParams.forEach((u,c)=>{a.push({AttributeId:`request.query.${c}`,Value:u})}),this.addAttributesToCategory(i,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:i,context:t}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:i,context:t}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:i,context:t});try{t.log.debug("PDP Request",i);let a=await this.pdpService.makePdpRequest(i);return t.log.debug("PDP Response",a),a.Response.every(u=>u.Decision==="Permit")?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),o("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling PDP service`,a),x.internalServerError(e,t)}}populateOptionAttributes({optionName:e,authzRequestCategory:t,authzRequest:o,context:r}){let i=this.options[e];if(i){let a=[];i.forEach(u=>{u.value?a.push({AttributeId:u.attributeId,Value:u.value}):r.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${u.attributeId} has no value. If using a selector, check that the selector is correct.`)}),this.addAttributesToCategory(o,t,a)}}addAttributesToCategory(e,t,o){e.Request[t]||(e.Request[t]=[]),e.Request[t].length===0?e.Request[t].push({Attribute:[]}):e.Request[t][0].Attribute=e.Request[t][0].Attribute??[],e.Request[t][0].Attribute.push(...o)}};var Pc=s(async(n,e,t)=>{g("policy.inbound.basic-auth");let o=n.headers.get("Authorization"),r="basic ",i=s(l=>x.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await s(async()=>{if(!o)return await i("No Authorization header");if(o.toLowerCase().indexOf(r)!==0)return await i("Invalid Basic token format for Authorization header");let l=o.substring(r.length);if(!l||l.length===0)return await i("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let f=d.substring(0,p),y=d.substring(p+1),O=t.accounts.find(P=>P.username===f&&P.password===y);return O||await i("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return t.allowUnauthenticatedRequests?n:u;let c=u.username;return n.user={sub:c,data:u.data},n},"BasicAuthInboundPolicy");function Sn(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}s(Sn,"extractDateElements");function zs(n,e){return new Date(n,e+1,0).getDate()}s(zs,"getDaysInMonth");function vr(n,e){return n<=e?e-n:6-n+e+1}s(vr,"getDaysBetweenWeekdays");var Cn=class{static{s(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:o,days:r,months:i,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!t||t.size===0)throw new Error("There must be at least one allowed minute.");if(!o||o.size===0)throw new Error("There must be at least one allowed hour.");if(!i||i.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!r||r.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((c,l)=>c-l),this.minutes=Array.from(t).sort((c,l)=>c-l),this.hours=Array.from(o).sort((c,l)=>c-l),this.days=Array.from(r).sort((c,l)=>c-l),this.months=Array.from(i).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=s((c,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${c} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");u("seconds",this.seconds,{min:0,max:59}),u("minutes",this.minutes,{min:0,max:59}),u("hours",this.hours,{min:0,max:23}),u("days",this.days,{min:1,max:31}),u("months",this.months,{min:0,max:11}),u("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(c=>c).reverse(),minutes:this.minutes.map(c=>c).reverse(),hours:this.hours.map(c=>c).reverse(),days:this.days.map(c=>c).reverse(),months:this.months.map(c=>c).reverse(),weekdays:this.weekdays.map(c=>c).reverse()}}findAllowedHour(e,t){return e==="next"?this.hours.find(o=>o>=t):this.reversed.hours.find(o=>o<=t)}findAllowedMinute(e,t){return e==="next"?this.minutes.find(o=>o>=t):this.reversed.minutes.find(o=>o<=t)}findAllowedSecond(e,t){return e==="next"?this.seconds.find(o=>o>t):this.reversed.seconds.find(o=>o<t)}findAllowedTime(e,t){let o=this.findAllowedHour(e,t.hour);if(o!==void 0)if(o===t.hour){let r=this.findAllowedMinute(e,t.minute);if(r!==void 0)if(r===t.minute){let i=this.findAllowedSecond(e,t.second);if(i!==void 0)return{hour:o,minute:r,second:i};if(r=this.findAllowedMinute(e,e==="next"?t.minute+1:t.minute-1),r!==void 0)return{hour:o,minute:r,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:o,minute:r,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(o=this.findAllowedHour(e,e==="next"?t.hour+1:t.hour-1),o!==void 0)return{hour:o,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:o,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,t,o,r){if(r<1)throw new Error("startDay must not be smaller than 1.");let i=zs(t,o),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return r>i?e==="next"?void 0:i:r;let c;a&&(c=e==="next"?this.days.find(d=>d>=r):this.reversed.days.find(d=>d<=r),c!==void 0&&c>i&&(c=void 0));let l;if(u){let d=new Date(t,o,r).getDay(),p=e==="next"?this.weekdays.find(f=>f>=d)??this.weekdays[0]:this.reversed.weekdays.find(f=>f<=d)??this.reversed.weekdays[0];if(p!==void 0){let f=e==="next"?vr(d,p):vr(p,d);l=e==="next"?r+f:r-f,(l>i||l<1)&&(l=void 0)}}if(c!==void 0&&l!==void 0)return e==="next"?Math.min(c,l):Math.max(c,l);if(c!==void 0)return c;if(l!==void 0)return l}getNextDate(e=new Date){let t=Sn(e),o=t.year,r=this.months.findIndex(a=>a>=t.month);r===-1&&(r=0,o++);let i=this.months.length*5;for(let a=0;a<i;a++){let u=o+Math.floor((r+a)/this.months.length),c=this.months[(r+a)%this.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("next",u,c,l?t.day:1),p=l&&d===t.day;if(d!==void 0&&p){let f=this.findAllowedTime("next",t);if(f!==void 0)return new Date(u,c,d,f.hour,f.minute,f.second);d=this.findAllowedDayInMonth("next",u,c,d+1),p=!1}if(d!==void 0&&!p)return new Date(u,c,d,this.hours[0],this.minutes[0],this.seconds[0])}throw new Error("No valid next date was found.")}getNextDates(e,t){let o=[],r;for(let i=0;i<e;i++)r=this.getNextDate(r??t),o.push(r);return o}*getNextDatesIterator(e,t){let o;for(;;){if(o=this.getNextDate(e),e=o,t&&t.getTime()<o.getTime())return;yield o}}getPrevDate(e=new Date){let t=Sn(e),o=t.year,r=this.reversed.months.findIndex(a=>a<=t.month);r===-1&&(r=0,o--);let i=this.reversed.months.length*5;for(let a=0;a<i;a++){let u=o-Math.floor((r+a)/this.reversed.months.length),c=this.reversed.months[(r+a)%this.reversed.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("prev",u,c,l?t.day:31),p=l&&d===t.day;if(d!==void 0&&p){let f=this.findAllowedTime("prev",t);if(f!==void 0)return new Date(u,c,d,f.hour,f.minute,f.second);d>1&&(d=this.findAllowedDayInMonth("prev",u,c,d-1),p=!1)}if(d!==void 0&&!p)return new Date(u,c,d,this.reversed.hours[0],this.reversed.minutes[0],this.reversed.seconds[0])}throw new Error("No valid previous date was found.")}getPrevDates(e,t){let o=[],r;for(let i=0;i<e;i++)r=this.getPrevDate(r??t),o.push(r);return o}*getPrevDatesIterator(e,t){let o;for(;;){if(o=this.getPrevDate(e),e=o,t&&t.getTime()>o.getTime())return;yield o}}matchDate(e){let{second:t,minute:o,hour:r,day:i,month:a,weekday:u}=Sn(e);return this.seconds.indexOf(t)===-1||this.minutes.indexOf(o)===-1||this.hours.indexOf(r)===-1||this.months.indexOf(a)===-1?!1:this.days.length!==31&&this.weekdays.length!==7?this.days.indexOf(i)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(i)!==-1&&this.weekdays.indexOf(u)!==-1}};var Ic={min:0,max:59},Ec={min:0,max:59},xc={min:0,max:23},Tc={min:1,max:31},vc={min:1,max:12,aliases:{jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"}},Sc={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},Cc={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 1 *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@hourly":"0 * * * *","@minutely":"* * * * *"};function at(n,e){let t=new Set;if(n==="*"){for(let d=e.min;d<=e.max;d=d+1)t.add(d);return t}let o=n.split(",");if(o.length>1)return o.forEach(d=>{at(d,e).forEach(f=>t.add(f))}),t;let r=s(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${n}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${n}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),i=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(i===null)return t.add(r(n)),t;let a=i[1]==="*"?e.min:r(i[3]),u=i[1]==="*"?e.max:r(i[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=i[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}s(at,"parseElement");function Sr(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=Cc[n.toLowerCase()]??n;let e=n.split(" ");if(e.length<5||e.length>6)throw new Error("Invalid cron expression: expected 5 or 6 elements.");let t=e.length===6?e[0]:"0",o=e.length===6?e[1]:e[0],r=e.length===6?e[2]:e[1],i=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],u=e.length===6?e[5]:e[4];return new Cn({seconds:at(t,Ic),minutes:at(o,Ec),hours:at(r,xc),days:at(i,Tc),months:new Set(Array.from(at(a,vc)).map(c=>c-1)),weekdays:new Set(Array.from(at(u,Sc)).map(c=>c%7))})}s(Sr,"parseCronExpression");var Cr=class extends ae{static{s(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),g("policy.inbound.brownout"),W(e,t).optional("problem","object"),e.problem&&W(e.problem,t,"policy","problem").optional("detail","string").optional("status","string").optional("title","string"),typeof e.cronSchedule!="string"&&!(typeof e.cronSchedule=="object"&&Array.isArray(e.cronSchedule)&&!e.cronSchedule.some(o=>typeof o!="string")))throw new m(`Value of 'cronSchedule' on policy '${t}' must be of type string or string[]. Received type ${typeof e.cronSchedule}.`);typeof this.options.cronSchedule=="string"?this.crons=[Sr(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(o=>Sr(o))}async handler(e,t){let o=new Date;if(o.setSeconds(0),o.setMilliseconds(0),this.crons.some(i=>i.matchDate(o))){let i=x.getProblemFromStatus(this.options.problem?.status??400,{detail:"This API is performing a scheduled brownout in advance of its pending deprecation. Please upgrade to a later version.",...this.options.problem});return x.format(i,e,t)}return e}};var Oc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Ac(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Ac,"digestMessage");var kc=s(async(n,e)=>{let t=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],o=[];for(let[d,p]of n.headers.entries())t.includes(d)&&o.push({key:d.toLowerCase(),value:p});o.sort((d,p)=>d.key.localeCompare(p.key));let r=await Ac(JSON.stringify(o)),i=new URL(n.url),a=new URLSearchParams(i.searchParams);a.set("_z-hdr-dgst",r);let u=e.cacheHttpMethods?.includes(n.method.toUpperCase())&&n.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",n.method);let c=`${i.origin}${i.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function Lc(n,e,t,o){g("policy.inbound.caching");let r=await ie(o,t.cacheId,t),i=await caches.open(r),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await kc(n,t),c=await i.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=t.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(n.method.toUpperCase()))return;let f=t?.expirationSecondsTtl??60,y=new Response(p.body,p);Oc.forEach(O=>y.headers.delete(O)),y.headers.set("cache-control",`s-maxage=${f}`),e.waitUntil(i.put(u,y))}catch(d){e.log.error(`Error in caching-inbound-policy '${o}': "${d.message}"`,d)}}),n)}s(Lc,"CachingInboundPolicy");var _c=s(async(n,e,t,o)=>{if(g("policy.inbound.change-method"),!t.method)throw new m(`ChangeMethodInboundPolicy '${o}' options.method must be valid HttpMethod`);return new te(n,{method:t.method})},"ChangeMethodInboundPolicy");var On=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},Or=class extends On{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Ar=class extends On{static{s(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function Nc(n,e){if(Fi(n))throw new Or(e)}s(Nc,"throwIfUndefinedOrNull");function Bs(n,e){if(Nc(n,e),!Ee(n))throw new Ar(e,"string")}s(Bs,"throwIfNotString");var kr=class{static{s(this,"InMemoryRateLimitClient")}keyValueStore;constructor(){this.keyValueStore=new Map}getCountAndUpdateExpiry(e,t){let r=Math.floor(t*60),i=Date.now()+r*1e3,a=this.keyValueStore.get(e);a?Date.now()>a.expiresAt?this.keyValueStore.set(e,{value:1,expiresAt:i}):this.keyValueStore.set(e,{value:a.value+1,expiresAt:a.expiresAt}):this.keyValueStore.set(e,{value:1,expiresAt:i});let u=this.keyValueStore.get(e);return Promise.resolve({count:u.value,ttlSeconds:Math.round((u.expiresAt-Date.now())/1e3)})}multiIncrement(e,t){throw new Error("In memory complex rate limits are not currently supported.")}multiCount(e,t){throw new Error("In memory complex rate limits are not currently supported.")}setQuota(e,t,o){throw new Error("In memory quotas are not currently supported.")}getQuota(e,t){throw new Error("In memory quotas are not currently supported.")}isEnabled(){return!0}},Lr=class{constructor(e,t,o,r){this.clientUrl=e;this.clientAuthToken=t;this.deploymentName=o;this.userAgent=r}static{s(this,"RemoteRateLimitClient")}static instance;isEnabled(){return this.clientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:t,method:o,requestId:r}){Bs(e,"url");let i=await F.fetch(`${this.clientUrl}${e}`,{method:o,body:t,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":r,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=i.headers.get("Content-Type")?.includes("application/json")?await i.json():await i.text();if(i.ok)return a;throw i.status===401?new J("Rate limiting service failed with 401: Unauthorized"):new J(`Rate limiting service failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}async multiCount(e,t){return(await this.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async multiIncrement(e,t){return(await this.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async getCountAndUpdateExpiry(e,t,o){let r=Math.floor(t*60);return await this.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:r,key:e}),requestId:o})}async getQuota(e,t){let o=await st(e);return await this.fetch({url:`/quota/${o}`,method:"GET",requestId:t})}async setQuota(e,t,o){let r=await st(e);await this.fetch({url:`/quota/${r}`,method:"POST",body:JSON.stringify(t),requestId:o})}},We;function Ke(n,e){if(We)return We;if(!h.instance.authApiJWT)return e.info("Using in-memory rate limit client for local development."),We=new kr,We;let{authApiJWT:t,redisURL:o}=h.instance;if(!Ee(o))throw new J(`RateLimitClient used in policy '${n}' - rate limit service URL not configured`);if(!Ee(t))throw new J(`RateLimitClient used in policy '${n}' - service authentication not configured`);if(o&&(We=new Lr(o,t,h.instance.deploymentName??"unknown",h.instance.systemUserAgent)),!We||!We.isEnabled())throw new J(`RateLimitClient used in policy '${n}' - no remote rate limiting service enabled`);return We}s(Ke,"getRateLimitClient");var _r="quota-inbound-policy-f307056c-8c00-4f2c-b4ac-c0ac7d04eca0";var Nr=class n extends ae{static{s(this,"QuotaInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.quota")}async handler(e,t){let o=this.options.debug??!1;t.log.debug({debug:o}),W(this.options,this.policyName).required("period","string").required("quotaBy","string").optional("quotaAnchorMode","string").optional("allowances","object"),n.setMeters(t,{requests:1});let r=Q.getLogger(t);try{let i=Dc(this.options,this.policyName),a=i.functions.getAnchorDate(e,t,this.policyName),u=i.functions.getQuotaDetail(e,t,this.policyName),[c,l]=await Promise.all([a,u]),d=Mc(l.key,this.policyName);o&&t.log.debug(`QuotaInboundPolicy: key - '${d}'`);let p=Ke(this.policyName,r),f=await p.getQuota(d,t.requestId);o&&t.log.debug("QuotaInboundPolicy: quotaResult",f),c&&new Date(f.anchorDate)!==c&&t.log.warn(`QuotaInboundPolicy '${this.policyName}' provided anchorDate ('${c}') did not match the stored, immutable anchorDate ('${f.anchorDate}')`);let y=Object.assign({},i.defaultAllowances);Object.assign(y,l.allowances);let O=[],P="";if(Object.entries(y).forEach(([v,N])=>{o&&(P+=`${v} - allowed: ${N} value: ${f.meters[v]??0}
|
|
62
|
+
`),(f.meters[v]??0)>=N&&O.push(v)}),o&&t.log.debug("QuotaInboundPolicy: debugTable",P),O.length>0)return x.tooManyRequests(e,t,{detail:`Quota exceeded for meters '${O.join(", ")}'`});t.addResponseSendingFinalHook(async(v,N,k)=>{if(o&&k.log.debug(`QuotaInboundPolicy: backend response - ${v.status}: ${v.statusText}`),!i.quotaOnStatusCodes.includes(v.status))return;let j=se.get(k,_r),q={config:{period:i.period,anchorDate:c?.toISOString()??""},increments:j};o&&k.log.debug("QuotaInboundPolicy: setQuotaDetails",q),await p.setQuota(d,q,k.requestId)})}catch(i){r.error(i),t.log.error(i)}return e}static setMeters(e,t){let o=se.get(e,_r)??{};Object.assign(o,t),se.set(e,_r,o)}};function Dc(n,e){let t=s(async i=>({key:`user-1385b4e8-800f-488e-b089-c197544e5801-${i.user?.sub}`,allowances:n.allowances??{}}),"getQuotaDetail"),o=s(async()=>{},"getAnchorDate");if(n.quotaBy==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getQuotaDetailExport===void 0)throw new m(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getQuotaDetailExport' is required when 'quotaBy' is 'function'`);t=n.identifier.module[n.identifier.getQuotaDetailExport]}if(n.quotaAnchorMode==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getAnchorDateExport===void 0)throw new m(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getAnchorDateExport' is required when 'quotaAnchorMode' is 'function'`);o=n.identifier.module[n.identifier.getAnchorDateExport]}return{period:n.period,quotaBy:n.quotaBy??"user",quotaAnchorMode:n.quotaAnchorMode??"first-api-call",quotaOnStatusCodes:je(n.quotaOnStatusCodes??"200-299"),defaultAllowances:Object.assign({},n.allowances),functions:{getQuotaDetail:t,getAnchorDate:o}}}s(Dc,"validateAndParseOptions");function Mc(n,e){return encodeURIComponent(`${e}-${n}`)}s(Mc,"processKey");var qc=s(async(n,e,t)=>{g("policy.inbound.clear-headers");let o=[...t.exclude??[]],r=new Headers;return o.forEach(a=>{let u=n.headers.get(a);u&&r.set(a,u)}),new te(n,{headers:r})},"ClearHeadersInboundPolicy");var Hc=s(async(n,e,t,o)=>{g("policy.outbound.clear-headers");let r=[...o.exclude??[]],i=new Headers;return r.forEach(u=>{let c=n.headers.get(u);c&&i.set(u,c)}),new Response(n.body,{headers:i,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var Uc=s(async(n,e,t,o)=>{g("policy.inbound.clerk-jwt-auth");let r=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),i=new URL(r);return i.pathname="/.well-known/jwks.json",we(n,e,{issuer:r.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)},"ClerkJwtInboundPolicy");var Zc=s(async(n,e,t,o)=>{if(g("policy.inbound.cognito-jwt-auth"),!t.userPoolId)throw new m("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new m("region must be set in the options for CognitoJwtInboundPolicy");return we(n,e,{issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,jwkUrl:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)},"CognitoJwtInboundPolicy");var Vs=Je(Qe());var Fc=s(n=>{let e=n.headers.get("x-real-ip")??n.headers.get("true-client-ip")??n.headers.get("cf-connecting-ip");if(e)return e;let t=n.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP");function yt(n,e){return{function:Bc(e,"RateLimitInboundPolicy",n),user:jc,ip:$c,all:zc}[e.rateLimitBy??"ip"]}s(yt,"getRateLimitByFunctions");var $c=s(async n=>({key:`ip-${Fc(n)}`}),"getIP"),jc=s(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),zc=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll");function Bc(n,e,t){let o;if(n.rateLimitBy==="function"){if(!n.identifier)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(o=n.identifier.module[n.identifier.export],!o||typeof o!="function")throw new m(`${e} '${t}' - Custom rate limit function must be a valid function`)}return s(async(i,a,u)=>{let c=await o(i,a,u);if(!c||typeof c!="object"){let l=`${e} '${u}' - Custom rate limit function must return a valid object.`;throw a.log.error(l),new L(l)}if(!("key"in c)){let l=`${e} '${u}' - Custom rate limit function must return a valid key property.`;throw a.log.error(l,c),new L(l)}if(typeof c.key!="string"){let l=`${e} '${u}' - Custom rate limit function must return a valid key property of type string. Received type '${typeof c.key}'`;throw a.log.error(l),new L(l)}return c},"outerFunction")}s(Bc,"wrapUserFunction");var bt="Retry-After";var Gs=(0,Vs.debug)("zuplo:policies:ComplexRateLimitInboundPolicy"),Dr=Symbol("complex-rate-limit-counters"),Mr=class n extends ae{static{s(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let o=se.get(e,Dr)??{};Object.assign(o,t),se.set(e,Dr,t)}static getIncrements(e){return se.get(e,Dr)??{}}constructor(e,t){super(e,t),g("policy.inbound.complex-rate-limit-inbound"),W(e,t).required("rateLimitBy","string").required("timeWindowMinutes","number").required("limits","object").optional("headerMode","string").optional("throwOnFailure","boolean").optional("mode","string").optional("identifier","object"),e.identifier&&W(e.identifier,t,"policy","identifier").required("export","string").required("module","object");for(let[o,r]of Object.entries(e.limits))if(typeof r!="number")throw new m(`ComplexRateLimitInboundPolicy '${this.policyName}' - The value of the limits must be numbers. The limit ${o} is set to type '${typeof e}'.`)}async handler(e,t){let o=Date.now(),r=Q.getLogger(t),i=Ke(this.policyName,r),a=s((c,l)=>{if(this.options.throwOnFailure)throw new J(c,{cause:l});r.error(c,l)},"throwOrLog"),u=s((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[bt]=l.toString()),x.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l=await yt(this.policyName,this.options)(e,t,this.policyName),d=h.instance.isTestMode||h.instance.isWorkingCopy?h.instance.build.BUILD_ID:"",p=Object.assign({},this.options.limits,l.limits),f=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;t.addResponseSendingFinalHook(async()=>{try{let v=n.getIncrements(t);Gs(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(v)}`);let N=Object.entries(p).map(([j])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${j}`,ttlSeconds:f,increment:v[j]??0})),k=i.multiIncrement(N,t.requestId);t.waitUntil(k),await k}catch(v){r.error(v),t.log.error(v)}});let y=Object.entries(p).map(([v,N])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${v}`,ttlSeconds:f,limit:N})),O=await i.multiCount(y,t.requestId);return Gc(O,y).length>0?u(this.options.headerMode??"retry-after",f):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-o;Gs(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function Gc(n,e){let t=[];for(let o of n){let r=e.find(i=>i.key===o.key)?.limit||0;o.count>=r&&t.push(o)}return t}s(Gc,"findOverLimits");var Vc=s(async(n,e,t,o)=>{if(g("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new m(`CompositeInboundPolicy '${o}' must have valid policies defined`);let r=he.instance,i=Mt(t.policies,r?.routeData.policies);return Eo(i)(n,e)},"CompositeInboundPolicy");var Wc=s(async(n,e,t,o)=>{g("policy.inbound.curity-phantom-token-auth");let r=n.headers.get("Authorization");if(!r)return x.unauthorized(n,e,{detail:"No authorization header"});let i=Kc(r);if(!i)return x.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await ie(o,void 0,t),u=new oe(a,e),c=await u.get(i);if(!c){let l=await F.fetch(t.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${t.clientId}:${t.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+i+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(i,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),x.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):x.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function Kc(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}s(Kc,"getToken");var Jc=s(async(n,e,t,o)=>(g("policy.inbound.firebase-jwt-auth"),W(t,o).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),we(n,e,{issuer:`https://securetoken.google.com/${t.projectId}`,audience:t.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)),"FirebaseJwtInboundPolicy");var Qc=s(async(n,e,t)=>{g("policy.inbound.form-data-to-json");let o="application/x-www-form-urlencoded",r="multipart/form-data",i=n.headers.get("content-type")?.toLowerCase();if(!i||![r,o].includes(i))return t&&t.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${o}' or ${r}`,{status:400,statusText:"Bad Request"}):n;let a=await n.formData();if(t&&t.optionalHoneypotName&&a.get(t.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(n.headers);return c.set("content-type","application/json"),c.delete("content-length"),new te(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var wt="__unknown__",Xc=s(async(n,e,t,o)=>{g("policy.inbound.geo-filter");let r={allow:{countries:Pt(t.allow?.countries,"allow.countries",o),regionCodes:Pt(t.allow?.regionCodes,"allow.regionCode",o),asns:Pt(t.allow?.asns,"allow.asOrganization",o)},block:{countries:Pt(t.block?.countries,"block.countries",o),regionCodes:Pt(t.block?.regionCodes,"block.regionCode",o),asns:Pt(t.block?.asns,"block.asOrganization",o)},ignoreUnknown:t.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??wt,a=e.incomingRequestProperties.regionCode?.toLowerCase()??wt,u=e.incomingRequestProperties.asn?.toString()??wt,c=r.ignoreUnknown&&i===wt,l=r.ignoreUnknown&&a===wt,d=r.ignoreUnknown&&u===wt,p=r.allow.countries,f=r.allow.regionCodes,y=r.allow.asns;if(p.length>0&&!p.includes(i)&&!c||f.length>0&&!f.includes(a)&&!l||y.length>0&&!y.includes(u)&&!d)return Rt(n,e,o,i,a,u);let O=r.block.countries,P=r.block.regionCodes,v=r.block.asns;return O.length>0&&O.includes(i)&&!c||P.length>0&&P.includes(a)&&!l||v.length>0&&v.includes(u)&&!d?Rt(n,e,o,i,a,u):n},"GeoFilterInboundPolicy");function Rt(n,e,t,o,r,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${o}', regionCode: '${r}', asn: '${i}')`),x.forbidden(n,e,{geographicContext:{country:o,regionCode:r,asn:i}})}s(Rt,"blockedResponse");function Pt(n,e,t){if(typeof n=="string")return n.split(",").map(o=>o.trim().toLowerCase());if(typeof n>"u")return[];if(Array.isArray(n))return n.map(o=>o.trim().toLowerCase());throw new m(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}s(Pt,"toLowerStringArray");var Yc=s(async(n,e,t)=>{g("policy.inbound.jwt-scope-validation");let o=n.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(u=>i.includes(u)),"scopeChecker")(o,t.scopes)){let i={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(i),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var el=s(async(n,e,t,o)=>{g("policy.inbound.mock-api");let r=e.route.raw().responses;if(!r)return qr(o,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(r),a=[];if(i.length===0)return qr(o,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(i.forEach(u=>{r[u].content&&Object.keys(r[u].content).forEach(l=>{let d=r[u].content[l].examples;d&&Object.keys(d).forEach(f=>{a.push({responseName:u,contentName:l,exampleName:f,exampleValue:d[f]})})})}),a=a.filter(u=>!(t.responsePrefixFilter&&!u.responseName.startsWith(t.responsePrefixFilter)||t.contentType&&u.contentName!==t.contentType||t.exampleName&&u.exampleName!==t.exampleName)),t.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return Ws(a[u])}else return a.length>0?Ws(a[0]):qr(o,n,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function Ws(n){let e=JSON.stringify(n.exampleValue,null,2),t=new Headers;switch(t.set("Content-Type",n.contentName),n.responseName){case"1XX":return new Response(e,{status:100,headers:t});case"2XX":return new Response(e,{status:200,headers:t});case"3XX":return new Response(e,{status:300,headers:t});case"4XX":return new Response(e,{status:400,headers:t});case"5XX":case"default":return new Response(e,{status:500,headers:t});default:return new Response(e,{status:Number(n.responseName),headers:t})}}s(Ws,"generateResponse");var qr=s((n,e,t,o)=>{let r=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${o}`;return x.internalServerError(e,t,{detail:r})},"getProblemDetailResponse");var tl="Incoming",nl={logRequestBody:!0,logResponseBody:!0};function Ks(n){let e={};return n.forEach((t,o)=>{e[o]=t}),e}s(Ks,"headersToObject");function Js(){return new Date().toISOString()}s(Js,"timestamp");var Hr=new WeakMap,ol={};function rl(n,e){let t=Hr.get(n);t||(t=ol);let o=Object.assign({...t},e);Hr.set(n,o)}s(rl,"setMoesifContext");async function Qs(n,e){let t=n.headers.get("content-type");if(t&&t.indexOf("json")!==-1)try{return await n.clone().json()}catch(r){e.log.error(r)}let o=await n.clone().text();return e.log.debug({textBody:o}),o}s(Qs,"readBody");var il={},Ur;function Xs(){if(!Ur)throw new L("Invalid State - no _lastLogger");return Ur}s(Xs,"getLastLogger");function sl(n){let e=il[n];return e||(e=new X("moesif-inbound",100,async t=>{let o=JSON.stringify(t);Xs().debug("posting",o);let r=await F.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:o});r.ok||Xs().error({status:r.status,body:await r.text()})})),e}s(sl,"getDispatcher");async function al(n,e,t,o){g("policy.inbound.moesif-analytics"),Ur=e.log;let r=Js(),i=Object.assign(nl,t);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${o}' - applicationId is required`);let a=i.logRequestBody?await Qs(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=sl(i.applicationId),d=n.headers.get("true-client-ip"),p=Hr.get(e)??{},f={time:r,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Ks(n.headers)},y=i.logResponseBody?await Qs(u,e):void 0,O={time:Js(),status:u.status,headers:Ks(u.headers),body:y},P={request:f,response:O,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:tl};l.enqueue(P),e.waitUntil(l.waitUntilFlushed())}),n}s(al,"MoesifInboundPolicy");async function Ys(n,e,t,o){let r=Q.getLogger(n),{authApiJWT:i,meteringServiceUrl:a}=h.instance,u;try{let l=await F.fetch(`${a}/internal/v1/metering/${o}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":n.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error loading subscription. ${l.status} - ${p}`),r.error(`MonetizationInboundPolicy '${t}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){r.error(`MonetizationInboundPolicy '${t}' - Error loading subscription`,l)}let c=u&&u.data&&u.data.length>0?u.data:void 0;return c&&c.length>1?c.sort((d,p)=>d.createdOn>p.createdOn?-1:1)[0]:c&&c[0]}s(Ys,"loadSubscription");async function ea(n,e,t,o,r){let{authApiJWT:i,meteringServiceUrl:a}=h.instance,u=Q.getLogger(n);try{let c=await F.fetch(`${a}/internal/v1/metering/${o}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":n.requestId},method:"POST",body:JSON.stringify({meters:r})});if(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`,c)}}s(ea,"consumeSubcriptionQuotas");var ul=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function An(n,e){try{let t=[];for(let o in n)typeof n[o]!="number"&&!(Number.isInteger(n[o])&&/^-?\d+$/.test(n[o].toString()))&&t.push(o);if(t.length>0)throw new m(t.length>1?`The values found in these properties are not integers : ${t.join(", ")}`:`The value in property '${t[0]}' is not an integer`)}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}s(An,"validateMeters");function ta(n,e){if(n)try{if(n.length===0)throw new m("Must set valid subscription statuses");let t=ot(n),o=[];for(let r of t)ul.has(r)||o.push(r);if(o.length>0)throw new m(`Found the following invalid statuses: ${o.join(", ")}`);return n}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}s(ta,"parseAllowedSubscriptionStatuses");function na(n,e){let t={},o={};for(let r in e)n.hasOwnProperty(r)?t[r]=e[r]:o[r]=e[r];return{metersInSubscription:t,metersNotInSubscription:o}}s(na,"compareMeters");var Zr=class extends ae{static{s(this,"MonetizationInboundPolicy")}static getSubscription(e){return se.get(e,St)}static setMeters(e,t){An(t,"setMeters");let o=se.get(e,Ct)??{};Object.assign(o,t),se.set(e,Ct,o)}constructor(e,t){super(e,t),g("policy.inbound.monetization")}async handler(e,t){W(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let o=this.options.allowRequestsOverQuota??!1,r=je(this.options.meterOnStatusCodes),i=se.get(t,Ct),a={...this.options.meters,...i};An(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=ta(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(P,v,N)=>{let k=se.get(N,St);if((this.options.allowRequestsWithoutSubscription??!1)&&!k){N.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(Re.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let q=se.get(N,Ct),$={...this.options.meters,...q};if(An($,this.policyName),r.includes(P.status)&&k&&$){N.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${k.id}' with meters '${JSON.stringify($)} on response status '${P.status}'`);let{metersInSubscription:E,metersNotInSubscription:H}=na(k.meters,$);if(H&&Object.keys(H).length>0){let G=Object.keys(H);N.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${G}'`)}await ea(N,k.id,this.policyName,this.options.bucketId,E)}});let l=e.user;if(!l)return u?e:x.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(Re.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Re.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await Ys(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:x.unauthorized(e,t,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return t.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),x.unauthorized(e,t,{detail:"No valid subscription found"});c.includes(p.status)&&(t.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),se.set(t,St,p));let f=se.get(t,St);if(!f)return u?e:(t.log.warn("Subscription is not available for user"),x.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(f&&Object.keys(f.meters).length===0)return t.log.error(`Quota is not set up for subscription '${f.id}'`),x.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let O=Object.keys(a).filter(P=>!Object.keys(f.meters).includes(P));if(O.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${O.join(", ")}`),x.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${O.join(", ")}`,title:"Quota Exceeded"});for(let P of Object.keys(a))if(f.meters[P].available<=0&&!o)return x.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${P}'`,title:"Quota Exceeded"});return e}};async function kn(n,e){let t=new URLSearchParams({client_id:n.clientId,client_secret:n.clientSecret,grant_type:"client_credentials"});n.scope&&t.append("scope",n.scope),n.audience&&t.append("audience",n.audience);let o=await fe({retries:n.retries?.maxRetries??3,retryDelayMs:n.retries?.delayMs??10},n.tokenEndpointUrl,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(o.status!==200){try{let i=await o.text();e.log.error(`Error getting token from identity provider. Status: ${o.status}`,i)}catch{}throw new L("Error getting token from identity provider.")}let r=await o.json();if(r&&typeof r=="object"&&"access_token"in r&&typeof r.access_token=="string"&&"expires_in"in r&&typeof r.expires_in=="number")return{access_token:r.access_token,expires_in:r.expires_in};throw new L("Response returned from identity provider is not in the expected format.")}s(kn,"getClientCredentialsAccessToken");var It=class extends Error{constructor(t,o,r){super(o,r);this.code=t}static{s(this,"OpenFGAError")}},Ln=class{static{s(this,"BaseOpenFGAClient")}apiUrl;storeId;authorizationModelId;constructor(e){this.apiUrl=e.apiUrl,this.storeId=e.storeId,this.authorizationModelId=e.authorizationModelId}getStoreId(e={},t=!1){let o=e?.storeId||this.storeId;if(!t&&!o)throw new Error("storeId is required");return o}getAuthorizationModelId(e={}){return e?.authorizationModelId||this.authorizationModelId}async get(e,t){return this.fetch(e,"GET",t)}async put(e,t,o){return this.fetch(e,"PUT",o,t)}post(e,t,o){return this.fetch(e,"POST",o,t)}async fetch(e,t,o,r){let i=new Headers(o.headers||{});i.set("Content-Type","application/json"),i.set("Accept","application/json"),i.set("User-Agent",h.instance.systemUserAgent);let a=`${this.apiUrl}${e}`,u=new Request(a,{method:t,headers:i,body:r?JSON.stringify(r):void 0}),c=await F.fetch(u);if(c.status!==200){let l;try{l=await c.json()}catch{}throw!l||!l.code||!l.message?new It("unknown",`Unknown error. Status: ${c.status}`):new It(l.code,l.message)}return c.json()}};function Vt(n,e,t){!n[e]&&t&&(n[e]=t)}s(Vt,"setHeaderIfNotSet");var oa="X-OpenFGA-Client-Method",ra="X-OpenFGA-Client-Bulk-Request-Id",Wt=class extends Ln{static{s(this,"OpenFGAClient")}async check(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/check`,{tuple_key:{user:e.user,relation:e.relation,object:e.object},context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]},authorization_model_id:this.getAuthorizationModelId(t)},t)}async batchCheck(e,t={}){let{headers:o={}}=t;return Vt(o,oa,"BatchCheck"),Vt(o,ra,crypto.randomUUID()),{responses:await Promise.all(e.map(async i=>this.check(i,Object.assign({},t,o)).then(a=>(a._request=i,a)).catch(a=>{if(a instanceof It)throw a;return{allowed:void 0,error:a,_request:i}})))}}async expand(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/expand`,{authorization_model_id:this.getAuthorizationModelId(t),tuple_key:e},t)}async listObjects(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-objects`,{authorization_model_id:this.getAuthorizationModelId(t),user:e.user,relation:e.relation,type:e.type,context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]}},t)}async listRelations(e,t={}){let{user:o,object:r,relations:i,contextualTuples:a,context:u}=e,{headers:c={}}=t;if(Vt(c,oa,"ListRelations"),Vt(c,ra,crypto.randomUUID()),!i?.length)throw new Error("When calling listRelations, at least one relation must be passed in the relations field");let l=await this.batchCheck(i.map(p=>({user:o,relation:p,object:r,contextualTuples:a,context:u})),Object.assign({},t,c)),d=l.responses.find(p=>p.error);if(d)throw d.error;return{relations:l.responses.filter(p=>p.allowed).map(p=>p._request.relation)}}async listUsers(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-users`,{authorization_model_id:this.getAuthorizationModelId(t),relation:e.relation,object:e.object,user_filters:e.user_filters,context:e.context,contextual_tuples:e.contextualTuples||[]},t)}};var ia=Symbol("openfga-authz-context-data"),Et=class extends ae{static{s(this,"BaseOpenFGAAuthZInboundPolicy")}client;authorizer;cache;static setContextChecks(e,t){let o=Array.isArray(t)?t:[t];se.set(e,ia,o)}constructor(e,t){if(super(e,t),W(e,t).required("apiUrl","string").optional("storeId","string").optional("authorizationModelId","string"),!e.credentials)throw new m(`${this.policyType} '${this.policyName}' - The 'credentials' option is required.`);if(e.credentials.method==="client-credentials")W(e.credentials,t).required("clientId","string").required("clientSecret","string").required("oauthTokenEndpointUrl","string").optional("apiAudience","string");else if(e.credentials.method==="api-token")W(e.credentials,t).required("token","string").optional("headerName","string").optional("headerValuePrefix","string");else if(e.credentials.method==="header")W(e.credentials,t).optional("headerName","string");else if(e.credentials.method!=="none")throw new m(`${this.policyType} '${this.policyName}' - The 'credentials.type' option is invalid. It must be set to either 'none', 'api-token', 'client-credentials', or 'header'.`);this.authorizer=this.getAuthorizer(e.credentials),this.client=new Wt({apiUrl:e.apiUrl,storeId:e.storeId,authorizationModelId:e.authorizationModelId})}async handler(e,t){if(!this.cache){let a=await ie(this.policyName,void 0,this.options);this.cache=new oe(a,t)}let o=s(a=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:a}),"forbiddenResponse"),r=se.get(t,ia);if(!r||r.length===0)throw new L(`${this.policyType} '${this.policyName}' - No checks found in the context.`);let i=await this.authorizer(e,t);try{t.log.debug("OpenFGA checks",r);let a=await this.client.batchCheck(r,{headers:i});return t.log.debug("OpenFGA Response",a),a.responses.every(u=>u.allowed)?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),o("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling OpenFGA service`,a),x.internalServerError(e,t)}}getAuthorizer(e){if(e.method==="none")return async()=>({});if(e.method==="header")return async t=>{let o=e.headerName??"Authorization",r=t.headers.get(o);if(!r)throw new J(`${this.policyType} '${this.policyName}' - The header '${o}' is missing.`);return{[o]:r}};if(e.method==="api-token")return async()=>({[e.headerName??"Authorization"]:`${e.headerValuePrefix??"Bearer "} ${e.token}`});if(e.method==="client-credentials")return async(t,o)=>{let r=await this.cache?.get("client_credentials_token");if(r)return{Authorization:`Bearer ${r}`};let i=await kn({tokenEndpointUrl:e.oauthTokenEndpointUrl,clientId:e.clientId,clientSecret:e.clientSecret,audience:e.apiAudience},o);return this.cache?.put("client_credentials_token",i.access_token,i.expires_in),{Authorization:`Bearer ${i.access_token}`}};throw new L("Invalid state for credentials method is not valid. This should not happen.")}};var sa=["us1","eu1","au1"],Fr=class extends Et{static{s(this,"OktaFGAAuthZInboundPolicy")}constructor(e,t){if(!sa.includes(e.region))throw new m(`OktaFGAAuthZInboundPolicy '${t}' - The 'region' option is invalid. Must be one of ${sa.join(", ")}.`);let o={...e,apiUrl:`https://api.${e.region}.fga.dev`,credentials:{method:"client-credentials",oauthTokenEndpointUrl:"https://fga.us.auth0.com/oauth/token",clientId:e.credentials.clientId,clientSecret:e.credentials.clientSecret,apiAudience:`https://api.${e.region}.fga.dev/`}};super(o,t),g("policy.inbound.oktafga-authz")}};var cl=s(async(n,e,t,o)=>(g("policy.inbound.okta-jwt-auth"),we(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},o)),"OktaJwtInboundPolicy");var $r=class extends Et{static{s(this,"OpenFGAAuthZInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.openfga-authz")}};import{importSPKI as ll}from"jose";var jr,dl=s(async(n,e,t,o)=>{if(g("policy.inbound.propel-auth-jwt-auth"),!jr)try{jr=await ll(t.verifierKey,"RS256")}catch(r){throw e.log.error("Could not import verifier key"),r}return we(n,e,{issuer:t.authUrl,secret:jr,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},o)},"PropelAuthJwtInboundPolicy");var da=Je(Qe());var ua=Je(Qe());var aa=(0,ua.debug)("zuplo:policies:RateLimitInboundPolicy"),ca=s(async(n,e,t,o)=>{let r=Q.getLogger(e),i=s(($,E)=>{let H={};return(!$||$==="retry-after")&&(H[bt]=E.toString()),x.tooManyRequests(n,e,void 0,H)},"rateLimited"),u=await yt(o,t)(n,e,o),c=u.key,l=u.requestsAllowed??t.requestsAllowed,d=u.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",f=Ke(o,r),O=`rate-limit${h.instance.isTestMode?h.instance.build.BUILD_ID:""}/${o}/${c}`,P=await ie(o,void 0,t),v=new oe(P,e),N=f.getCountAndUpdateExpiry(O,d,e.requestId),k;s(async()=>{let $=await N;if($.count>l){let E=Date.now()+$.ttlSeconds*1e3;v.put(O,E,$.ttlSeconds),aa(`RateLimitInboundPolicy '${o}' - returning 429 from redis for '${O}' (async mode)`),k=i(p,$.ttlSeconds)}},"asyncCheck")();let q=await v.get(O);if(q!==void 0&&q>Date.now()){aa(`RateLimitInboundPolicy '${o}' - returning 429 from cache for '${O}' (async mode)`);let $=Math.round((q-Date.now())/1e3);return i(p,$)}return e.addResponseSendingHook(async $=>k??$),n},"AsyncRateLimitInboundPolicyImpl");var la=(0,da.debug)("zuplo:policies:RateLimitInboundPolicy"),pl="strict",pa=s(async(n,e,t,o)=>{if(g("policy.inbound.rate-limit"),(t.mode??pl)==="async")return ca(n,e,t,o);let i=Date.now(),a=Q.getLogger(e),u=s((l,d)=>{if(t.throwOnFailure)throw new J(l,{cause:d});a.error(l,d)},"throwOrLog"),c=s((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[bt]=d.toString()),x.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await yt(o,t)(n,e,o),p=d.key,f=d.requestsAllowed??t.requestsAllowed,y=d.timeWindowMinutes??t.timeWindowMinutes,O=t.headerMode??"retry-after",P=Ke(o,a),N=`rate-limit${h.instance.isTestMode||h.instance.isWorkingCopy?h.instance.build.BUILD_ID:""}/${o}/${p}`,k=await P.getCountAndUpdateExpiry(N,y,e.requestId);return k.count>f?(la(`RateLimitInboundPolicy '${o}' - returning 429 from redis for '${N}' (strict mode)`),c(O,k.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-i;la(`RateLimitInboundPolicy '${o}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var zr;function ma(n){let e=[];for(let[t,o]of n)e.push({name:t,value:o});return e}s(ma,"headersToNameValuePairs");function ml(n){let e=[];return Object.entries(n).forEach(([t,o])=>{e.push({name:t,value:o})}),e}s(ml,"queryToNameValueParis");function gl(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}s(gl,"parseIntOrUndefined");var ga={};async function fl(n,e,t,o){g("policy.inbound.readme-metrics");let r=new Date,i=Date.now();return zr||(zr={name:"zuplo",version:h.instance.build.ZUPLO_VERSION,comment:`zuplo/${h.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?nt(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?nt(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:h.instance.isWorkingCopy||h.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:zr,entries:[{startedDateTime:r.toISOString(),time:Date.now()-i,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:ma(n.headers),queryString:ml(n.query)},response:{status:a.status,statusText:a.statusText,headers:ma(a.headers),content:{size:gl(n.headers.get("content-length"))}}}]}}},d=ga[t.apiKey];if(!d){let p=t.apiKey;d=new X("readme-metering-inbound-policy",10,async f=>{try{let y=t.url??"https://metrics.readme.io/request",O=await F.fetch(y,{method:"POST",body:JSON.stringify(f),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});O.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${o}'. ${O.status}: '${await O.text()}'`)}catch(y){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${o}': '${y.message}'`),y}}),ga[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}s(fl,"ReadmeMetricsInboundPolicy");var hl=s(async(n,e,t,o)=>{g("policy.inbound.remove-headers");let r=t?.headers;if(!r||!Array.isArray(r)||r.length===0)throw new m(`RemoveHeadersInboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let i=new Headers(n.headers);return r.forEach(u=>{i.delete(u)}),new te(n,{headers:i})},"RemoveHeadersInboundPolicy");var yl=s(async(n,e,t,o,r)=>{g("policy.outbound.remove-headers");let i=o?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new m(`RemoveHeadersOutboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let a=new Headers(n.headers);return i.forEach(c=>{a.delete(c)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var bl=s(async(n,e,t,o)=>{g("policy.inbound.remove-query-params");let r=t.params;if(!r||!Array.isArray(r)||r.length===0)throw new m(`RemoveQueryParamsInboundPolicy '${o}' options.params must be a non-empty string array of header names`);let i=new URL(n.url);return r.forEach(u=>{i.searchParams.delete(u)}),new te(i.toString(),n)},"RemoveQueryParamsInboundPolicy");var wl=s(async(n,e,t,o)=>{g("policy.outbound.replace-string");let r=await n.text(),i=o.mode==="regexp"?new RegExp(o.match,"gm"):o.match,a=r.replaceAll(i,o.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var fa=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Rl=s(async(n,e,t)=>{g("policy.inbound.request-size-limit");let o=t.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(n.method))return n;let r=n.headers.get("content-length"),i=r!==null?parseInt(r):void 0;return i&&!isNaN(i)&&i>t.maxSizeInBytes?fa():i&&o?n:(await n.clone().text()).length>t.maxSizeInBytes?fa():n},"RequestSizeLimitInboundPolicy");var xt=s(n=>{let e=n.route.raw();return e.parameters?e.parameters.map(o=>({name:o.name,location:o.in,required:o.required,deprecated:o.deprecated,allowEmptyValue:o.allowEmptyValue})):[]},"getParametersForOperation"),Tt=s((n,e,t,o,r)=>{let i=[],a=!0,u=[];return n.forEach(c=>{let l=c.required||r==="path";if(l&&!e[c.name])a=!1,i.push(`Required ${r} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=qn(t,o,r,c.name),p=he.instance.schemaValidator[d],f=p(e[c.name]),y=Br(p.errors);f||(a=!1,u.push(`${r} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${r} parameter: '${c.name}' ${y.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),Oe=s((n,e,t,o,r)=>{o?n.log[e](t,o,r):n.log[e](t,r)},"logErrors"),Ae=s(n=>n==="log-only"||n==="reject-and-log","shouldLog"),ke=s(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),Br=s(n=>n?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function ha(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let o;try{o=await e.clone().json()}catch(y){let O=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,P=x.badRequest(e,n,{detail:`${O}, see errors property for more details`,errors:`${y}`});if(Ae(t.validateBody)&&Oe(n,t.logLevel??"info",O,[o],y),ke(t.validateBody))return P}if(!e.headers.get("Content-Type")){let y=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,O=x.badRequest(e,n,{detail:y});return Ae(t.validateBody)&&Oe(n,t.logLevel??"info",y,[o],[y]),ke(t.validateBody)?O:void 0}let r=e.headers.get("Content-Type"),i=r.indexOf(";");i>-1&&(r=r.substring(0,i));let a=Hn(n.route.path,e.method,r),u=he.instance.schemaValidator[a];if(!u){let y=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,O=x.badRequest(e,n,{detail:y});return Ae(t.validateBody)&&Oe(n,t.logLevel??"info",y,[o],[y]),ke(t.validateBody)?O:void 0}if(u(o))return;let l=u.errors,d="Request body did not pass validation",p=Br(l),f=x.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(Ae(t.validateBody)&&Oe(n,t.logLevel??"info",d,[o],p),ke(t.validateBody))return f}s(ha,"handleBodyValidation");function ya(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let o={};e.headers.forEach((a,u)=>{o[u]=a});let r=xt(n),i=Tt(r.filter(a=>a.location==="header"),o,n.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=x.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:i.errors});if(Ae(t.validateHeaders)&&Oe(n,t.logLevel??"info",a,i.invalidValues,i.errors),ke(t.validateHeaders))return u}}s(ya,"handleHeadersValidation");function ba(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let o=xt(n),r=Tt(o.filter(i=>i.location==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!r.isValid){let i="Path parameters validation failed",a=x.badRequest(e,n,{detail:`${i}, see errors property for more details`,errors:r.errors});if(Ae(t.validatePathParameters)&&Oe(n,t.logLevel??"info",i,r.invalidValues,r.errors),ke(t.validatePathParameters))return a}}s(ba,"handlePathParameterValidation");function wa(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let o=xt(n),r=Tt(o.filter(i=>i.location==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!r.isValid){let i="Query parameters validation failed",a=x.badRequest(e,n,{detail:`${i}, see errors property for more details`,errors:r.errors});if(Ae(t.validateQueryParameters)&&Oe(n,t.logLevel??"info",i,r.invalidValues,r.errors),ke(t.validateQueryParameters))return a}}s(wa,"handleQueryParameterValidation");var Ra=s(async(n,e,t)=>{g("policy.inbound.request-validation");let o=wa(e,n,t);if(o!==void 0||(o=ba(e,n,t),o!==void 0)||(o=ya(e,n,t),o!==void 0))return o;let r=await ha(e,n,t);return r!==void 0?r:n},"RequestValidationInboundPolicy"),Pl=Ra;var Il=s(async(n,e,t,o)=>{if(g("policy.inbound.require-origin"),t.origins===void 0||t.origins.length===0)throw new m(`RequireOriginInboundPolicy '${o}' configuration error - no allowed origins specified`);let r=typeof t.origins=="string"?t.origins.split(","):t.origins;r=r.map(a=>a.trim());let i=n.headers.get("origin");if(!i||!r.includes(i)){let a=t.failureDetail??"Forbidden";return x.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var El=s(async(n,e,t)=>(g("policy.inbound.set-body"),new te(n,{body:t.body})),"SetBodyInboundPolicy");var xl=s(async(n,e,t,o)=>{g("policy.inbound.set-headers");let r=t.headers;if(!r||!Array.isArray(r)||r.length==0)throw new m(`SetHeadersInboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let i=new Headers(n.headers);return r.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetHeadersInboundPolicy '${o}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new te(n,{headers:i})},"SetHeadersInboundPolicy");var Tl=s(async(n,e,t,o,r)=>{g("policy.outbound.set-headers");let i=o.headers;if(!i||!Array.isArray(i)||i.length==0)throw new m(`SetHeadersOutboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new m(`SetHeadersOutboundPolicy '${r}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"SetHeadersOutboundPolicy");var vl=s(async(n,e,t,o)=>{g("policy.inbound.set-query-params");let r=t.params;if(!r||!Array.isArray(r)||r.length==0)throw new m(`SetQueryParamsInboundPolicy '${o}' options.params must be a valid array of { name, value }`);let i=new URL(n.url);return r.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetQueryParamsInboundPolicy '${o}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new te(i.toString(),n)},"SetQueryParamsInboundPolicy");var Sl=s(async(n,e,t,o,r)=>{if(g("policy.outbound.set-status"),!o.status||isNaN(o.status)||o.status<100||o.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${r}' - status must be a valid number between 100 and 599, not '${o.status}'`);return new Response(n.body,{headers:n.headers,status:o.status,statusText:o.statusText??n.statusText})},"SetStatusOutboundPolicy");var Cl=s(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),Ol=s(async(n,e,t,o)=>{if(g("policy.inbound.sleep"),!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new m(`SleepInboundPolicy '${o} must have a valid options.sleepInMs value`);return await Cl(t.sleepInMs),n},"SleepInboundPolicy");var Al=s(async(n,e,t,o)=>{g("policy.inbound.supabase-jwt-auth"),W(t,o).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let r={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},i=await we(n,e,r,o);if(i instanceof Response)return i;if(!(i instanceof te))throw new J("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return i;let u=n.user?.data.app_metadata;if(!u)throw new L(`SupabaseJwtInboundPolicy policy '${o}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?x.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var kl=s(async(n,e,t,o)=>{g("policy.inbound.upstream-azure-ad-service-auth"),W(t,o).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let r=await ie(o,void 0,t),i=new oe(r,e),a=await i.get(o);if(!a){let u=await Ll(t,e);i.put(o,u.access_token,u.expires_in-(t.expirationOffsetSeconds??300)),a=u.access_token}return n.headers.set("Authorization",`Bearer ${a}`),n},"UpstreamAzureAdServiceAuthInboundPolicy");async function Ll(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),o=await fe({retries:n.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${n.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(o.status!==200){try{let i=await o.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new L("Could not get token from Azure AD")}let r=await o.json();if(r&&typeof r=="object"&&"access_token"in r&&typeof r.access_token=="string"&&"expires_in"in r&&typeof r.expires_in=="number")return{access_token:r.access_token,expires_in:r.expires_in};throw new L("Response returned from Azure AD is not in the expected format.")}s(Ll,"getAccessToken");var Pa="https://accounts.google.com/o/oauth2/token",Gr,_l=s(async(n,e,t,o)=>{g("policy.inbound.upstream-firebase-admin-auth"),W(t,o).required("serviceAccountJson","string"),Gr||(Gr=await xe.init(t.serviceAccountJson));let r={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},i=await ie(o,void 0,t),a=new oe(i,e),u=await a.get(o);if(!u){let c=await _e({serviceAccount:Gr,audience:Pa,payload:r}),l=await pn(Pa,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new L("Invalid OAuth response from Firebase");u=l.access_token,a.put(o,u,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var Nl="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Dl=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Vr,Ml=s(async(n,e,t,o)=>{if(g("policy.inbound.upstream-firebase-user-auth"),W(t,o).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!t.userId&&!t.userIdPropertyPath)throw new m(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${o}'.`);let r={};if(typeof t.developerClaims<"u"){for(let p in t.developerClaims)if(Object.prototype.hasOwnProperty.call(t.developerClaims,p)){if(Dl.indexOf(p)!==-1)throw new m(`Developer claim "${p}" is reserved and cannot be specified.`);r[p]=t.developerClaims[p]}}Vr||(Vr=await xe.init(t.serviceAccountJson));let i=t.userId;if(!i&&!t.userIdPropertyPath){if(!n.user)throw new L("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");i=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new L(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=nt(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new L(`Unable to determine user from for the policy ${o}`);let a=await ie(o,void 0,t),u=new oe(a,e),c={uid:i,claims:r},l=await st(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await _e({serviceAccount:Vr,audience:Nl,payload:c}),f=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,y=await as(f,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!y.idToken)throw new L("Invalid token response from Firebase");d=y.idToken,u.put(l,d,(y.expiresIn?parseInt(y.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var Kt=class{static{s(this,"ZuploServices")}static async getIDToken(e,t){let o=new oe("0c13603a-a19f-4f03-a04a-50aa393f7ffa-zuplo-tokens",e),r=await ie("zuplo-token",void 0,t),i=await o.get(r);if(i)return i;let{authClientId:a,authClientSecret:u,developerApiUrl:c,zuploClientAuthBucketId:l}=h.instance;if(!a||!u)throw new L("Zuplo service authentication is not enabled for this deployment. Contact support assistance.");let d=await kn({tokenEndpointUrl:`${c}/v1/client-auth/${l}/oauth/token`,clientId:a,clientSecret:u,audience:t?.audience},e);return o.put(r,d.access_token,d.expires_in-300),d.access_token}};var Ia="workload-access-token",Ea="service-account-id-token",Wr=class extends ae{static{s(this,"UpstreamGcpFederatedAuthInboundPolicy")}cacheName;normalizedWorkloadIdentityProvider;constructor(e,t){super(e,t),g("policy.inbound.upstream-gcp-federated-auth"),W(e,t).required("audience","string").required("serviceAccountEmail","string").required("workloadIdentityProvider","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number").optional("useMemoryCacheOnly","boolean").optional("tokenLifetime","number"),e.workloadIdentityProvider.startsWith("https://iam.googleapis.com/")?this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider.replace("https://iam.googleapis.com/",""):this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider}async handler(e,t){this.cacheName||(this.cacheName=await ie(this.policyName,void 0,this.options));let o;this.options.useMemoryCacheOnly?o=new Ze(this.cacheName):o=new oe(this.cacheName,t);let r=await o.get(Ia);if(!r){let a=`https://iam.googleapis.com/${this.normalizedWorkloadIdentityProvider}`,u=await Kt.getIDToken(t,{audience:a}),c=await is(this.normalizedWorkloadIdentityProvider,u,{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!c.access_token||!c.expires_in)throw new L("Invalid token response from GCP");r=c.access_token,o.put(Ia,r,c.expires_in-(this.options.expirationOffsetSeconds??300))}let i=await o.get(Ea);if(!i){let a=await ss({serviceAccountEmailOrIdentifier:this.options.serviceAccountEmail,audience:this.options.audience,accessToken:r},{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!a.token)throw new L("Invalid token response from GCP");i=a.token,o.put(Ea,r,3600-(this.options.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${i}`),e}};var Kr,ql=s(async(n,e,t,o)=>{g("policy.inbound.upstream-gcp-jwt"),W(t,o).required("audience","string").required("serviceAccountJson","string"),Kr||(Kr=await xe.init(t.serviceAccountJson));let r=await _e({serviceAccount:Kr,audience:t.audience});return n.headers.set("Authorization",`Bearer ${r}`),n},"UpstreamGcpJwtInboundPolicy");var xa="https://www.googleapis.com/oauth2/v4/token",Jr,Hl=s(async(n,e,t,o)=>{g("policy.inbound.upstream-gcp-service-auth"),W(t,o).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Jr||(Jr=await xe.init(t.serviceAccountJson));let r={};if(t.scopes&&t.audience)throw new m("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let c=ot(t.scopes);r.scope=c.join(" ")}catch(c){throw c instanceof m?new m(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}t.audience&&(r.target_audience=`${t.audience}`);let i=await ie(o,void 0,t),a;t.useMemoryCacheOnly?a=new Ze(i):a=new oe(i,e);let u=await a.get(o);if(!u){let c=await _e({serviceAccount:Jr,audience:xa,payload:r}),l=await pn(xa,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new L("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new L("Invalid token response from GCP");u=l.access_token}a.put(o,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var Ul=s(async(n,e,t)=>{g("policy.inbound.validate-json-schema");let o=n.clone(),r;try{r=await o.json()}catch{return x.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator(r))return n;let{errors:a}=t.validator;if(!a)throw new J("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return x.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var Ta=s(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,o=s((P,v)=>e(P,"name",{value:v,configurable:!0}),"__name"),r=s((P,v)=>s(function(){return v||(0,P[t(P)[0]])((v={exports:{}}).exports,v),v.exports},"__require"),"__commonJS"),i=r({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(P){var v={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(k,j){return j},attributeValueProcessor:function(k,j){return j},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(k,j,q){return k}},N=o(function(k){return Object.assign({},v,k)},"buildOptions");P.buildOptions=N,P.defaultOptions=v}}),a=r({"node_modules/fast-xml-parser/src/util.js"(P){"use strict";var v=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",N=v+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",k="["+v+"]["+N+"]*",j=new RegExp("^"+k+"$"),q=o(function(E,H){let G=[],V=H.exec(E);for(;V;){let S=[];S.startIndex=H.lastIndex-V[0].length;let T=V.length;for(let U=0;U<T;U++)S.push(V[U]);G.push(S),V=H.exec(E)}return G},"getAllMatches"),$=o(function(E){let H=j.exec(E);return!(H===null||typeof H>"u")},"isName");P.isExist=function(E){return typeof E<"u"},P.isEmptyObject=function(E){return Object.keys(E).length===0},P.merge=function(E,H,G){if(H){let V=Object.keys(H),S=V.length;for(let T=0;T<S;T++)G==="strict"?E[V[T]]=[H[V[T]]]:E[V[T]]=H[V[T]]}},P.getValue=function(E){return P.isExist(E)?E:""},P.isName=$,P.getAllMatches=q,P.nameRegexp=k}}),u=r({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(P,v){"use strict";var N=class{static{s(this,"XmlNode")}static{o(this,"XmlNode")}constructor(k){this.tagname=k,this.child=[],this[":@"]={}}add(k,j){k==="__proto__"&&(k="#__proto__"),this.child.push({[k]:j})}addChild(k){k.tagname==="__proto__"&&(k.tagname="#__proto__"),k[":@"]&&Object.keys(k[":@"]).length>0?this.child.push({[k.tagname]:k.child,":@":k[":@"]}):this.child.push({[k.tagname]:k.child})}};v.exports=N}}),c=r({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(P,v){var N=a();function k(S,T){let U={};if(S[T+3]==="O"&&S[T+4]==="C"&&S[T+5]==="T"&&S[T+6]==="Y"&&S[T+7]==="P"&&S[T+8]==="E"){T=T+9;let de=1,K=!1,Y=!1,ve="";for(;T<S.length;T++)if(S[T]==="<"&&!Y){if(K&&$(S,T))T+=7,[entityName,val,T]=j(S,T+1),val.indexOf("&")===-1&&(U[V(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(K&&E(S,T))T+=8;else if(K&&H(S,T))T+=8;else if(K&&G(S,T))T+=9;else if(q)Y=!0;else throw new Error("Invalid DOCTYPE");de++,ve=""}else if(S[T]===">"){if(Y?S[T-1]==="-"&&S[T-2]==="-"&&(Y=!1,de--):de--,de===0)break}else S[T]==="["?K=!0:ve+=S[T];if(de!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:U,i:T}}s(k,"readDocType"),o(k,"readDocType");function j(S,T){let U="";for(;T<S.length&&S[T]!=="'"&&S[T]!=='"';T++)U+=S[T];if(U=U.trim(),U.indexOf(" ")!==-1)throw new Error("External entites are not supported");let de=S[T++],K="";for(;T<S.length&&S[T]!==de;T++)K+=S[T];return[U,K,T]}s(j,"readEntityExp"),o(j,"readEntityExp");function q(S,T){return S[T+1]==="!"&&S[T+2]==="-"&&S[T+3]==="-"}s(q,"isComment"),o(q,"isComment");function $(S,T){return S[T+1]==="!"&&S[T+2]==="E"&&S[T+3]==="N"&&S[T+4]==="T"&&S[T+5]==="I"&&S[T+6]==="T"&&S[T+7]==="Y"}s($,"isEntity"),o($,"isEntity");function E(S,T){return S[T+1]==="!"&&S[T+2]==="E"&&S[T+3]==="L"&&S[T+4]==="E"&&S[T+5]==="M"&&S[T+6]==="E"&&S[T+7]==="N"&&S[T+8]==="T"}s(E,"isElement"),o(E,"isElement");function H(S,T){return S[T+1]==="!"&&S[T+2]==="A"&&S[T+3]==="T"&&S[T+4]==="T"&&S[T+5]==="L"&&S[T+6]==="I"&&S[T+7]==="S"&&S[T+8]==="T"}s(H,"isAttlist"),o(H,"isAttlist");function G(S,T){return S[T+1]==="!"&&S[T+2]==="N"&&S[T+3]==="O"&&S[T+4]==="T"&&S[T+5]==="A"&&S[T+6]==="T"&&S[T+7]==="I"&&S[T+8]==="O"&&S[T+9]==="N"}s(G,"isNotation"),o(G,"isNotation");function V(S){if(N.isName(S))return S;throw new Error(`Invalid entity name ${S}`)}s(V,"validateEntityName"),o(V,"validateEntityName"),v.exports=k}}),l=r({"../../node_modules/strnum/strnum.js"(P,v){var N=/^[-+]?0x[a-fA-F0-9]+$/,k=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var j={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function q(E,H={}){if(H=Object.assign({},j,H),!E||typeof E!="string")return E;let G=E.trim();if(H.skipLike!==void 0&&H.skipLike.test(G))return E;if(H.hex&&N.test(G))return Number.parseInt(G,16);{let V=k.exec(G);if(V){let S=V[1],T=V[2],U=$(V[3]),de=V[4]||V[6];if(!H.leadingZeros&&T.length>0&&S&&G[2]!==".")return E;if(!H.leadingZeros&&T.length>0&&!S&&G[1]!==".")return E;{let K=Number(G),Y=""+K;return Y.search(/[eE]/)!==-1||de?H.eNotation?K:E:G.indexOf(".")!==-1?Y==="0"&&U===""||Y===U||S&&Y==="-"+U?K:E:T?U===Y||S+U===Y?K:E:G===Y||G===S+Y?K:E}}else return E}}s(q,"toNumber"),o(q,"toNumber");function $(E){return E&&E.indexOf(".")!==-1&&(E=E.replace(/0+$/,""),E==="."?E="0":E[0]==="."?E="0"+E:E[E.length-1]==="."&&(E=E.substr(0,E.length-1))),E}s($,"trimZeros"),o($,"trimZeros"),v.exports=q}}),d=r({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(P,v){"use strict";var N=a(),k=u(),j=c(),q=l(),$=class{static{s(this,"OrderedObjParser")}static{o(this,"OrderedObjParser")}constructor(R){this.options=R,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(I,A)=>String.fromCharCode(Number.parseInt(A,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(I,A)=>String.fromCharCode(Number.parseInt(A,16))}},this.addExternalEntities=E,this.parseXml=T,this.parseTextData=H,this.resolveNameSpace=G,this.buildAttributesMap=S,this.isItStopNode=Y,this.replaceEntitiesValue=de,this.readStopNodeData=B,this.saveTextToParentTag=K,this.addChild=U}};function E(R){let I=Object.keys(R);for(let A=0;A<I.length;A++){let z=I[A];this.lastEntities[z]={regex:new RegExp("&"+z+";","g"),val:R[z]}}}s(E,"addExternalEntities"),o(E,"addExternalEntities");function H(R,I,A,z,_,D,ee){if(R!==void 0&&(this.options.trimValues&&!z&&(R=R.trim()),R.length>0)){ee||(R=this.replaceEntitiesValue(R));let Z=this.options.tagValueProcessor(I,R,A,_,D);return Z==null?R:typeof Z!=typeof R||Z!==R?Z:this.options.trimValues?pe(R,this.options.parseTagValue,this.options.numberParseOptions):R.trim()===R?pe(R,this.options.parseTagValue,this.options.numberParseOptions):R}}s(H,"parseTextData"),o(H,"parseTextData");function G(R){if(this.options.removeNSPrefix){let I=R.split(":"),A=R.charAt(0)==="/"?"/":"";if(I[0]==="xmlns")return"";I.length===2&&(R=A+I[1])}return R}s(G,"resolveNameSpace"),o(G,"resolveNameSpace");var V=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function S(R,I,A){if(!this.options.ignoreAttributes&&typeof R=="string"){let z=N.getAllMatches(R,V),_=z.length,D={};for(let ee=0;ee<_;ee++){let Z=this.resolveNameSpace(z[ee][1]),M=z[ee][4],ue=this.options.attributeNamePrefix+Z;if(Z.length)if(this.options.transformAttributeName&&(ue=this.options.transformAttributeName(ue)),ue==="__proto__"&&(ue="#__proto__"),M!==void 0){this.options.trimValues&&(M=M.trim()),M=this.replaceEntitiesValue(M);let ne=this.options.attributeValueProcessor(Z,M,I);ne==null?D[ue]=M:typeof ne!=typeof M||ne!==M?D[ue]=ne:D[ue]=pe(M,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(D[ue]=!0)}if(!Object.keys(D).length)return;if(this.options.attributesGroupName){let ee={};return ee[this.options.attributesGroupName]=D,ee}return D}}s(S,"buildAttributesMap"),o(S,"buildAttributesMap");var T=o(function(R){R=R.replace(/\r\n?/g,`
|
|
63
|
+
`);let I=new k("!xml"),A=I,z="",_="";for(let D=0;D<R.length;D++)if(R[D]==="<")if(R[D+1]==="/"){let Z=b(R,">",D,"Closing Tag is not closed."),M=R.substring(D+2,Z).trim();if(this.options.removeNSPrefix){let Ce=M.indexOf(":");Ce!==-1&&(M=M.substr(Ce+1))}this.options.transformTagName&&(M=this.options.transformTagName(M)),A&&(z=this.saveTextToParentTag(z,A,_));let ue=_.substring(_.lastIndexOf(".")+1);if(M&&this.options.unpairedTags.indexOf(M)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${M}>`);let ne=0;ue&&this.options.unpairedTags.indexOf(ue)!==-1?(ne=_.lastIndexOf(".",_.lastIndexOf(".")-1),this.tagsNodeStack.pop()):ne=_.lastIndexOf("."),_=_.substring(0,ne),A=this.tagsNodeStack.pop(),z="",D=Z}else if(R[D+1]==="?"){let Z=C(R,D,!1,"?>");if(!Z)throw new Error("Pi Tag is not closed.");if(z=this.saveTextToParentTag(z,A,_),!(this.options.ignoreDeclaration&&Z.tagName==="?xml"||this.options.ignorePiTags)){let M=new k(Z.tagName);M.add(this.options.textNodeName,""),Z.tagName!==Z.tagExp&&Z.attrExpPresent&&(M[":@"]=this.buildAttributesMap(Z.tagExp,_,Z.tagName)),this.addChild(A,M,_)}D=Z.closeIndex+1}else if(R.substr(D+1,3)==="!--"){let Z=b(R,"-->",D+4,"Comment is not closed.");if(this.options.commentPropName){let M=R.substring(D+4,Z-2);z=this.saveTextToParentTag(z,A,_),A.add(this.options.commentPropName,[{[this.options.textNodeName]:M}])}D=Z}else if(R.substr(D+1,2)==="!D"){let Z=j(R,D);this.docTypeEntities=Z.entities,D=Z.i}else if(R.substr(D+1,2)==="!["){let Z=b(R,"]]>",D,"CDATA is not closed.")-2,M=R.substring(D+9,Z);z=this.saveTextToParentTag(z,A,_);let ue=this.parseTextData(M,A.tagname,_,!0,!1,!0,!0);ue==null&&(ue=""),this.options.cdataPropName?A.add(this.options.cdataPropName,[{[this.options.textNodeName]:M}]):A.add(this.options.textNodeName,ue),D=Z+2}else{let Z=C(R,D,this.options.removeNSPrefix),M=Z.tagName,ue=Z.rawTagName,ne=Z.tagExp,Ce=Z.attrExpPresent,ri=Z.closeIndex;this.options.transformTagName&&(M=this.options.transformTagName(M)),A&&z&&A.tagname!=="!xml"&&(z=this.saveTextToParentTag(z,A,_,!1));let ii=A;if(ii&&this.options.unpairedTags.indexOf(ii.tagname)!==-1&&(A=this.tagsNodeStack.pop(),_=_.substring(0,_.lastIndexOf("."))),M!==I.tagname&&(_+=_?"."+M:M),this.isItStopNode(this.options.stopNodes,_,M)){let Se="";if(ne.length>0&&ne.lastIndexOf("/")===ne.length-1)D=Z.closeIndex;else if(this.options.unpairedTags.indexOf(M)!==-1)D=Z.closeIndex;else{let Mn=this.readStopNodeData(R,ue,ri+1);if(!Mn)throw new Error(`Unexpected end of ${ue}`);D=Mn.i,Se=Mn.tagContent}let Dn=new k(M);M!==ne&&Ce&&(Dn[":@"]=this.buildAttributesMap(ne,_,M)),Se&&(Se=this.parseTextData(Se,M,_,!0,Ce,!0,!0)),_=_.substr(0,_.lastIndexOf(".")),Dn.add(this.options.textNodeName,Se),this.addChild(A,Dn,_)}else{if(ne.length>0&&ne.lastIndexOf("/")===ne.length-1){M[M.length-1]==="/"?(M=M.substr(0,M.length-1),_=_.substr(0,_.length-1),ne=M):ne=ne.substr(0,ne.length-1),this.options.transformTagName&&(M=this.options.transformTagName(M));let Se=new k(M);M!==ne&&Ce&&(Se[":@"]=this.buildAttributesMap(ne,_,M)),this.addChild(A,Se,_),_=_.substr(0,_.lastIndexOf("."))}else{let Se=new k(M);this.tagsNodeStack.push(A),M!==ne&&Ce&&(Se[":@"]=this.buildAttributesMap(ne,_,M)),this.addChild(A,Se,_),A=Se}z="",D=ri}}else z+=R[D];return I.child},"parseXml");function U(R,I,A){let z=this.options.updateTag(I.tagname,A,I[":@"]);z===!1||(typeof z=="string"&&(I.tagname=z),R.addChild(I))}s(U,"addChild"),o(U,"addChild");var de=o(function(R){if(this.options.processEntities){for(let I in this.docTypeEntities){let A=this.docTypeEntities[I];R=R.replace(A.regx,A.val)}for(let I in this.lastEntities){let A=this.lastEntities[I];R=R.replace(A.regex,A.val)}if(this.options.htmlEntities)for(let I in this.htmlEntities){let A=this.htmlEntities[I];R=R.replace(A.regex,A.val)}R=R.replace(this.ampEntity.regex,this.ampEntity.val)}return R},"replaceEntitiesValue");function K(R,I,A,z){return R&&(z===void 0&&(z=Object.keys(I.child).length===0),R=this.parseTextData(R,I.tagname,A,!1,I[":@"]?Object.keys(I[":@"]).length!==0:!1,z),R!==void 0&&R!==""&&I.add(this.options.textNodeName,R),R=""),R}s(K,"saveTextToParentTag"),o(K,"saveTextToParentTag");function Y(R,I,A){let z="*."+A;for(let _ in R){let D=R[_];if(z===D||I===D)return!0}return!1}s(Y,"isItStopNode"),o(Y,"isItStopNode");function ve(R,I,A=">"){let z,_="";for(let D=I;D<R.length;D++){let ee=R[D];if(z)ee===z&&(z="");else if(ee==='"'||ee==="'")z=ee;else if(ee===A[0])if(A[1]){if(R[D+1]===A[1])return{data:_,index:D}}else return{data:_,index:D};else ee===" "&&(ee=" ");_+=ee}}s(ve,"tagExpWithClosingIndex"),o(ve,"tagExpWithClosingIndex");function b(R,I,A,z){let _=R.indexOf(I,A);if(_===-1)throw new Error(z);return _+I.length-1}s(b,"findClosingIndex"),o(b,"findClosingIndex");function C(R,I,A,z=">"){let _=ve(R,I+1,z);if(!_)return;let D=_.data,ee=_.index,Z=D.search(/\s/),M=D,ue=!0;Z!==-1&&(M=D.substring(0,Z),D=D.substring(Z+1).trimStart());let ne=M;if(A){let Ce=M.indexOf(":");Ce!==-1&&(M=M.substr(Ce+1),ue=M!==_.data.substr(Ce+1))}return{tagName:M,tagExp:D,closeIndex:ee,attrExpPresent:ue,rawTagName:ne}}s(C,"readTagExp"),o(C,"readTagExp");function B(R,I,A){let z=A,_=1;for(;A<R.length;A++)if(R[A]==="<")if(R[A+1]==="/"){let D=b(R,">",A,`${I} is not closed`);if(R.substring(A+2,D).trim()===I&&(_--,_===0))return{tagContent:R.substring(z,A),i:D};A=D}else if(R[A+1]==="?")A=b(R,"?>",A+1,"StopNode is not closed.");else if(R.substr(A+1,3)==="!--")A=b(R,"-->",A+3,"StopNode is not closed.");else if(R.substr(A+1,2)==="![")A=b(R,"]]>",A,"StopNode is not closed.")-2;else{let D=C(R,A,">");D&&((D&&D.tagName)===I&&D.tagExp[D.tagExp.length-1]!=="/"&&_++,A=D.closeIndex)}}s(B,"readStopNodeData"),o(B,"readStopNodeData");function pe(R,I,A){if(I&&typeof R=="string"){let z=R.trim();return z==="true"?!0:z==="false"?!1:q(R,A)}else return N.isExist(R)?R:""}s(pe,"parseValue"),o(pe,"parseValue"),v.exports=$}}),p=r({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(P){"use strict";function v($,E){return N($,E)}s(v,"prettify"),o(v,"prettify");function N($,E,H){let G,V={};for(let S=0;S<$.length;S++){let T=$[S],U=k(T),de="";if(H===void 0?de=U:de=H+"."+U,U===E.textNodeName)G===void 0?G=T[U]:G+=""+T[U];else{if(U===void 0)continue;if(T[U]){let K=N(T[U],E,de),Y=q(K,E);T[":@"]?j(K,T[":@"],de,E):Object.keys(K).length===1&&K[E.textNodeName]!==void 0&&!E.alwaysCreateTextNode?K=K[E.textNodeName]:Object.keys(K).length===0&&(E.alwaysCreateTextNode?K[E.textNodeName]="":K=""),V[U]!==void 0&&V.hasOwnProperty(U)?(Array.isArray(V[U])||(V[U]=[V[U]]),V[U].push(K)):E.isArray(U,de,Y)?V[U]=[K]:V[U]=K}}}return typeof G=="string"?G.length>0&&(V[E.textNodeName]=G):G!==void 0&&(V[E.textNodeName]=G),V}s(N,"compress"),o(N,"compress");function k($){let E=Object.keys($);for(let H=0;H<E.length;H++){let G=E[H];if(G!==":@")return G}}s(k,"propName"),o(k,"propName");function j($,E,H,G){if(E){let V=Object.keys(E),S=V.length;for(let T=0;T<S;T++){let U=V[T];G.isArray(U,H+"."+U,!0,!0)?$[U]=[E[U]]:$[U]=E[U]}}}s(j,"assignAttributes"),o(j,"assignAttributes");function q($,E){let{textNodeName:H}=E,G=Object.keys($).length;return!!(G===0||G===1&&($[H]||typeof $[H]=="boolean"||$[H]===0))}s(q,"isLeafTag"),o(q,"isLeafTag"),P.prettify=v}}),f=r({"node_modules/fast-xml-parser/src/validator.js"(P){"use strict";var v=a(),N={allowBooleanAttributes:!1,unpairedTags:[]};P.validate=function(b,C){C=Object.assign({},N,C);let B=[],pe=!1,R=!1;b[0]==="\uFEFF"&&(b=b.substr(1));for(let I=0;I<b.length;I++)if(b[I]==="<"&&b[I+1]==="?"){if(I+=2,I=j(b,I),I.err)return I}else if(b[I]==="<"){let A=I;if(I++,b[I]==="!"){I=q(b,I);continue}else{let z=!1;b[I]==="/"&&(z=!0,I++);let _="";for(;I<b.length&&b[I]!==">"&&b[I]!==" "&&b[I]!==" "&&b[I]!==`
|
|
64
|
+
`&&b[I]!=="\r";I++)_+=b[I];if(_=_.trim(),_[_.length-1]==="/"&&(_=_.substring(0,_.length-1),I--),!K(_)){let Z;return _.trim().length===0?Z="Invalid space after '<'.":Z="Tag '"+_+"' is an invalid name.",U("InvalidTag",Z,Y(b,I))}let D=H(b,I);if(D===!1)return U("InvalidAttr","Attributes for '"+_+"' have open quote.",Y(b,I));let ee=D.value;if(I=D.index,ee[ee.length-1]==="/"){let Z=I-ee.length;ee=ee.substring(0,ee.length-1);let M=V(ee,C);if(M===!0)pe=!0;else return U(M.err.code,M.err.msg,Y(b,Z+M.err.line))}else if(z)if(D.tagClosed){if(ee.trim().length>0)return U("InvalidTag","Closing tag '"+_+"' can't have attributes or invalid starting.",Y(b,A));{let Z=B.pop();if(_!==Z.tagName){let M=Y(b,Z.tagStartPos);return U("InvalidTag","Expected closing tag '"+Z.tagName+"' (opened in line "+M.line+", col "+M.col+") instead of closing tag '"+_+"'.",Y(b,A))}B.length==0&&(R=!0)}}else return U("InvalidTag","Closing tag '"+_+"' doesn't have proper closing.",Y(b,I));else{let Z=V(ee,C);if(Z!==!0)return U(Z.err.code,Z.err.msg,Y(b,I-ee.length+Z.err.line));if(R===!0)return U("InvalidXml","Multiple possible root nodes found.",Y(b,I));C.unpairedTags.indexOf(_)!==-1||B.push({tagName:_,tagStartPos:A}),pe=!0}for(I++;I<b.length;I++)if(b[I]==="<")if(b[I+1]==="!"){I++,I=q(b,I);continue}else if(b[I+1]==="?"){if(I=j(b,++I),I.err)return I}else break;else if(b[I]==="&"){let Z=T(b,I);if(Z==-1)return U("InvalidChar","char '&' is not expected.",Y(b,I));I=Z}else if(R===!0&&!k(b[I]))return U("InvalidXml","Extra text at the end",Y(b,I));b[I]==="<"&&I--}}else{if(k(b[I]))continue;return U("InvalidChar","char '"+b[I]+"' is not expected.",Y(b,I))}if(pe){if(B.length==1)return U("InvalidTag","Unclosed tag '"+B[0].tagName+"'.",Y(b,B[0].tagStartPos));if(B.length>0)return U("InvalidXml","Invalid '"+JSON.stringify(B.map(I=>I.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return U("InvalidXml","Start tag expected.",1);return!0};function k(b){return b===" "||b===" "||b===`
|
|
65
|
+
`||b==="\r"}s(k,"isWhiteSpace"),o(k,"isWhiteSpace");function j(b,C){let B=C;for(;C<b.length;C++)if(b[C]=="?"||b[C]==" "){let pe=b.substr(B,C-B);if(C>5&&pe==="xml")return U("InvalidXml","XML declaration allowed only at the start of the document.",Y(b,C));if(b[C]=="?"&&b[C+1]==">"){C++;break}else continue}return C}s(j,"readPI"),o(j,"readPI");function q(b,C){if(b.length>C+5&&b[C+1]==="-"&&b[C+2]==="-"){for(C+=3;C<b.length;C++)if(b[C]==="-"&&b[C+1]==="-"&&b[C+2]===">"){C+=2;break}}else if(b.length>C+8&&b[C+1]==="D"&&b[C+2]==="O"&&b[C+3]==="C"&&b[C+4]==="T"&&b[C+5]==="Y"&&b[C+6]==="P"&&b[C+7]==="E"){let B=1;for(C+=8;C<b.length;C++)if(b[C]==="<")B++;else if(b[C]===">"&&(B--,B===0))break}else if(b.length>C+9&&b[C+1]==="["&&b[C+2]==="C"&&b[C+3]==="D"&&b[C+4]==="A"&&b[C+5]==="T"&&b[C+6]==="A"&&b[C+7]==="["){for(C+=8;C<b.length;C++)if(b[C]==="]"&&b[C+1]==="]"&&b[C+2]===">"){C+=2;break}}return C}s(q,"readCommentAndCDATA"),o(q,"readCommentAndCDATA");var $='"',E="'";function H(b,C){let B="",pe="",R=!1;for(;C<b.length;C++){if(b[C]===$||b[C]===E)pe===""?pe=b[C]:pe!==b[C]||(pe="");else if(b[C]===">"&&pe===""){R=!0;break}B+=b[C]}return pe!==""?!1:{value:B,index:C,tagClosed:R}}s(H,"readAttributeStr"),o(H,"readAttributeStr");var G=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function V(b,C){let B=v.getAllMatches(b,G),pe={};for(let R=0;R<B.length;R++){if(B[R][1].length===0)return U("InvalidAttr","Attribute '"+B[R][2]+"' has no space in starting.",ve(B[R]));if(B[R][3]!==void 0&&B[R][4]===void 0)return U("InvalidAttr","Attribute '"+B[R][2]+"' is without value.",ve(B[R]));if(B[R][3]===void 0&&!C.allowBooleanAttributes)return U("InvalidAttr","boolean attribute '"+B[R][2]+"' is not allowed.",ve(B[R]));let I=B[R][2];if(!de(I))return U("InvalidAttr","Attribute '"+I+"' is an invalid name.",ve(B[R]));if(!pe.hasOwnProperty(I))pe[I]=1;else return U("InvalidAttr","Attribute '"+I+"' is repeated.",ve(B[R]))}return!0}s(V,"validateAttributeString"),o(V,"validateAttributeString");function S(b,C){let B=/\d/;for(b[C]==="x"&&(C++,B=/[\da-fA-F]/);C<b.length;C++){if(b[C]===";")return C;if(!b[C].match(B))break}return-1}s(S,"validateNumberAmpersand"),o(S,"validateNumberAmpersand");function T(b,C){if(C++,b[C]===";")return-1;if(b[C]==="#")return C++,S(b,C);let B=0;for(;C<b.length;C++,B++)if(!(b[C].match(/\w/)&&B<20)){if(b[C]===";")break;return-1}return C}s(T,"validateAmpersand"),o(T,"validateAmpersand");function U(b,C,B){return{err:{code:b,msg:C,line:B.line||B,col:B.col}}}s(U,"getErrorObject"),o(U,"getErrorObject");function de(b){return v.isName(b)}s(de,"validateAttrName"),o(de,"validateAttrName");function K(b){return v.isName(b)}s(K,"validateTagName"),o(K,"validateTagName");function Y(b,C){let B=b.substring(0,C).split(/\r?\n/);return{line:B.length,col:B[B.length-1].length+1}}s(Y,"getLineNumberForPosition"),o(Y,"getLineNumberForPosition");function ve(b){return b.startIndex+b[1].length}s(ve,"getPositionFromMatch"),o(ve,"getPositionFromMatch")}}),y=r({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(P,v){var{buildOptions:N}=i(),k=d(),{prettify:j}=p(),q=f(),$=class{static{s(this,"XMLParser")}static{o(this,"XMLParser")}constructor(E){this.externalEntities={},this.options=N(E)}parse(E,H){if(typeof E!="string")if(E.toString)E=E.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(H){H===!0&&(H={});let S=q.validate(E,H);if(S!==!0)throw Error(`${S.err.msg}:${S.err.line}:${S.err.col}`)}let G=new k(this.options);G.addExternalEntities(this.externalEntities);let V=G.parseXml(E);return this.options.preserveOrder||V===void 0?V:j(V,this.options)}addEntity(E,H){if(H.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(E.indexOf("&")!==-1||E.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");if(H==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[E]=H}};v.exports=$}});let O=y();return new O(n)},"getXmlParser");var Qr=class extends ze{static{s(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),g("policy.outbound.xml-to-json"),W(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=e.parseOnStatusCodes?je(e.parseOnStatusCodes):void 0,this.parser=Ta({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,t,o){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let r;try{let u=await e.text();r=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw o.log.error(c,u),new L(c)}let i=new Headers(e.headers);return i.set("content-type","application/json"),new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:i})}};var Xr=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(e,t){if(this.services.get(e))throw new J(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,t)}getService(e){return this.services.get(e)}};var Yr=class{static{s(this,"BackgroundDispatcher")}#e;constructor(e,t){if(!t||t.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new X(t.name??"",t.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),Rn().waitUntil(this.#e.waitUntilFlushed())}};var va=10,Sa=3e4,ei=class{static{s(this,"BackgroundLoader")}#e=new Map;#t;#n;#o;#r;#i={};constructor(e,t){if(typeof t=="number"){let o=t;this.#n=o*1e3,this.#r=Sa,this.#o=va}else{let o=t;this.#n=o.ttlSeconds*1e3,this.#r=o.loaderTimeoutSeconds?o.loaderTimeoutSeconds*1e3:Sa,this.#o=va}this.#t=e}#s(e){return e.expiry<=new Date}#a(e){let t=this.#i[e];return!(t===void 0||t===0)}#u(e){let t=this.#e.get(e);if(t&&!this.#s(t))return t.data}async get(e){let t=this.#u(e);if(t)return this.#l(e),t;if(this.#a(e))try{await Zl(()=>this.#u(e)!==void 0||!this.#a,this.#r+this.#o+1,this.#o);let o=this.#u(e);if(o)return o}catch{}return this.#c(e)}#l(e){if(!this.#a(e)){let t=this.#c(e);Rn().waitUntil(t)}}async#c(e){try{this.#i[e]===void 0&&(this.#i[e]=0),this.#i[e]++;let t=await Promise.race([this.#t(e),scheduler.wait(this.#r)]);if(t===void 0)throw new Error(`BackgroundLoader: Loader timed out after ${this.#r} ms.`);return this.#e.set(e,{data:t,expiry:new Date(Date.now()+this.#n)}),t}finally{this.#i[e]--}}};async function Zl(n,e,t){let o=Date.now();for(;!n();){let r=Date.now()-o;if(r>e)throw new Error(`BackgroundLoader: Timeout waiting for an on-going loader after ${r} ms.`);await scheduler.wait(t)}}s(Zl,"waitUntilTrue");var ti=["sha-1","sha-256","sha-384","sha-512"],_n=class{static{s(this,"BaseCryptoBeta")}};var ni=class extends _n{static{s(this,"WorkerCryptoBeta")}async digest(e,t){if(!ti.includes(e.toLowerCase()))throw new L(`Algorithm ${e} is not supported. Try using ${ti.join(", ")}`);let o=new TextEncoder().encode(t),r=await crypto.subtle.digest(e,o);return Array.from(new Uint8Array(r)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var Nn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var oi=class extends Nn{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let t=h.instance.runtime.ZUPLO_KV;if(!t)throw new si("The Key Value Store feature is not enabled for this project.");this.#e=t,g("platform.kv-store")}put(e,t,o){if(typeof e!="string")throw new m("value must be of type string");return this.#e.put(e,t,o?{expirationTtl:o.expirationSecondsTtl}:void 0)}get(e,t){return this.#e.get(e,{type:"text",cacheTtl:t?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};export{tr as AWSLoggingPlugin,pc as AmberfloMeteringInboundPolicy,Rr as AmberfloMeteringPolicy,fc as ApiAuthKeyInboundPolicy,Pr as ApiKeyInboundPolicy,dr as AuditLogDataStaxProvider,pr as AuditLogPlugin,Rc as Auth0JwtInboundPolicy,Lu as AwsLambdaHandlerExtensions,Tr as AxiomaticsAuthZInboundPolicy,Yr as BackgroundDispatcher,ei as BackgroundLoader,Pc as BasicAuthInboundPolicy,pa as BasicRateLimitInboundPolicy,X as BatchDispatch,Cr as BrownoutInboundPolicy,Lc as CachingInboundPolicy,_c as ChangeMethodInboundPolicy,qc as ClearHeadersInboundPolicy,Hc as ClearHeadersOutboundPolicy,Uc as ClerkJwtInboundPolicy,Zc as CognitoJwtInboundPolicy,Mr as ComplexRateLimitInboundPolicy,Vc as CompositeInboundPolicy,m as ConfigurationError,so as ContentTypes,se as ContextData,ni as CryptoBeta,Wc as CurityPhantomTokenInboundPolicy,_o as DataDogLoggingPlugin,rr as DataDogMetricsPlugin,Go as DynaTraceLoggingPlugin,ur as DynatraceMetricsPlugin,Jc as FirebaseJwtInboundPolicy,Qc as FormDataToJsonInboundPolicy,Xc as GeoFilterInboundPolicy,Co as GoogleCloudLoggingPlugin,Ho as Handler,x as HttpProblems,nn as HttpStatusCode,ae as InboundPolicy,Yc as JWTScopeValidationInboundPolicy,oi as KeyValueStore,Wo as LokiLoggingPlugin,jt as LookupResult,oe as MemoryZoneReadThroughCache,el as MockApiInboundPolicy,al as MoesifInboundPolicy,Zr as MonetizationInboundPolicy,Fr as OktaFGAAuthZInboundPolicy,cl as OktaJwtInboundPolicy,$r as OpenFGAAuthZInboundPolicy,we as OpenIdJwtInboundPolicy,ze as OutboundPolicy,et as ProblemResponseFormatter,dl as PropelAuthJwtInboundPolicy,Nr as QuotaInboundPolicy,pa as RateLimitInboundPolicy,fl as ReadmeMetricsInboundPolicy,hl as RemoveHeadersInboundPolicy,yl as RemoveHeadersOutboundPolicy,bl as RemoveQueryParamsInboundPolicy,wl as ReplaceStringOutboundPolicy,Rl as RequestSizeLimitInboundPolicy,Ra as RequestValidationInboundPolicy,Il as RequireOriginInboundPolicy,Lt as ResponseSendingEvent,_t as ResponseSentEvent,zt as Router,L as RuntimeError,Qt as SYSTEM_LOGGER,Pl as SchemaBasedRequestValidation,Le as SemanticAttributes,Xr as ServiceProviderImpl,El as SetBodyInboundPolicy,xl as SetHeadersInboundPolicy,Tl as SetHeadersOutboundPolicy,vl as SetQueryParamsInboundPolicy,Sl as SetStatusOutboundPolicy,Ol as SleepInboundPolicy,qs as StripeMonetizationPlugin,Gt as StripeWebhookVerificationInboundPolicy,Qo as SumoLogicLoggingPlugin,Al as SupabaseJwtInboundPolicy,Ue as SystemRouteName,Ot as TelemetryPlugin,kl as UpstreamAzureAdServiceAuthInboundPolicy,_l as UpstreamFirebaseAdminAuthInboundPolicy,Ml as UpstreamFirebaseUserAuthInboundPolicy,Wr as UpstreamGcpFederatedAuthInboundPolicy,ql as UpstreamGcpJwtInboundPolicy,Hl as UpstreamGcpServiceAuthInboundPolicy,Yo as VMWareLogInsightLoggingPlugin,Ul as ValidateJsonSchemaInbound,Qr as XmlToJsonOutboundPolicy,vt as ZoneCache,te as ZuploRequest,Kt as ZuploServices,_u as awsLambdaHandler,Re as environment,qn as getIdForParameterSchema,Oa as getIdForRefSchema,Hn as getIdForRequestBodySchema,Ca as getRawOperationDataIdentifierName,uo as httpStatuses,Fu as openApiSpecHandler,ju as redirectHandler,Aa as sanitizedIdentifierName,ao as serialize,rl as setMoesifContext,g as trackFeature,Bu as urlForwardHandler,Vu as urlRewriteHandler,Wu as webSocketHandler,Ku as webSocketPipelineHandler};
|
|
65
66
|
/*! For license information please see index.js.LEGAL.txt */
|