@zuplo/runtime 5.2181.0 → 5.2183.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 -19
- package/out/cjs/internal/index.js +1 -1
- package/out/cjs/policies/axiomatics-authz-inbound/exports.js +2 -2
- package/out/esm/{chunk-HPMPWPKQ.js → chunk-4NFZOV2A.js} +2 -2
- package/out/esm/{chunk-QSL25HFO.js → chunk-CRZT3N5H.js} +2 -2
- package/out/esm/{chunk-CI735RIK.js → chunk-M2WV76HS.js} +2 -2
- package/out/esm/index.js +15 -15
- package/out/esm/internal/index.js +1 -1
- package/out/esm/policies/axiomatics-authz-inbound/exports.js +1 -1
- package/out/types/index.d.ts +109 -6
- package/package.json +1 -1
- /package/out/esm/{chunk-HPMPWPKQ.js.LEGAL.txt → chunk-4NFZOV2A.js.LEGAL.txt} +0 -0
- /package/out/esm/{chunk-QSL25HFO.js.LEGAL.txt → chunk-CRZT3N5H.js.LEGAL.txt} +0 -0
- /package/out/esm/{chunk-CI735RIK.js.LEGAL.txt → chunk-M2WV76HS.js.LEGAL.txt} +0 -0
package/out/cjs/index.js
CHANGED
|
@@ -22,17 +22,17 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
"use strict";var
|
|
26
|
-
`).map(u=>u.trim()).join(" ");case"%O":return n(t[r++]);case"%j":try{return JSON.stringify(t[r++])}catch{return"[Circular]"}default:return a}});for(let a of t.splice(r))a===null||!(typeof a=="object"&&a!==null)?s+=" "+a:s+=" "+n(a);return s}i(
|
|
25
|
+
"use strict";var cc=Object.create;var Ht=Object.defineProperty;var lc=Object.getOwnPropertyDescriptor;var dc=Object.getOwnPropertyNames;var pc=Object.getPrototypeOf,mc=Object.prototype.hasOwnProperty;var i=(n,e)=>Ht(n,"name",{value:e,configurable:!0});var Zt=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),gc=(n,e)=>{for(var t in e)Ht(n,t,{get:e[t],enumerable:!0})},Ci=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of dc(e))!mc.call(n,o)&&o!==t&&Ht(n,o,{get:()=>e[o],enumerable:!(r=lc(e,o))||r.enumerable});return n};var Be=(n,e,t)=>(t=n!=null?cc(pc(n)):{},Ci(e||!n||!n.__esModule?Ht(t,"default",{value:n,enumerable:!0}):t,n)),fc=n=>Ci(Ht({},"__esModule",{value:!0}),n);var Hi=Zt(v=>{"use strict";Object.defineProperty(v,"__esModule",{value:!0});v.generateColor=v.colorFunctions=v.stripColor=v.bgRgb24=v.rgb24=v.bgRgb8=v.rgb8=v.bgBrightWhite=v.bgBrightCyan=v.bgBrightMagenta=v.bgBrightBlue=v.bgBrightYellow=v.bgBrightGreen=v.bgBrightRed=v.bgBrightBlack=v.bgWhite=v.bgCyan=v.bgMagenta=v.bgBlue=v.bgYellow=v.bgGreen=v.bgRed=v.bgBlack=v.brightWhite=v.brightCyan=v.brightMagenta=v.brightBlue=v.brightYellow=v.brightGreen=v.brightRed=v.brightBlack=v.gray=v.white=v.cyan=v.magenta=v.blue=v.yellow=v.green=v.red=v.black=v.strikethrough=v.hidden=v.inverse=v.underline=v.italic=v.dim=v.bold=v.reset=v.getColorEnabled=v.setColorEnabled=void 0;var Ai=!0,Lr=!Ai;function hc(n){Ai||(Lr=n)}i(hc,"setColorEnabled");v.setColorEnabled=hc;function yc(){return Lr}i(yc,"getColorEnabled");v.getColorEnabled=yc;function J(n,e){return{open:`\x1B[${n.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}i(J,"code");function K(n,e){return Lr?`${e.open}${n.replace(e.regexp,e.open)}${e.close}`:n}i(K,"run");function bc(n){return K(n,J([0],0))}i(bc,"reset");v.reset=bc;function wc(n){return K(n,J([1],22))}i(wc,"bold");v.bold=wc;function Rc(n){return K(n,J([2],22))}i(Rc,"dim");v.dim=Rc;function Pc(n){return K(n,J([3],23))}i(Pc,"italic");v.italic=Pc;function Ec(n){return K(n,J([4],24))}i(Ec,"underline");v.underline=Ec;function Ic(n){return K(n,J([7],27))}i(Ic,"inverse");v.inverse=Ic;function xc(n){return K(n,J([8],28))}i(xc,"hidden");v.hidden=xc;function Tc(n){return K(n,J([9],29))}i(Tc,"strikethrough");v.strikethrough=Tc;function vc(n){return K(n,J([30],39))}i(vc,"black");v.black=vc;function _i(n){return K(n,J([31],39))}i(_i,"red");v.red=_i;function Li(n){return K(n,J([32],39))}i(Li,"green");v.green=Li;function ki(n){return K(n,J([33],39))}i(ki,"yellow");v.yellow=ki;function Ni(n){return K(n,J([34],39))}i(Ni,"blue");v.blue=Ni;function Mi(n){return K(n,J([35],39))}i(Mi,"magenta");v.magenta=Mi;function Di(n){return K(n,J([36],39))}i(Di,"cyan");v.cyan=Di;function Sc(n){return K(n,J([37],39))}i(Sc,"white");v.white=Sc;function Oc(n){return Ui(n)}i(Oc,"gray");v.gray=Oc;function Ui(n){return K(n,J([90],39))}i(Ui,"brightBlack");v.brightBlack=Ui;function Cc(n){return K(n,J([91],39))}i(Cc,"brightRed");v.brightRed=Cc;function Ac(n){return K(n,J([92],39))}i(Ac,"brightGreen");v.brightGreen=Ac;function _c(n){return K(n,J([93],39))}i(_c,"brightYellow");v.brightYellow=_c;function Lc(n){return K(n,J([94],39))}i(Lc,"brightBlue");v.brightBlue=Lc;function kc(n){return K(n,J([95],39))}i(kc,"brightMagenta");v.brightMagenta=kc;function Nc(n){return K(n,J([96],39))}i(Nc,"brightCyan");v.brightCyan=Nc;function Mc(n){return K(n,J([97],39))}i(Mc,"brightWhite");v.brightWhite=Mc;function Dc(n){return K(n,J([40],49))}i(Dc,"bgBlack");v.bgBlack=Dc;function Uc(n){return K(n,J([41],49))}i(Uc,"bgRed");v.bgRed=Uc;function Hc(n){return K(n,J([42],49))}i(Hc,"bgGreen");v.bgGreen=Hc;function Zc(n){return K(n,J([43],49))}i(Zc,"bgYellow");v.bgYellow=Zc;function qc(n){return K(n,J([44],49))}i(qc,"bgBlue");v.bgBlue=qc;function Fc(n){return K(n,J([45],49))}i(Fc,"bgMagenta");v.bgMagenta=Fc;function $c(n){return K(n,J([46],49))}i($c,"bgCyan");v.bgCyan=$c;function jc(n){return K(n,J([47],49))}i(jc,"bgWhite");v.bgWhite=jc;function Bc(n){return K(n,J([100],49))}i(Bc,"bgBrightBlack");v.bgBrightBlack=Bc;function zc(n){return K(n,J([101],49))}i(zc,"bgBrightRed");v.bgBrightRed=zc;function Vc(n){return K(n,J([102],49))}i(Vc,"bgBrightGreen");v.bgBrightGreen=Vc;function Gc(n){return K(n,J([103],49))}i(Gc,"bgBrightYellow");v.bgBrightYellow=Gc;function Wc(n){return K(n,J([104],49))}i(Wc,"bgBrightBlue");v.bgBrightBlue=Wc;function Jc(n){return K(n,J([105],49))}i(Jc,"bgBrightMagenta");v.bgBrightMagenta=Jc;function Kc(n){return K(n,J([106],49))}i(Kc,"bgBrightCyan");v.bgBrightCyan=Kc;function Yc(n){return K(n,J([107],49))}i(Yc,"bgBrightWhite");v.bgBrightWhite=Yc;function ze(n,e=255,t=0){return Math.trunc(Math.max(Math.min(n,e),t))}i(ze,"clampAndTruncate");function Xc(n,e){return K(n,J([38,5,ze(e)],39))}i(Xc,"rgb8");v.rgb8=Xc;function Qc(n,e){return K(n,J([48,5,ze(e)],49))}i(Qc,"bgRgb8");v.bgRgb8=Qc;function el(n,e){return typeof e=="number"?K(n,J([38,2,e>>16&255,e>>8&255,e&255],39)):K(n,J([38,2,ze(e.r),ze(e.g),ze(e.b)],39))}i(el,"rgb24");v.rgb24=el;function tl(n,e){return typeof e=="number"?K(n,J([48,2,e>>16&255,e>>8&255,e&255],49)):K(n,J([48,2,ze(e.r),ze(e.g),ze(e.b)],49))}i(tl,"bgRgb24");v.bgRgb24=tl;var nl=new RegExp(["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|"),"g");function rl(n){return n.replace(nl,"")}i(rl,"stripColor");v.stripColor=rl;v.colorFunctions=[_i,Li,ki,Ni,Mi,Di];function ol(n){let e=0,t=n.length,r=0;if(t>0)for(;r<t;)e=(e<<5)-e+n.charCodeAt(r++)|0;return e}i(ol,"hashCode");function il(n){let e=Math.abs(ol(n));return v.colorFunctions[e%v.colorFunctions.length]}i(il,"generateColor");v.generateColor=il});var Zi=Zt(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.format=void 0;function sl(n,e,...t){let r=0,o=t.length,s=String(e).replace(/%[sdjoO%]/g,a=>{if(a==="%%")return"%";if(r>=o)return a;switch(a){case"%s":return String(t[r++]);case"%d":return Number(t[r++]).toString();case"%o":return n(t[r++]).split(`
|
|
26
|
+
`).map(u=>u.trim()).join(" ");case"%O":return n(t[r++]);case"%j":try{return JSON.stringify(t[r++])}catch{return"[Circular]"}default:return a}});for(let a of t.splice(r))a===null||!(typeof a=="object"&&a!==null)?s+=" "+a:s+=" "+n(a);return s}i(sl,"format");on.format=sl});var zi=Zt(an=>{"use strict";Object.defineProperty(an,"__esModule",{value:!0});an.inspect=void 0;function tt(n,e,t,r){let o={seen:[],stylize:al,showHidden:e??!1,depth:t??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=cl),sn(o,n,o.depth)}i(tt,"inspect");an.inspect=tt;tt.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};tt.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function al(n,e){return n}i(al,"stylizeNoColor");function ul(n){return typeof n=="boolean"}i(ul,"isBoolean");function Fi(n){return n===void 0}i(Fi,"isUndefined");function cl(n,e){let t=tt.styles[e];return t?"\x1B["+tt.colors[t][0]+"m"+n+"\x1B["+tt.colors[t][1]+"m":n}i(cl,"stylizeWithColor");function kr(n){return typeof n=="function"}i(kr,"isFunction");function $i(n){return typeof n=="string"}i($i,"isString");function ll(n){return typeof n=="number"}i(ll,"isNumber");function ji(n){return n===null}i(ji,"isNull");function Bi(n,e){return Object.prototype.hasOwnProperty.call(n,e)}i(Bi,"hasOwn");function Nr(n){return Hr(n)&&Zr(n)==="[object RegExp]"}i(Nr,"isRegExp");function Hr(n){return typeof n=="object"&&n!==null}i(Hr,"isObject");function Mr(n){return Hr(n)&&(Zr(n)==="[object Error]"||n instanceof Error)}i(Mr,"isError");function qi(n){return Hr(n)&&Zr(n)==="[object Date]"}i(qi,"isDate");function Zr(n){return Object.prototype.toString.call(n)}i(Zr,"objectToString");function dl(n){let e={};return n.forEach(function(t,r){e[t]=!0}),e}i(dl,"arrayToHash");function pl(n,e,t,r,o){let s=[];for(let a=0,u=e.length;a<u;++a)Bi(e,String(a))?s.push(Ur(n,e,t,r,String(a),!0)):s.push("");return o.forEach(function(a){a.match(/^\d+$/)||s.push(Ur(n,e,t,r,a,!0))}),s}i(pl,"formatArray");function Dr(n){return"["+Error.prototype.toString.call(n)+"]"}i(Dr,"formatError");function sn(n,e,t){if(n.customInspect&&e&&kr(e.inspect)&&e.inspect!==tt&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(t,n);return $i(d)||(d=sn(n,d,t)),d}let r=ml(n,e);if(r)return r;let o=Object.keys(e),s=dl(o);try{n.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(Mr(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return Dr(e);if(o.length===0){if(kr(e)){let d=e.name?": "+e.name:"";return n.stylize("[Function"+d+"]","special")}if(Nr(e))return n.stylize(RegExp.prototype.toString.call(e),"regexp");if(qi(e))return n.stylize(Date.prototype.toString.call(e),"date");if(Mr(e))return Dr(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),kr(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),Nr(e)&&(a=" "+RegExp.prototype.toString.call(e)),qi(e)&&(a=" "+Date.prototype.toUTCString.call(e)),Mr(e)&&(a=" "+Dr(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(t<0)return Nr(e)?n.stylize(RegExp.prototype.toString.call(e),"regexp"):n.stylize("[Object]","special");n.seen.push(e);let l;return u?l=pl(n,e,t,s,o):l=o.map(function(d){return Ur(n,e,t,s,d,u)}),n.seen.pop(),gl(l,a,c)}i(sn,"formatValue");function Ur(n,e,t,r,o,s){let a,u,c;c={value:void 0};try{c.value=e[o]}catch{}try{Object.getOwnPropertyDescriptor&&(c=Object.getOwnPropertyDescriptor(e,o)||c)}catch{}if(c.get?c.set?u=n.stylize("[Getter/Setter]","special"):u=n.stylize("[Getter]","special"):c.set&&(u=n.stylize("[Setter]","special")),Bi(r,o)||(a="["+o+"]"),u||(n.seen.indexOf(c.value)<0?(ji(t)?u=sn(n,c.value,null):u=sn(n,c.value,t-1),u.indexOf(`
|
|
27
27
|
`)>-1&&(s?u=u.split(`
|
|
28
28
|
`).map(function(l){return" "+l}).join(`
|
|
29
29
|
`).substr(2):u=`
|
|
30
30
|
`+u.split(`
|
|
31
31
|
`).map(function(l){return" "+l}).join(`
|
|
32
|
-
`))):u=n.stylize("[Circular]","special"))
|
|
32
|
+
`))):u=n.stylize("[Circular]","special")),Fi(a)){if(s&&o.match(/^\d+$/))return u;a=JSON.stringify(""+o),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=n.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=n.stylize(a,"string"))}return a+": "+u}i(Ur,"formatProperty");function ml(n,e){if(Fi(e))return n.stylize("undefined","undefined");if($i(e)){let t="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return n.stylize(t,"string")}if(ll(e))return n.stylize(""+e,"number");if(ul(e))return n.stylize(""+e,"boolean");if(ji(e))return n.stylize("null","null")}i(ml,"formatPrimitive");function gl(n,e,t){let r=0;return n.reduce(function(s,a){return r++,a.indexOf(`
|
|
33
33
|
`)>=0&&r++,s+a.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?t[0]+(e===""?"":e+`
|
|
34
34
|
`)+" "+n.join(`,
|
|
35
|
-
`)+" "+t[1]:t[0]+e+" "+n.join(", ")+" "+t[1]}i(pl,"reduceToSingleString")});var Gi=Dt(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.format=void 0;var ml=qi(),gl=Vi(),fl=i((n,...e)=>(0,ml.format)(gl.inspect,n,e),"format");on.format=fl});var ze=Dt(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.debug=Be.withoutEnv=Be.Debugger=void 0;var hl=Zi(),yl=Gi(),sn=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=(0,hl.generateColor)(t),this.last=0,this.enabled=e.enabled.some(r=>r.test(t))}log(...e){if(!this.enabled)return;let t,r=e[0];typeof r=="function"?t=r():t=String(r);let o=Date.now()-(this.last||Date.now());t=(0,yl.format)(t,...e);let s=`${this.color(this.ns)} ${t} ${this.color(`+${o}ms`)}`;console.log(s),this.last=Date.now()}};Be.Debugger=sn;var an=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function Wi(n){return!n||n.length===0?[]:(n=n.replace(/\s/g,"").replace(/\*/g,".+"),n.split(",").map(e=>new RegExp(`^${e}$`)))}i(Wi,"extract");var Ut;function bl(n){n||(n=[]),typeof n=="string"&&(n=Wi(n)),Ut=new an(n)}i(bl,"withoutEnv");Be.withoutEnv=bl;function wl(n){let e=globalThis.DEBUG;Ut||(Ut=new an(Wi(e)));let t=new sn(Ut,n);return Ut.debuggers.set(n,t),Object.assign(t.log.bind(t),{self:t})}i(wl,"debug");Be.debug=wl});var Sp={};pc(Sp,{AWSLoggingPlugin:()=>Gn,AmberfloMeteringInboundPolicy:()=>Za,AmberfloMeteringPolicy:()=>er,ApiAuthKeyInboundPolicy:()=>$a,ApiKeyInboundPolicy:()=>nr,AuditLogDataStaxProvider:()=>Kn,AuditLogPlugin:()=>Yn,Auth0JwtInboundPolicy:()=>za,AwsLambdaHandlerExtensions:()=>wa,AxiomaticsAuthZInboundPolicy:()=>ir,BackgroundDispatcher:()=>vr,BackgroundLoader:()=>Sr,BasicAuthInboundPolicy:()=>Va,BasicRateLimitInboundPolicy:()=>wi,BatchDispatch:()=>X,BrownoutInboundPolicy:()=>ur,CachingInboundPolicy:()=>Wa,ChangeMethodInboundPolicy:()=>Ja,ClearHeadersInboundPolicy:()=>Ka,ClearHeadersOutboundPolicy:()=>Ya,ClerkJwtInboundPolicy:()=>Xa,CognitoJwtInboundPolicy:()=>Qa,CompositeInboundPolicy:()=>eu,ConfigurationError:()=>m,ContentTypes:()=>fn,ContextData:()=>Ce,CryptoBeta:()=>Cr,CurityPhantomTokenInboundPolicy:()=>tu,DataDogLoggingPlugin:()=>Ln,DataDogMetricsPlugin:()=>Wn,DynaTraceLoggingPlugin:()=>jn,DynatraceMetricsPlugin:()=>Jn,FirebaseJwtInboundPolicy:()=>nu,FormDataToJsonInboundPolicy:()=>ru,GeoFilterInboundPolicy:()=>ou,GoogleCloudLoggingPlugin:()=>Cn,Handler:()=>Fn,HttpProblems:()=>T,HttpStatusCode:()=>$t,InboundPolicy:()=>we,JWTScopeValidationInboundPolicy:()=>iu,KeyValueStore:()=>_r,LokiLoggingPlugin:()=>Bn,LookupResult:()=>Pt,MemoryZoneReadThroughCache:()=>de,MockApiInboundPolicy:()=>au,MoesifInboundPolicy:()=>mu,MonetizationInboundPolicy:()=>lr,OktaJwtInboundPolicy:()=>bu,OpenIdJwtInboundPolicy:()=>fe,OutboundPolicy:()=>Fe,ProblemResponseFormatter:()=>Ge,PropelAuthJwtInboundPolicy:()=>Ru,RateLimitInboundPolicy:()=>wi,ReadmeMetricsInboundPolicy:()=>Ou,RemoveHeadersInboundPolicy:()=>Cu,RemoveHeadersOutboundPolicy:()=>Au,RemoveQueryParamsInboundPolicy:()=>_u,ReplaceStringOutboundPolicy:()=>Lu,RequestSizeLimitInboundPolicy:()=>Nu,RequestValidationInboundPolicy:()=>Ei,RequireOriginInboundPolicy:()=>$u,ResponseSendingEvent:()=>ft,ResponseSentEvent:()=>ht,Router:()=>Et,RuntimeError:()=>L,SYSTEM_LOGGER:()=>Zt,SchemaBasedRequestValidation:()=>Fu,SemanticAttributes:()=>_e,ServiceProviderImpl:()=>Tr,SetBodyInboundPolicy:()=>ju,SetHeadersInboundPolicy:()=>Bu,SetHeadersOutboundPolicy:()=>zu,SetQueryParamsInboundPolicy:()=>Vu,SetStatusOutboundPolicy:()=>Gu,SleepInboundPolicy:()=>Wu,StripeMonetizationPlugin:()=>ai,StripeWebhookVerificationInboundPolicy:()=>vt,SumoLogicLoggingPlugin:()=>zn,SupabaseJwtInboundPolicy:()=>Ju,SystemRouteName:()=>Me,TelemetryPlugin:()=>mt,UpstreamAzureAdServiceAuthInboundPolicy:()=>Ku,UpstreamFirebaseAdminAuthInboundPolicy:()=>Xu,UpstreamFirebaseUserAuthInboundPolicy:()=>Qu,UpstreamGcpJwtInboundPolicy:()=>ec,UpstreamGcpServiceAuthInboundPolicy:()=>nc,VMWareLogInsightLoggingPlugin:()=>Vn,ValidateJsonSchemaInbound:()=>rc,XmlToJsonOutboundPolicy:()=>xr,ZoneCache:()=>pt,ZuploRequest:()=>re,awsLambdaHandler:()=>Ra,environment:()=>Re,getIdForParameterSchema:()=>Er,getIdForRefSchema:()=>Du,getIdForRequestBodySchema:()=>Ir,getRawOperationDataIdentifierName:()=>Mu,httpStatuses:()=>bn,openApiSpecHandler:()=>Pa,redirectHandler:()=>Ea,sanitizedIdentifierName:()=>Qe,serialize:()=>hn,setMoesifContext:()=>pu,trackFeature:()=>f,urlForwardHandler:()=>Ia,urlRewriteHandler:()=>xa,webSocketHandler:()=>Ta,webSocketPipelineHandler:()=>Oa});module.exports=mc(Sp);var Xi=et(ze());var Q=class extends Error{static{i(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},L=class extends Error{static{i(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},m=class extends L{static{i(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}},un=class extends L{static{i(this,"FeatureNotEnabledError")}constructor(e,t){super(e,t),this.name="FeatureNotEnabledError"}};var $r="2024-03-14",Ji=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0}});function Ki(){return new g({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),IS_PRODUCTION:!1,BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:$r,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,COMPATIBILITY_FLAGS:Ji[$r]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}i(Ki,"getMockEnvironment");var g=class n{static{i(this,"Environment")}config;static#e;static#t=!1;static initialize(e){this.#e||(this.#e=new n(e),this.#t=!0)}static get instance(){return this.#t||(console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=Ki()),this.#e}constructor({build:e,runtime:t}){let r;try{if(t.__ZUPLO_CONFIG){let o=atob(t.__ZUPLO_CONFIG);r=JSON.parse(o)}}catch{console.warn("Failed to parse runtime configuration")}this.config=r??{},this.build=e,this.runtime=t,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.ENVIRONMENT_TYPE?this.build.ENVIRONMENT_TYPE==="LOCAL_DEVELOPMENT":!1}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var nt=(0,Xi.debug)("zuplo:runtime:external-service");function Rl(){let n,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=g.instance.runtime;if(e&&e!=="undefined")try{let t=atob(e);n=JSON.parse(t)}catch{}return n}i(Rl,"getServiceAuth");async function Qi(n,e){let t=Rl();if(t)if(nt(`Using external service auth. ClientId: ${t.clientId})`),typeof n=="string"){let r=new URL(n),o=r.hostname,s=e??{},a=new Headers(s.headers||{});a.set("CF-Access-Client-Id",t.clientId),a.set("CF-Access-Client-Secret",t.clientSecret),s.headers=a;let u;if(t.customServiceMapping&&t.customServiceMapping[o])u=`https://${t.customServiceMapping[o]}`;else if(g.instance.useLegacyServiceRouting)u=`https://${o}.zuptunnel.com`;else{nt("Using sha256 service routing");let d=g.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await Pl(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw nt("Cannot use sha256 service routing, missing build variables"),new L("Failed to generate fully qualified tunnel url.")}let c=new URL(`${u}${r.pathname}${r.search}`);nt(`Calling external service: ${c.toString()}`);let l=await F.fetch(c.toString(),s);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:t.clientId,tunnelHost:u}),new L("Could not connect to secure tunnel.");return l}else throw nt("Cannot call external service with Request object"),new L("Currently, we only support fetch(<some_string>, ...).");else throw nt("There is no external service auth configured for this zup."),new L("There are no external services configured for this zup.")}i(Qi,"externalServiceHandler");async function Pl(n,e,t,r){let o=n.toLowerCase(),s=e.toLowerCase(),a=t.toLowerCase(),u=El(r);nt(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await Yi(`${s}-${o}`),l=await Yi(`${s}-${a}-${u}`);return`${c}.${l}`}i(Pl,"hashServiceName");async function Yi(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("").slice(0,-1)}i(Yi,"hashSegment");function El(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(El,"sanitizeEnvironmentType");var ts=new Map;ts.set("service:",Qi);var es=globalThis.fetch;function jr(n,e){let t=Il(e);if(typeof n=="string"){let r=new URL(n),o=ts.get(r.protocol);return o?o(n,t):es(n,t)}else return es(n,t)}i(jr,"internalFetch");globalThis.fetch=jr;var Il=i(n=>{if(!n||n instanceof Request)return n;let e=n;if(!e.zuplo)return n;let t=n;return t.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete n.zuplo,n},"transformInit");var xl={fetch:jr},F=xl;Function.prototype.toString=function(){return"[native code]"};var cn=globalThis,ns=cn.caches;if(ns){let n=ns.open;cn.caches.open=function(e){let t=g.instance.deploymentName??g.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete cn.caches.default,Object.freeze(cn.caches)}var rs=new Map,Br=class{static{i(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(),s={created:o,lastUsed:o,expiresAt:o+r*1e3,data:t};this.#r.push(e),this.#n.set(e,s)}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)})}},dt=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=rs.get(e);r||(r=new Br(t),rs.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 zr="__zuplo-expiry-header",pt=class{static{i(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 s=o.headers.get(zr);if(!s){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(s);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(zr,`${Date.now()+r*1e3}`);let s=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(t),{headers:o});await s.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(zr,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),s=new Response("",{headers:t});await r.put(o,s)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var de=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new dt(r),this.#n=new pt(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},s=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(s)}};var os="zuplo-request-id",rt="zp-rid",Vr="zp-body-removed",ot="cf-ray",is="x-real-ip",Gr="cf-ipcity",Wr="cf-ipcontinent",Jr="cf-ipcountry",Kr="cf-iplongitude",Yr="cf-iplatitude",ss="cf-region",as="cf-region-code",us="cf-metro-code",cs="cf-postal-code",ls="cf-timezone",ds="zp-ipcity",ps="zp-ipcontinent",ms="zp-ipcountry",gs="zp-iplongitude",fs="zp-iplatitude",hs="true-client-ip",Xr="zp-asn",Qr="zp-asorg",eo="zp-colo",to="zp-postalcode",no="zp-metrocode",ro="zp-region",oo="zp-regioncode",io="zp-timezone",ys=[Gr,Wr,Jr,Kr,Yr,Xr,Qr,eo,to,no,ro,oo,io],bs=["zp-","cf-"],ws=[rt,ot,Vr];var Ht="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49",ln="zuplo_dynamic_meters_0c8cdc26-2514-4756-8adb-474a6e103d91",Zt="system-logger";var oa=require("@opentelemetry/api"),ia=et(ze());var yn=require("@opentelemetry/api");var We=require("@opentelemetry/api");var Rs=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function Ps(n){Rs=n}i(Ps,"setTelemetryInitFunction");var Es=i(n=>Rs(n),"proxyHandler");var Ve=class{static{i(this,"RuntimePlugin")}},Ze=class extends Ve{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},dn=class extends Ze{static{i(this,"MeteringPlugin")}},mt=class extends Ve{static{i(this,"TelemetryPlugin")}};var pn=new Set,Is=new Set;function f(n){Is.has(n)||(Is.add(n),pn.add(n))}i(f,"trackFeature");function xs(){let n=[...pn];return pn.clear(),n}i(xs,"getUnsentFeatures");function Ts(n){for(let e of n)pn.add(e)}i(Ts,"restoreFeatures");var qt=class n{static{i(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&&(f("runtime.problem-response-formatter"),n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(s){throw new L("Error in custom 'problemResponseFormat'",{cause:s})}})}},Ge=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,r){return await qt.problemResponseFormat(e,t,r)}};function mn(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&mn(t)}return Object.freeze(n)}i(mn,"deepFreeze");var re=class n extends Request{static{i(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 mn(this.#e)}get params(){return mn(this.#t)}user};var Ft={},qe=[],so=[],ao=[],uo=[];var gn={addPlugin(n){qe.push(n)},addRequestHook(n){so.push(n)},addResponseSendingHook(n){ao.push(n)},addResponseSendingFinalHook(n){uo.push(n)}},Ss=i(async(n,e)=>{if(so.length===0)return n;let t=We.trace.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let s of so){let a=await t.startActiveSpan(s.name,async u=>{let c=await s(o,e);if(c instanceof re||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:We.SpanStatusCode.ERROR}),l}});if(a instanceof re)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),Os=i(async(n,e,t)=>{if(ao.length===0)return n;let r=We.trace.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let s=n;for(let a of ao)await r.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)s=c,u.end();else{let l=new m(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof s}.`);throw u.recordException(l),u.setStatus({code:We.SpanStatusCode.ERROR}),u.end(),l}});return s}finally{o.end()}})},"invokeOnResponseSendingExtensions"),Cs=i(async(n,e,t)=>{if(uo.length===0)return;let r=We.trace.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let s of uo)await r.startActiveSpan(s.name,async a=>{try{await s(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:We.SpanStatusCode.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),vs=!1;async function As(n){if(!vs){n&&(f("runtime.extensions"),await n(gn)),Ft.value=gn;for(let e of qe)if(e instanceof mt){let{requestHandlerProxy:t}=e.instrument({accountName:g.instance.build.ACCOUNT_NAME,projectName:g.instance.build.PROJECT_NAME,buildId:g.instance.build.BUILD_ID,zuploVersion:g.instance.build.ZUPLO_VERSION,compatibilityDate:g.instance.build.COMPATIBILITY_DATE,instanceId:g.instance.instanceId,environmentType:g.instance.loggingEnvironmentType,environmentStage:g.instance.loggingEnvironmentStage,deploymentName:g.instance.deploymentName});Ps(t)}for(let e of qe)e instanceof Ze&&await e.initialize(gn);qt.setProblemResponseFormat(gn.problemResponseFormat),vs=!0}}i(As,"initializeRuntime");var fn={Json:"application/json",Form:"application/x-www-form-urlencoded"};function hn(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(fn.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(fn.Json)||!e?JSON.stringify(n):n}i(hn,"serialize");function gt(n){return he.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(he.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}i(gt,"isSystemRoute");var pe=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,t)=>async(r,o)=>yn.trace.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:yn.SpanStatusCode.ERROR}),c}finally{a.end()}});#t=({processors:e,gateway:t,handler:r})=>async(o,s)=>{let a=[...e],u=i(async E=>{let C=a.pop();return C?C(o,s,t,u):await this.#e(async j=>{let q=await r(j,s);return Tl(q)},t)(E,s)},"nextPipe"),l=await u(o),d=new URL(o.url);if(gt(d)&&g.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new ft(o,l);s.dispatchEvent(p);let h=ye.getContextExtensions(s),y=h.latestRequest,_;try{_=await p.mutableResponse}catch(E){return s.log.error(E),t.errorHandler(o,s,E)}try{_=await h.onResponseSending(_,y,s)}catch(E){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${E.message}'`,E),t.errorHandler(o,s,E)}try{_=await Os(_,y,s)}catch(E){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${E.message}'`,E),t.errorHandler(o,s,E)}s.dispatchEvent(new ht(o,_));try{await h.onResponseSendingFinal(l,y,s)}catch(E){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${E.message}'`,E),E}try{await Cs(l,y,s)}catch(E){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${E.message}'`,E),E}return _}};function Tl(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(hn(n),{headers:{"content-type":"application/json"}})}i(Tl,"resultToResponse");var $t=(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))($t||{}),_s={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 vl={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"},bn=vl;function Sl(n){return`${new URL(n.url).pathname}`}i(Sl,"instance");function Ol(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:g.instance.build.BUILD_ID},r=n.headers.get(ot);return r&&(t.rayId=r),t}i(Ol,"trace");var Cl=i((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:Sl(e),trace:Ol(e,t),...r},additionalHeaders:o,statusText:bn[n.status]}),"merge"),co=class{static{i(this,"HttpProblemsBase")}static format=(e,t,r)=>"problem"in e?Ge.format(e,t,r):Ge.format({problem:e},t,r);static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:_s[e],...t}}},T=class extends co{static{i(this,"HttpProblems")}static#e(e,t,r,o,s){let a=Cl(this.getProblemFromStatus(e),t,r,o,s);return Ge.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 Je=class extends Ve{static{i(this,"MetricsPlugin")}};var ne=class n{static{i(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 Q(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var X=class{static{i(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 wn=class{static{i(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=g.instance.loggingId,this.#e=e,this.#t=new X("ellie-metrics-transport",10,this.dispatchFunction,ne.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}=g.instance,{ACCOUNT_NAME:o,PROJECT_NAME:s}=g.instance.build,a=e.map(d=>{let p=Object.assign({},d);return delete p.requestContentLength,delete p.responseContentLength,p}),u=xs(),c={metadata:{timestamp:new Date,accountName:o,projectName:s,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":g.instance.deploymentName??"unknown","user-agent":g.instance.systemUserAgent}});if(!l.ok){let d=await l.text();ne.getLogger(this.#e).error(`Metrics POST responded ${l.status}: ${l.statusText}`,d),Ts(u)}}};var ue=class{static{i(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:r,systemRouteName:o,corsPolicy:s="none"}){this.label=e,this.path=t,this.methods=r,this.corsPolicy=s,this.version=jt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},jt={name:"__system-no-version",pathPrefix:""};var be=i(async(n,e,t,r)=>{let o=new Date,s=Date.now(),a=await r(n),u=n.headers.get(ot)??void 0,c=n.headers.get(hs)??void 0,l=e.incomingRequestProperties,d;e.route instanceof ue&&(d=e.route.systemRouteName);let p=ye.getContextExtensions(e).latestRequest,h={timestamp:o,statusCode:a.status,durationMs:Date.now()-s,requestContentLength:n.headers.get("content-length")?Number(n.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:n.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:g.instance.instanceId,userSub:p.user?.sub,clientIp:c},y=[];return y.push(new wn(e)),qe.forEach(_=>{if(_ instanceof Je){let E=_.getTransport();y.push(E)}}),y.forEach(_=>{_.pushMetrics(h,e)}),a},"metricsProcessor");var Me=(c=>(c.Build="build-data",c.CorsPreflight="cors-preflight",c.DeveloperPortal="developer-portal",c.DeveloperPortalLegacy="developer-portal-legacy",c.StripePlugin="stripe-plugin",c.EmptyGatewayCatchall="empty-gateway-catchall",c.Ping="ping",c.UnmatchedPath="unmatched-path",c))(Me||{});var lo=i((n,e)=>{let t=i(async(s,a)=>{let c=new URL(s.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return T.notFound(s,a);let l=g.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,compatibilityDate:l.COMPATIBILITY_DATE,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=s.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&ne.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 ue({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var{toString:Al}=Object.prototype,{propertyIsEnumerable:_l}=Object.prototype;function po(n){return Al.call(n)}i(po,"toString");function xe(n){return typeof n=="string"}i(xe,"isString");function yt(n){return xe(n)&&n!==""}i(yt,"isNonEmptyString");function Ls(n){return po(n)==="[object RegExp]"}i(Ls,"isRegexp");function ks(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>_l.call(n,e))]}i(ks,"getOwnEnumerableKeys");function it(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}i(it,"isObject");function mo(n){return typeof n=="number"&&!isNaN(n)}i(mo,"isNumber");function go(n){return n===!0||n===!1}i(go,"isBoolean");function Ns(n){return typeof n>"u"}i(Ns,"isUndefined");function Ms(n){return Ns(n)||n===null}i(Ms,"isUndefinedOrNull");function Bt(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(Bt,"isErrorLike");var Ds=new Map;function bt(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=Ds.get(n);if(e)return e;let t=n.split(","),r=[];for(let o of t){let s=o.split("-");if(s.length===2){let a=parseInt(s[0],10),u=parseInt(s[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return Ds.set(n,r),r}i(bt,"statusCodesStringToNumberArray");function st(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(s=>{if(o===void 0)throw new L(`Error applying ${t} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i(st,"getValueFromRequestUser");function Us(n,e){if(!e.startsWith("."))throw new m(`Invalid selector. must start with '.' - '${e}' does not`);let t=e.split(".").splice(1),r=n;return t.forEach(o=>{if(r===void 0)throw new L(`Error applying'${e}', reading '${o}'`);if(r&&typeof r=="object")r=Reflect.get(r,o);else throw new L(`Error applying'${e}', reading '${o}'`)}),`${r}`}i(Us,"selectPropertyUsingJsonPath");function at(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new m("Received an array that contains non-string values.");return n}if(xe(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new m(`Expected type of string, received type '${typeof n}'`)}i(at,"parseValueToStringArray");function Hs(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(!it(t))throw new m(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!yt(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 r=fo(t,"allowedHeaders"),o=fo(t,"allowedMethods"),s=fo(t,"exposeHeaders"),a;try{a=at(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:s?s.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}i(Hs,"parseCorsPolicies");function fo(n,e){let t;if(n[e]!==void 0)try{t=at(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}i(fo,"parseOptionalProperty");var Rn=i((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"),Pn=i((n,e)=>{let t={"access-control-allow-origin":e};n.allowedHeaders&&(t["access-control-allow-headers"]=n.allowedHeaders),n.allowedMethods&&(t["access-control-allow-methods"]=n.allowedMethods),n.exposeHeaders&&(t["access-control-expose-headers"]=n.exposeHeaders);let 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 ho=i((n,e)=>{let t=e.routeData.corsPolicies,r=i(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return T.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let h=n.lookup(l,c);if(!h)return T.notFound(a,u);let y=h.routeConfiguration,_=Ll(l,d,p,y,t);return _.isValid?new Response(void 0,{status:200,statusText:"OK",headers:_.headers}):(_.error&&u.log.warn(_.error),T.notFound(a,u))},"optionsHandler"),o=new pe({processors:[be],handler:r,gateway:e}),s=new ue({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(s,o.execute)},"registerCorsRoute"),Ll=i((n,e,t,r,o)=>{let s={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{...s,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:Pn(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var Zs=i((n,e)=>{let t=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new pe({processors:[be],handler:t,gateway:e}),o=new ue({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 yo=new ue({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),qs=i((n,e)=>{let t=i(async(o,s)=>{let a=Ft.value?.notFoundHandler;if(a){let u=ye.getContextExtensions(s);return a(o,s,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return T.notFound(o,s)},"notFoundHandler"),r=new pe({processors:[be],handler:t,gateway:e});n.addRoute(yo,r.execute)},"registerNotMatchedHandler");var kl=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Fs=i(n=>{kl.forEach(e=>n.delete(e))},"stripCorsHeaders"),En=i(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 Fs(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await r(n);if(!(s instanceof Response))throw new Q(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=Nl(o,t.routeData.corsPolicies),u=Ml(n,a),c=new Headers(s.headers);return Fs(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(s.body,{status:s.status,statusText:s.statusText,headers:c,webSocket:s.webSocket})},"corsProcessor"),Nl=i((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(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"),Ml=i((n,e)=>{let t=Rn(e.allowedOrigins,n.headers.get("origin"));return t?Pn(e,t):{}},"getCorsHeaders");var bo=i((n,e)=>{let t=i(async()=>new Response(JSON.stringify({buildId:g.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new pe({processors:[En],handler:t,gateway:e}),o=new ue({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");var wt=require("@opentelemetry/api");var _e={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var In=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!xe(t))throw new L(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},we=class extends In{static{i(this,"InboundPolicy")}},Fe=class extends In{static{i(this,"OutboundPolicy")}};var Po=class extends we{static{i(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)}},Eo=class extends Fe{static{i(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)}},wo=new Map;function zt(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(s=>!wo.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new m(`Invalid state - no Policy with the name '${s}' ${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 '${s}' 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 '${s}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof we)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 '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${s}' on route '${r}' (typeof handler '${typeof c.handler}')`);wo.set(a.name,c)}),t.map(s=>{let a=wo.get(s);if(a===void 0)throw new L("Internal error. Policy not found in cache.");return a})}i(zt,"getInboundPolicyInstances");var Ro=new Map;function Dl(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!Ro.has(o)).forEach(o=>{let s=e?.find(c=>c.name===o);if(!s)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 s.handler?.module!="object")throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof s.handler?.module}')`);let a=s.handler?.module[s.handler.export],u;if(typeof a!="function")throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof Fe)u=new a(s.handler.options??{},s.name);else if(typeof a=="function")u=new Eo(a,s.handler.options??{},s.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}'`);Ro.set(s.name,u)}),t.map(o=>{let s=Ro.get(o);if(s===void 0)throw new L("Internal error. Policy not found in cache.");return s})}i(Dl,"getOutboundPolicyInstances");var Io=i(n=>async(e,t)=>{let r=ye.getContextExtensions(t),o=wt.trace.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;let l=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{let p=await c.handler(u,t);if(p instanceof Request||p instanceof re||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:wt.SpanStatusCode.ERROR}),d.recordException(h),h}});if(l instanceof re)u=l;else if(l instanceof Request)u=new re(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),Ul=i(n=>async(e,t,r)=>{let o=wt.trace.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(_e.PolicyName,c.policyName),d.setAttribute(_e.PolicyType,c.policyType);let p=await c.handler(u,t,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:wt.SpanStatusCode.ERROR}),d.recordException(h),h}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),xn=i(async(n,e,t,r)=>{let o=zt(e.route,t.routeData.policies),s=Dl(e.route,t.routeData.policies);return js({request:n,context:e,inboundPolicies:o,outboundPolicies:s,gateway:t,next:r})},"policyProcessor");function $s({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>js({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i($s,"createInternalPolicyProcessor");async function js({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:s}){let a=Io(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await s(u),l=Ul(r),d;return g.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)}}i(js,"executePolicyProcessor");function Bs(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||Hl,s=0;for(;s<n.length;){let a=n.indexOf("=",s);if(a===-1)break;let u=n.indexOf(";",s);if(u===-1)u=n.length;else if(u<a){s=n.lastIndexOf(";",a-1)+1;continue}let c=n.slice(s,a).trim();if(t[c]===void 0){let l=n.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),t[c]=Zl(l,o)}s=u+1}return t}i(Bs,"parse");function Hl(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}i(Hl,"decode");function Zl(n,e){try{return e(n)}catch{return n}}i(Zl,"tryDecode");function zs(n,e){try{let t=/v\d+(-\d+)?/g,o=Bs(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}i(zs,"devPortalBaseURL");var Vs="/__zuplo/dev-portal",ql="dev-portal-id",Fl="dev-portal-host",$l="zp-account",jl="zp-project",Bl="dev-portal-build",zl=`
|
|
35
|
+
`)+" "+t[1]:t[0]+e+" "+n.join(", ")+" "+t[1]}i(gl,"reduceToSingleString")});var Vi=Zt(un=>{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.format=void 0;var fl=Zi(),hl=zi(),yl=i((n,...e)=>(0,fl.format)(hl.inspect,n,e),"format");un.format=yl});var Ze=Zt(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.debug=Ve.withoutEnv=Ve.Debugger=void 0;var bl=Hi(),wl=Vi(),cn=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=(0,bl.generateColor)(t),this.last=0,this.enabled=e.enabled.some(r=>r.test(t))}log(...e){if(!this.enabled)return;let t,r=e[0];typeof r=="function"?t=r():t=String(r);let o=Date.now()-(this.last||Date.now());t=(0,wl.format)(t,...e);let s=`${this.color(this.ns)} ${t} ${this.color(`+${o}ms`)}`;console.log(s),this.last=Date.now()}};Ve.Debugger=cn;var ln=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function Gi(n){return!n||n.length===0?[]:(n=n.replace(/\s/g,"").replace(/\*/g,".+"),n.split(",").map(e=>new RegExp(`^${e}$`)))}i(Gi,"extract");var qt;function Rl(n){n||(n=[]),typeof n=="string"&&(n=Gi(n)),qt=new ln(n)}i(Rl,"withoutEnv");Ve.withoutEnv=Rl;function Pl(n){let e=globalThis.DEBUG;qt||(qt=new ln(Gi(e)));let t=new cn(qt,n);return qt.debuggers.set(n,t),Object.assign(t.log.bind(t),{self:t})}i(Pl,"debug");Ve.debug=Pl});var Mp={};gc(Mp,{AWSLoggingPlugin:()=>nr,AmberfloMeteringInboundPolicy:()=>Fa,AmberfloMeteringPolicy:()=>cr,ApiAuthKeyInboundPolicy:()=>Ba,ApiKeyInboundPolicy:()=>dr,AuditLogDataStaxProvider:()=>ir,AuditLogPlugin:()=>sr,Auth0JwtInboundPolicy:()=>Ga,AwsLambdaHandlerExtensions:()=>ba,AxiomaticsAuthZInboundPolicy:()=>gr,BackgroundDispatcher:()=>xr,BackgroundLoader:()=>Tr,BasicAuthInboundPolicy:()=>Wa,BasicRateLimitInboundPolicy:()=>bi,BatchDispatch:()=>Q,BrownoutInboundPolicy:()=>yr,CachingInboundPolicy:()=>Ka,ChangeMethodInboundPolicy:()=>Ya,ClearHeadersInboundPolicy:()=>Xa,ClearHeadersOutboundPolicy:()=>Qa,ClerkJwtInboundPolicy:()=>eu,CognitoJwtInboundPolicy:()=>tu,ComplexRateLimitInboundPolicy:()=>Yn,CompositeInboundPolicy:()=>nu,ConfigurationError:()=>m,ContentTypes:()=>bn,ContextData:()=>he,CryptoBeta:()=>Sr,CurityPhantomTokenInboundPolicy:()=>ru,DataDogLoggingPlugin:()=>Mn,DataDogMetricsPlugin:()=>rr,DynaTraceLoggingPlugin:()=>Xn,DynatraceMetricsPlugin:()=>or,FirebaseJwtInboundPolicy:()=>ou,FormDataToJsonInboundPolicy:()=>iu,GeoFilterInboundPolicy:()=>su,GoogleCloudLoggingPlugin:()=>Ln,Handler:()=>Bn,HttpProblems:()=>x,HttpStatusCode:()=>zt,InboundPolicy:()=>fe,JWTScopeValidationInboundPolicy:()=>au,KeyValueStore:()=>Cr,LokiLoggingPlugin:()=>Qn,LookupResult:()=>Pt,MemoryZoneReadThroughCache:()=>de,MockApiInboundPolicy:()=>cu,MoesifInboundPolicy:()=>fu,MonetizationInboundPolicy:()=>wr,OktaJwtInboundPolicy:()=>Ru,OpenIdJwtInboundPolicy:()=>ye,OutboundPolicy:()=>$e,ProblemResponseFormatter:()=>We,PropelAuthJwtInboundPolicy:()=>Eu,RateLimitInboundPolicy:()=>bi,ReadmeMetricsInboundPolicy:()=>Au,RemoveHeadersInboundPolicy:()=>_u,RemoveHeadersOutboundPolicy:()=>Lu,RemoveQueryParamsInboundPolicy:()=>ku,ReplaceStringOutboundPolicy:()=>Nu,RequestSizeLimitInboundPolicy:()=>Du,RequestValidationInboundPolicy:()=>Pi,RequireOriginInboundPolicy:()=>Bu,ResponseSendingEvent:()=>ft,ResponseSentEvent:()=>ht,Router:()=>Et,RuntimeError:()=>L,SYSTEM_LOGGER:()=>$t,SchemaBasedRequestValidation:()=>ju,SemanticAttributes:()=>_e,ServiceProviderImpl:()=>Ir,SetBodyInboundPolicy:()=>zu,SetHeadersInboundPolicy:()=>Vu,SetHeadersOutboundPolicy:()=>Gu,SetQueryParamsInboundPolicy:()=>Wu,SetStatusOutboundPolicy:()=>Ju,SleepInboundPolicy:()=>Ku,StripeMonetizationPlugin:()=>ui,StripeWebhookVerificationInboundPolicy:()=>Ct,SumoLogicLoggingPlugin:()=>er,SupabaseJwtInboundPolicy:()=>Yu,SystemRouteName:()=>Me,TelemetryPlugin:()=>mt,UpstreamAzureAdServiceAuthInboundPolicy:()=>Xu,UpstreamFirebaseAdminAuthInboundPolicy:()=>ec,UpstreamFirebaseUserAuthInboundPolicy:()=>tc,UpstreamGcpJwtInboundPolicy:()=>nc,UpstreamGcpServiceAuthInboundPolicy:()=>oc,VMWareLogInsightLoggingPlugin:()=>tr,ValidateJsonSchemaInbound:()=>ic,XmlToJsonOutboundPolicy:()=>Er,ZoneCache:()=>pt,ZuploRequest:()=>re,awsLambdaHandler:()=>wa,environment:()=>Pe,getIdForParameterSchema:()=>Rr,getIdForRefSchema:()=>Hu,getIdForRequestBodySchema:()=>Pr,getRawOperationDataIdentifierName:()=>Uu,httpStatuses:()=>Pn,openApiSpecHandler:()=>Ra,redirectHandler:()=>Pa,sanitizedIdentifierName:()=>et,serialize:()=>wn,setMoesifContext:()=>gu,trackFeature:()=>y,urlForwardHandler:()=>Ea,urlRewriteHandler:()=>Ia,webSocketHandler:()=>xa,webSocketPipelineHandler:()=>Sa});module.exports=fc(Mp);var Yi=Be(Ze());var Y=class extends Error{static{i(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},L=class extends Error{static{i(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},m=class extends L{static{i(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}},dn=class extends L{static{i(this,"FeatureNotEnabledError")}constructor(e,t){super(e,t),this.name="FeatureNotEnabledError"}};var qr="2024-03-14",Wi=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0}});function Ji(){return new g({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),IS_PRODUCTION:!1,BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:qr,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,COMPATIBILITY_FLAGS:Wi[qr]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}i(Ji,"getMockEnvironment");var g=class n{static{i(this,"Environment")}config;static#e;static#t=!1;static initialize(e){this.#e||(this.#e=new n(e),this.#t=!0)}static get instance(){return this.#t||(console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=Ji()),this.#e}constructor({build:e,runtime:t}){let r;try{if(t.__ZUPLO_CONFIG){let o=atob(t.__ZUPLO_CONFIG);r=JSON.parse(o)}}catch{console.warn("Failed to parse runtime configuration")}this.config=r??{},this.build=e,this.runtime=t,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.ENVIRONMENT_TYPE?this.build.ENVIRONMENT_TYPE==="LOCAL_DEVELOPMENT":!1}get isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var nt=(0,Yi.debug)("zuplo:runtime:external-service");function El(){let n,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=g.instance.runtime;if(e&&e!=="undefined")try{let t=atob(e);n=JSON.parse(t)}catch{}return n}i(El,"getServiceAuth");async function Xi(n,e){let t=El();if(t)if(nt(`Using external service auth. ClientId: ${t.clientId})`),typeof n=="string"){let r=new URL(n),o=r.hostname,s=e??{},a=new Headers(s.headers||{});a.set("CF-Access-Client-Id",t.clientId),a.set("CF-Access-Client-Secret",t.clientSecret),s.headers=a;let u;if(t.customServiceMapping&&t.customServiceMapping[o])u=`https://${t.customServiceMapping[o]}`;else if(g.instance.useLegacyServiceRouting)u=`https://${o}.zuptunnel.com`;else{nt("Using sha256 service routing");let d=g.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await Il(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw nt("Cannot use sha256 service routing, missing build variables"),new L("Failed to generate fully qualified tunnel url.")}let c=new URL(`${u}${r.pathname}${r.search}`);nt(`Calling external service: ${c.toString()}`);let l=await F.fetch(c.toString(),s);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:t.clientId,tunnelHost:u}),new L("Could not connect to secure tunnel.");return l}else throw nt("Cannot call external service with Request object"),new L("Currently, we only support fetch(<some_string>, ...).");else throw nt("There is no external service auth configured for this zup."),new L("There are no external services configured for this zup.")}i(Xi,"externalServiceHandler");async function Il(n,e,t,r){let o=n.toLowerCase(),s=e.toLowerCase(),a=t.toLowerCase(),u=xl(r);nt(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await Ki(`${s}-${o}`),l=await Ki(`${s}-${a}-${u}`);return`${c}.${l}`}i(Il,"hashServiceName");async function Ki(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("").slice(0,-1)}i(Ki,"hashSegment");function xl(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(xl,"sanitizeEnvironmentType");var es=new Map;es.set("service:",Xi);var Qi=globalThis.fetch;function Fr(n,e){let t=Tl(e);if(typeof n=="string"){let r=new URL(n),o=es.get(r.protocol);return o?o(n,t):Qi(n,t)}else return Qi(n,t)}i(Fr,"internalFetch");globalThis.fetch=Fr;var Tl=i(n=>{if(!n||n instanceof Request)return n;let e=n;if(!e.zuplo)return n;let t=n;return t.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete n.zuplo,n},"transformInit");var vl={fetch:Fr},F=vl;Function.prototype.toString=function(){return"[native code]"};var pn=globalThis,ts=pn.caches;if(ts){let n=ts.open;pn.caches.open=function(e){let t=g.instance.deploymentName??g.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete pn.caches.default,Object.freeze(pn.caches)}var ns=new Map,$r=class{static{i(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(),s={created:o,lastUsed:o,expiresAt:o+r*1e3,data:t};this.#r.push(e),this.#n.set(e,s)}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)})}},dt=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=ns.get(e);r||(r=new $r(t),ns.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 jr="__zuplo-expiry-header",pt=class{static{i(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 s=o.headers.get(jr);if(!s){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(s);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(jr,`${Date.now()+r*1e3}`);let s=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(t),{headers:o});await s.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(jr,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),s=new Response("",{headers:t});await r.put(o,s)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var de=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new dt(r),this.#n=new pt(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},s=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(s)}};var rs="zuplo-request-id",rt="zp-rid",Br="zp-body-removed",ot="cf-ray",os="x-real-ip",zr="cf-ipcity",Vr="cf-ipcontinent",Gr="cf-ipcountry",Wr="cf-iplongitude",Jr="cf-iplatitude",is="cf-region",ss="cf-region-code",as="cf-metro-code",us="cf-postal-code",cs="cf-timezone",ls="zp-ipcity",ds="zp-ipcontinent",ps="zp-ipcountry",ms="zp-iplongitude",gs="zp-iplatitude",fs="true-client-ip",Kr="zp-asn",Yr="zp-asorg",Xr="zp-colo",Qr="zp-postalcode",eo="zp-metrocode",to="zp-region",no="zp-regioncode",ro="zp-timezone",hs=[zr,Vr,Gr,Wr,Jr,Kr,Yr,Xr,Qr,eo,to,no,ro],ys=["zp-","cf-"],bs=[rt,ot,Br];var Ft=Symbol("zuplo_meters"),mn=Symbol("zuplo_dynamic_meters"),$t="system-logger";var ra=require("@opentelemetry/api"),oa=Be(Ze());var Rn=require("@opentelemetry/api");var Je=require("@opentelemetry/api");var ws=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function Rs(n){ws=n}i(Rs,"setTelemetryInitFunction");var Ps=i(n=>ws(n),"proxyHandler");var Ge=class{static{i(this,"RuntimePlugin")}},qe=class extends Ge{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},gn=class extends qe{static{i(this,"MeteringPlugin")}},mt=class extends Ge{static{i(this,"TelemetryPlugin")}};var fn=new Set,Es=new Set;function y(n){Es.has(n)||(Es.add(n),fn.add(n))}i(y,"trackFeature");function Is(){let n=[...fn];return fn.clear(),n}i(Is,"getUnsentFeatures");function xs(n){for(let e of n)fn.add(e)}i(xs,"restoreFeatures");var jt=class n{static{i(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&&(y("runtime.problem-response-formatter"),n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(s){throw new L("Error in custom 'problemResponseFormat'",{cause:s})}})}},We=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,r){return await jt.problemResponseFormat(e,t,r)}};function hn(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&hn(t)}return Object.freeze(n)}i(hn,"deepFreeze");var re=class n extends Request{static{i(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 hn(this.#e)}get params(){return hn(this.#t)}user};var Bt={},Fe=[],oo=[],io=[],so=[];var yn={addPlugin(n){Fe.push(n)},addRequestHook(n){oo.push(n)},addResponseSendingHook(n){io.push(n)},addResponseSendingFinalHook(n){so.push(n)}},vs=i(async(n,e)=>{if(oo.length===0)return n;let t=Je.trace.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let s of oo){let a=await t.startActiveSpan(s.name,async u=>{let c=await s(o,e);if(c instanceof re||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:Je.SpanStatusCode.ERROR}),l}});if(a instanceof re)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),Ss=i(async(n,e,t)=>{if(io.length===0)return n;let r=Je.trace.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let s=n;for(let a of io)await r.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)s=c,u.end();else{let l=new m(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof s}.`);throw u.recordException(l),u.setStatus({code:Je.SpanStatusCode.ERROR}),u.end(),l}});return s}finally{o.end()}})},"invokeOnResponseSendingExtensions"),Os=i(async(n,e,t)=>{if(so.length===0)return;let r=Je.trace.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let s of so)await r.startActiveSpan(s.name,async a=>{try{await s(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:Je.SpanStatusCode.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),Ts=!1;async function Cs(n){if(!Ts){n&&(y("runtime.extensions"),await n(yn)),Bt.value=yn;for(let e of Fe)if(e instanceof mt){let{requestHandlerProxy:t}=e.instrument({accountName:g.instance.build.ACCOUNT_NAME,projectName:g.instance.build.PROJECT_NAME,buildId:g.instance.build.BUILD_ID,zuploVersion:g.instance.build.ZUPLO_VERSION,compatibilityDate:g.instance.build.COMPATIBILITY_DATE,instanceId:g.instance.instanceId,environmentType:g.instance.loggingEnvironmentType,environmentStage:g.instance.loggingEnvironmentStage,deploymentName:g.instance.deploymentName});Rs(t)}for(let e of Fe)e instanceof qe&&await e.initialize(yn);jt.setProblemResponseFormat(yn.problemResponseFormat),Ts=!0}}i(Cs,"initializeRuntime");var bn={Json:"application/json",Form:"application/x-www-form-urlencoded"};function wn(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(bn.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(bn.Json)||!e?JSON.stringify(n):n}i(wn,"serialize");function gt(n){return be.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(be.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}i(gt,"isSystemRoute");var pe=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,t)=>async(r,o)=>Rn.trace.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:Rn.SpanStatusCode.ERROR}),c}finally{a.end()}});#t=({processors:e,gateway:t,handler:r})=>async(o,s)=>{let a=[...e],u=i(async P=>{let C=a.pop();return C?C(o,s,t,u):await this.#e(async B=>{let Z=await r(B,s);return Sl(Z)},t)(P,s)},"nextPipe"),l=await u(o),d=new URL(o.url);if(gt(d)&&g.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new ft(o,l);s.dispatchEvent(p);let f=we.getContextExtensions(s),h=f.latestRequest,A;try{A=await p.mutableResponse}catch(P){return s.log.error(P),t.errorHandler(o,s,P)}try{A=await f.onResponseSending(A,h,s)}catch(P){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(o,s,P)}try{A=await Ss(A,h,s)}catch(P){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(o,s,P)}s.dispatchEvent(new ht(o,A));try{await f.onResponseSendingFinal(l,h,s)}catch(P){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}try{await Os(l,h,s)}catch(P){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}return A}};function Sl(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(wn(n),{headers:{"content-type":"application/json"}})}i(Sl,"resultToResponse");var zt=(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))(zt||{}),As={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 Ol={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"},Pn=Ol;function Cl(n){return`${new URL(n.url).pathname}`}i(Cl,"instance");function Al(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:g.instance.build.BUILD_ID},r=n.headers.get(ot);return r&&(t.rayId=r),t}i(Al,"trace");var _l=i((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:Cl(e),trace:Al(e,t),...r},additionalHeaders:o,statusText:Pn[n.status]}),"merge"),ao=class{static{i(this,"HttpProblemsBase")}static format=(e,t,r)=>"problem"in e?We.format(e,t,r):We.format({problem:e},t,r);static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:As[e],...t}}},x=class extends ao{static{i(this,"HttpProblems")}static#e(e,t,r,o,s){let a=_l(this.getProblemFromStatus(e),t,r,o,s);return We.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 Ke=class extends Ge{static{i(this,"MetricsPlugin")}};var ee=class n{static{i(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 Y(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var Q=class{static{i(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 En=class{static{i(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=g.instance.loggingId,this.#e=e,this.#t=new Q("ellie-metrics-transport",10,this.dispatchFunction,ee.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}=g.instance,{ACCOUNT_NAME:o,PROJECT_NAME:s}=g.instance.build,a=e.map(d=>{let p=Object.assign({},d);return delete p.requestContentLength,delete p.responseContentLength,p}),u=Is(),c={metadata:{timestamp:new Date,accountName:o,projectName:s,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":g.instance.deploymentName??"unknown","user-agent":g.instance.systemUserAgent}});if(!l.ok){let d=await l.text();ee.getLogger(this.#e).error(`Metrics POST responded ${l.status}: ${l.statusText}`,d),xs(u)}}};var ue=class{static{i(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:r,systemRouteName:o,corsPolicy:s="none"}){this.label=e,this.path=t,this.methods=r,this.corsPolicy=s,this.version=Vt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Vt={name:"__system-no-version",pathPrefix:""};var Re=i(async(n,e,t,r)=>{let o=new Date,s=Date.now(),a=await r(n),u=n.headers.get(ot)??void 0,c=n.headers.get(fs)??void 0,l=e.incomingRequestProperties,d;e.route instanceof ue&&(d=e.route.systemRouteName);let p=we.getContextExtensions(e).latestRequest,f={timestamp:o,statusCode:a.status,durationMs:Date.now()-s,requestContentLength:n.headers.get("content-length")?Number(n.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:n.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:g.instance.instanceId,userSub:p.user?.sub,clientIp:c},h=[];return h.push(new En(e)),Fe.forEach(A=>{if(A instanceof Ke){let P=A.getTransport();h.push(P)}}),h.forEach(A=>{A.pushMetrics(f,e)}),a},"metricsProcessor");var Me=(c=>(c.Build="build-data",c.CorsPreflight="cors-preflight",c.DeveloperPortal="developer-portal",c.DeveloperPortalLegacy="developer-portal-legacy",c.StripePlugin="stripe-plugin",c.EmptyGatewayCatchall="empty-gateway-catchall",c.Ping="ping",c.UnmatchedPath="unmatched-path",c))(Me||{});var uo=i((n,e)=>{let t=i(async(s,a)=>{let c=new URL(s.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return x.notFound(s,a);let l=g.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,compatibilityDate:l.COMPATIBILITY_DATE,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=s.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&ee.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:[Re],handler:t,gateway:e}),o=new ue({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var{toString:Ll}=Object.prototype,{propertyIsEnumerable:kl}=Object.prototype;function co(n){return Ll.call(n)}i(co,"toString");function Te(n){return typeof n=="string"}i(Te,"isString");function yt(n){return Te(n)&&n!==""}i(yt,"isNonEmptyString");function _s(n){return co(n)==="[object RegExp]"}i(_s,"isRegexp");function Ls(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>kl.call(n,e))]}i(Ls,"getOwnEnumerableKeys");function it(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}i(it,"isObject");function lo(n){return typeof n=="number"&&!isNaN(n)}i(lo,"isNumber");function po(n){return n===!0||n===!1}i(po,"isBoolean");function ks(n){return typeof n>"u"}i(ks,"isUndefined");function Ns(n){return ks(n)||n===null}i(Ns,"isUndefinedOrNull");function Gt(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(Gt,"isErrorLike");var Ms=new Map;function bt(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=Ms.get(n);if(e)return e;let t=n.split(","),r=[];for(let o of t){let s=o.split("-");if(s.length===2){let a=parseInt(s[0],10),u=parseInt(s[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return Ms.set(n,r),r}i(bt,"statusCodesStringToNumberArray");function st(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(s=>{if(o===void 0)throw new L(`Error applying ${t} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i(st,"getValueFromRequestUser");function Ds(n,e){if(!e.startsWith("."))throw new m(`Invalid selector. must start with '.' - '${e}' does not`);let t=e.split(".").splice(1),r=n;return t.forEach(o=>{if(r===void 0)throw new L(`Error applying'${e}', reading '${o}'`);if(r&&typeof r=="object")r=Reflect.get(r,o);else throw new L(`Error applying'${e}', reading '${o}'`)}),`${r}`}i(Ds,"selectPropertyUsingJsonPath");function at(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(Te(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new m(`Expected type of string, received type '${typeof n}'`)}i(at,"parseValueToStringArray");function Us(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(!it(t))throw new m(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!yt(t.name))throw new m("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!lo(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&&!po(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=mo(t,"allowedHeaders"),o=mo(t,"allowedMethods"),s=mo(t,"exposeHeaders"),a;try{a=at(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:s?s.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}i(Us,"parseCorsPolicies");function mo(n,e){let t;if(n[e]!==void 0)try{t=at(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}i(mo,"parseOptionalProperty");var In=i((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"),xn=i((n,e)=>{let t={"access-control-allow-origin":e};n.allowedHeaders&&(t["access-control-allow-headers"]=n.allowedHeaders),n.allowedMethods&&(t["access-control-allow-methods"]=n.allowedMethods),n.exposeHeaders&&(t["access-control-expose-headers"]=n.exposeHeaders);let 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 go=i((n,e)=>{let t=e.routeData.corsPolicies,r=i(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return x.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let f=n.lookup(l,c);if(!f)return x.notFound(a,u);let h=f.routeConfiguration,A=Nl(l,d,p,h,t);return A.isValid?new Response(void 0,{status:200,statusText:"OK",headers:A.headers}):(A.error&&u.log.warn(A.error),x.notFound(a,u))},"optionsHandler"),o=new pe({processors:[Re],handler:r,gateway:e}),s=new ue({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(s,o.execute)},"registerCorsRoute"),Nl=i((n,e,t,r,o)=>{let s={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{...s,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=In(a.allowedOrigins,t);return u?{isValid:!0,headers:xn(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var Hs=i((n,e)=>{let t=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new pe({processors:[Re],handler:t,gateway:e}),o=new ue({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 fo=new ue({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Zs=i((n,e)=>{let t=i(async(o,s)=>{let a=Bt.value?.notFoundHandler;if(a){let u=we.getContextExtensions(s);return a(o,s,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return x.notFound(o,s)},"notFoundHandler"),r=new pe({processors:[Re],handler:t,gateway:e});n.addRoute(fo,r.execute)},"registerNotMatchedHandler");var Ml=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],qs=i(n=>{Ml.forEach(e=>n.delete(e))},"stripCorsHeaders"),Tn=i(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 qs(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await r(n);if(!(s instanceof Response))throw new Y(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=Dl(o,t.routeData.corsPolicies),u=Ul(n,a),c=new Headers(s.headers);return qs(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(s.body,{status:s.status,statusText:s.statusText,headers:c,webSocket:s.webSocket})},"corsProcessor"),Dl=i((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(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"),Ul=i((n,e)=>{let t=In(e.allowedOrigins,n.headers.get("origin"));return t?xn(e,t):{}},"getCorsHeaders");var ho=i((n,e)=>{let t=i(async()=>new Response(JSON.stringify({buildId:g.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new pe({processors:[Tn],handler:t,gateway:e}),o=new ue({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");var wt=require("@opentelemetry/api");var _e={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var vn=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!Te(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}},fe=class extends vn{static{i(this,"InboundPolicy")}},$e=class extends vn{static{i(this,"OutboundPolicy")}};var wo=class extends fe{static{i(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)}},Ro=class extends $e{static{i(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)}},yo=new Map;function Wt(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(s=>!yo.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new m(`Invalid state - no Policy with the name '${s}' ${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 '${s}' 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 '${s}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof fe)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new wo(u,a.handler.options,a.name);else throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${s}' on route '${r}' (typeof handler '${typeof c.handler}')`);yo.set(a.name,c)}),t.map(s=>{let a=yo.get(s);if(a===void 0)throw new L("Internal error. Policy not found in cache.");return a})}i(Wt,"getInboundPolicyInstances");var bo=new Map;function Hl(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!bo.has(o)).forEach(o=>{let s=e?.find(c=>c.name===o);if(!s)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 s.handler?.module!="object")throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof s.handler?.module}')`);let a=s.handler?.module[s.handler.export],u;if(typeof a!="function")throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof $e)u=new a(s.handler.options??{},s.name);else if(typeof a=="function")u=new Ro(a,s.handler.options??{},s.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}'`);bo.set(s.name,u)}),t.map(o=>{let s=bo.get(o);if(s===void 0)throw new L("Internal error. Policy not found in cache.");return s})}i(Hl,"getOutboundPolicyInstances");var Po=i(n=>async(e,t)=>{let r=we.getContextExtensions(t),o=wt.trace.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;let l=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{let p=await c.handler(u,t);if(p instanceof Request||p instanceof re||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:wt.SpanStatusCode.ERROR}),d.recordException(f),f}});if(l instanceof re)u=l;else if(l instanceof Request)u=new re(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),Zl=i(n=>async(e,t,r)=>{let o=wt.trace.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(_e.PolicyName,c.policyName),d.setAttribute(_e.PolicyType,c.policyType);let p=await c.handler(u,t,r);if(p instanceof Response)return p;{let f=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:wt.SpanStatusCode.ERROR}),d.recordException(f),f}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),Sn=i(async(n,e,t,r)=>{let o=Wt(e.route,t.routeData.policies),s=Hl(e.route,t.routeData.policies);return $s({request:n,context:e,inboundPolicies:o,outboundPolicies:s,gateway:t,next:r})},"policyProcessor");function Fs({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>$s({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(Fs,"createInternalPolicyProcessor");async function $s({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:s}){let a=Po(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await s(u),l=Zl(r),d;return g.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)}}i($s,"executePolicyProcessor");function js(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||ql,s=0;for(;s<n.length;){let a=n.indexOf("=",s);if(a===-1)break;let u=n.indexOf(";",s);if(u===-1)u=n.length;else if(u<a){s=n.lastIndexOf(";",a-1)+1;continue}let c=n.slice(s,a).trim();if(t[c]===void 0){let l=n.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),t[c]=Fl(l,o)}s=u+1}return t}i(js,"parse");function ql(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}i(ql,"decode");function Fl(n,e){try{return e(n)}catch{return n}}i(Fl,"tryDecode");function Bs(n,e){try{let t=/v\d+(-\d+)?/g,o=js(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}i(Bs,"devPortalBaseURL");var zs="/__zuplo/dev-portal",$l="dev-portal-id",jl="dev-portal-host",Bl="zp-account",zl="zp-project",Vl="dev-portal-build",Gl=`
|
|
36
36
|
<!DOCTYPE html>
|
|
37
37
|
<html lang="en">
|
|
38
38
|
<head>
|
|
@@ -46,20 +46,20 @@
|
|
|
46
46
|
<p>For more information, see <a href="https://zuplo.com/docs/articles/developer-portal">https://zuplo.com/docs/articles/developer-portal</a>.</p>
|
|
47
47
|
</body>
|
|
48
48
|
</html>
|
|
49
|
-
`,
|
|
50
|
-
`).filter(e=>!e.trim().startsWith("at async file")).map((e,t)=>{let r=e.replaceAll(
|
|
51
|
-
`)}i(
|
|
49
|
+
`,Vs=i((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=g.instance.deploymentName,o=g.instance.devPortalBaseUrl,s=i(async(c,l)=>{if(g.instance.isLocalDevelopment)return new Response(Gl,{headers:{"content-type":"text/html"}});if(!r)return x.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=Bs(o,c.headers),f=new URL(`${d.pathname}${d.search}`,p),{headers:h,method:A,body:P}=c;return g.instance.build.ACCOUNT_NAME&&h.set(Bl,g.instance.build.ACCOUNT_NAME),g.instance.build.PROJECT_NAME&&h.set(zl,g.instance.build.PROJECT_NAME),h.set($l,r),h.set(jl,d.host),h.set(Vl,g.instance.build.BUILD_ID),await F.fetch(f.toString(),{headers:h,method:A,body:P,redirect:"manual"})},"devPortalRoute"),a=new pe({processors:[Re,Sn],handler:s,gateway:e}),u=new ue({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"),Gs=i((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=i(async a=>{let u=new URL(a.url);return u.pathname=`${t}${u.pathname.substring(zs.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new pe({processors:[Re],handler:r,gateway:e}),s=new ue({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${zs}(.*)`,systemRouteName:"developer-portal-legacy"});n.addRoute(s,o.execute)},"registerDevPortalLegacyRedirectRoute");var ea=Be(Ze());var Eo=0,Jt=class{static{i(this,"CoreLogger")}constructor(e,t,r,o,s){this.#n=t,this.#r=r??"local",this.#o=o,this.#i=s,this.#e(e)}#e=e=>{let t=["error","warn","info","debug"],r=!1,o=i(()=>{},"emptyFunction"),s=i((a,u)=>{this.#i.forEach(c=>{c.log(a,u)})},"pushFunction");t.forEach(a=>{this.#t[a]=r?o:s,a==e&&(r=!0)})};#t={};#n;#r;#o;#i;log(e,t,r,o,s,a){Eo>=Number.MAX_SAFE_INTEGER&&(Eo=0);let u={requestId:r,rayId:o,level:e,logSource:t,messages:s,timestamp:new Date,logOwner:this.#n,loggingId:this.#r,buildId:this.#o,vectorClock:Eo++};this.#t[e](u,a)}};var me=class extends Ge{static{i(this,"LogPlugin")}};var On=class{static{i(this,"LoggingContext")}constructor(e,t,r){this.#e=e,this.custom=t,this.originalRequest=r}#e;custom;originalRequest;waitUntil=e=>{this.#e.waitUntil(e)}};var Kt=class{static{i(this,"RequestLogger")}constructor(e,t,r,o){this.#t=e,this.#n=t,this.#r=r,this.#o=o}#e="request";#t;#n;#r;#o;debug=(...e)=>{this.#r.log("debug",this.#e,this.#t,this.#n,e,this.#o)};info=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};log=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};warn=(...e)=>{this.#r.log("warn",this.#e,this.#t,this.#n,e,this.#o)};error=(...e)=>{this.#r.log("error",this.#e,this.#t,this.#n,e,this.#o)}};var Wl=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(n=>[n.name,n]),Jl=new Map(Wl);var Kl=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],Io=Symbol(".toJSON was called"),Yl=i(n=>{n[Io]=!0;let e=n.toJSON();return delete n[Io],e},"toJSON"),Xl=i(n=>Jl.get(n)??Error,"getErrorConstructor"),Ws=i(({from:n,seen:e,to:t,forceEnumerable:r,maxDepth:o,depth:s,useToJSON:a,serialize:u})=>{if(!t)if(Array.isArray(n))t=[];else if(!u&&Gt(n)){let l=Xl(n.name);t=new l}else t={};if(e.push(n),s>=o)return t;if(a&&typeof n.toJSON=="function"&&n[Io]!==!0)return Yl(n);let c=i(l=>Ws({from:l,seen:[...e],forceEnumerable:r,maxDepth:o,depth:s,useToJSON:a,serialize:u}),"continueDestroyCircular");for(let[l,d]of Object.entries(n)){if(typeof Buffer=="function"&&Buffer.isBuffer(d)){t[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){t[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){t[l]=d;continue}if(!e.includes(n[l])){s++,t[l]=c(n[l]);continue}t[l]="[Circular]"}}for(let{property:l,enumerable:d}of Kl)typeof n[l]<"u"&&n[l]!==null&&Object.defineProperty(t,l,{value:Gt(n[l])?c(n[l]):n[l],enumerable:r?!0:d,configurable:!0,writable:!0});return t},"destroyCircular");function Ee(n,e){let t=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof n=="object"&&n!==null?Ws({from:n,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:r,serialize:!0}):typeof n=="function"?`[Function: ${n.name??"anonymous"}]`:n}i(Ee,"serializeError");var Ql=/file:\/\/\/(.*?)\/dist\//g,ed="at async Event.respondWith";function Js(n){return typeof n!="string"?n:n.split(`
|
|
50
|
+
`).filter(e=>!e.trim().startsWith("at async file")).map((e,t)=>{let r=e.replaceAll(Ql,"").replaceAll(ed,"").trim();return t===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
|
|
51
|
+
`)}i(Js,"cleanStack");function Cn(n,e,t=""){let r=[],o=e?.maxDepth??3;return i(function s(a,u={},c,l){let d=u.indent||" ",p;u.inlineCharacterLimit===void 0?p={newline:`
|
|
52
52
|
`,newlineOrSpace:`
|
|
53
|
-
`,pad:c,indent:c+d}:p={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let
|
|
54
|
-
`).replace(new RegExp(p.pad,"g"),c).replace(new RegExp(p.indent,"g"),c+d)},"expandWhiteSpace");if(r.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||
|
|
55
|
-
`?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}i(
|
|
56
|
-
`)}i(Ys,"messagesToMultilineText");function $e(n){return typeof n=="string"?n:JSON.stringify(n)}i($e,"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"}i(vo,"stringifyNonStringToText");var Sn=require("jose");async function Ee(n,e,t){for(let r=0;r<=n.retries;r++){let o=F.fetch(e,t);if(r===n.retries)return o;let s=await o;if(s.status<500&&s.status!==429)return s;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,r)))}throw new m("An unknown error occurred, ensure retries is not negative")}i(Ee,"fetchRetry");async function De({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=n;return await new Sn.SignJWT(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(De,"getTokenFromGcpServiceAccount");async function Xs(n,e,t){return Qs(n,{token:e,returnSecureToken:!0},t)}i(Xs,"exchangeFirebaseJwtForIdToken");async function On(n,e,t){return Qs(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(On,"exchangeGgpJwtForIdToken");async function Qs(n,e,t){let r=await Ee(t,n,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let s;try{let a=await r.text(),u=JSON.parse(a);s={cause:u.error??u}}catch{}throw new L({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(Qs,"fetchToken");var Te=class n{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),r=await(0,Sn.importPKCS8)(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}};var Cn=class extends me{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Wt(this.options)}},Ql="https://logging.googleapis.com/v2/entries:write?alt=json",So={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Wt=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=g.instance.loggingEnvironmentType,this.#i=g.instance.loggingEnvironmentStage,this.#r=g.instance.deploymentName,f("logging.google-cloud")}#e;#t;#n;#r;#o;#i;async init(){this.#t=await Te.init(this.#e)}log(e,t){if(!this.#t)throw new Q("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:Ke(e.messages)},o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:So[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&&(s.labels.rayId=e.rayId);let a=Rt(r.allMessages);s.jsonPayload={...r,message:a},this.batcher.enqueue(s),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await Te.init(this.#e));let t=await De({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await F.fetch(Ql,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});r.ok||console.error(r.status,r.statusText,await r.text())};batcher=new X("google-log-transport",1,this.dispatchFunction)};var An="gcp";function _n(n){let e={allMessages:Ke(n.messages)},t="zuplo-production",r=Rt(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:So[n.level],timestamp:n.timestamp,"logging.googleapis.com/labels":{buildId:n.buildId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${n.requestId}`,allMessages:e.allMessages};return n.rayId&&(o["logging.googleapis.com/labels"].rayId=n.rayId),o}i(_n,"gcpLogFormat");var Jt=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===An){if(e.messages.length===0)return;this.#e[e.level].apply(null,[_n(e)])}else this.#e.log(JSON.stringify(e))}};var Ln=class extends me{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new Kt(this.options)}},Oo="__ddtags",Co="__ddattr",Ao=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),ed=i(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(Ao(r)):t.push(`${Ao(r)}:${Ao(o.toString())}`)}),t.join(",")},"formatTags"),Kt=class{static{i(this,"DataDogTransport")}constructor(e){f("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=g.instance.loggingEnvironmentType,this.#o=g.instance.loggingEnvironmentStage,this.#n=g.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[Oo];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(y=>y[Oo]!==void 0);a>-1&&(Object.assign(r,s[a][Oo]),s.splice(a,1));let u={},c=t.custom[Co];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(y=>y[Co]!==void 0);l>-1&&(Object.assign(u,s[l][Co]),s.splice(l,1));let d=Ke(s),h={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:Rt(d),service:e.loggingId,ddtags:ed(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=>{e.length!==0&&await F.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new X("data-dog-transport",10,this.dispatchFunction)};var Yt=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===An){if(e.messages.length===0)return;this.#e[e.level].apply(null,[_n(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 td=i(({url:n,remoteLogToken:e,loggingId:t,sendOnlyErrors:r})=>async o=>{let s;if(r===!0?s=o.filter(a=>a.level==="error"):s=o,s.length!==0)try{await F.fetch(`${n}/publish/${t}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:s.map(a=>({...a,messages:Ke(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":g.instance.systemUserAgent,"zp-dn":g.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),kn,Nn=class{static{i(this,"RemoteLogTransport")}constructor(e){kn||(kn=new X("remote-log-transport",1,td(e)))}log(e,t){kn.enqueue(e),t.waitUntil(kn.waitUntilFlushed())}};var nd={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},ea=i((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:nd[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var rd=i(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let s=ea(t,r);try{await F.fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":g.instance.systemUserAgent,"zp-dn":g.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Mn,Dn=class{static{i(this,"UnifiedLogTransport")}constructor(e){Mn||(Mn=new X("unified-log-transport",1,rd(e)))}async log(e,t){Mn.enqueue(e),t.waitUntil(Mn.waitUntilFlushed())}};var _o=(0,ta.debug)("zuplo:logging"),Un=class n{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(g.instance,e),r=await n.setupUserCoreLogger(g.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;_o("Gateway.setupSystemCoreLogger");let o=[],s=t.getService(Zt);return s?o.push(new Yt(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new Jt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Dn({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 Vt(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){_o("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=t.getService(Zt);if(a&&a.captureUserLogs===!0?r.push(new Yt(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new Jt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new Nn({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:!e.isWorkingCopy})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new Wt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME})),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new Kt({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return qe.forEach(u=>{u instanceof me&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new Vt(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,t,r,o,s){_o("Gateway.createRequestLoggers");let a=new Tn(r,o,s),u=new Gt(e,t,this.systemCoreLogger,a);return{userRequestLogger:new Gt(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var ut=class{static{i(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};var Lo=class{static{i(this,"RouterEntry")}constructor(e,t,r,o){this.fullPath=e,this.urlPattern=t,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},Pt=class{static{i(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},ko=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}},Et=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof ut||e instanceof ue))throw new Q("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(s=>s.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let s=new URLPattern({pathname:o}),a=new Lo(o,s,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new ko(`addRoute-error: Invalid path '${o}'. '${s.message}'`,{cause:s})}}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 s=r[o],u=s.urlPattern.exec({pathname:t});if(u!==null)return new Pt(s.config,s.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 Pt(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var No;function na(n){No=n}i(na,"setGlobalZuploEventContext");function Hn(){if(No===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return No}i(Hn,"getGlobalZuploEventContext");function ra({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);bs.includes(o.toLowerCase())&&!ws.includes(r.toLowerCase())&&t.delete(r)}t.delete(is)}else ys.forEach(r=>{t.delete(r)});return t}i(ra,"normalizeIncomingRequestHeaders");var Ue=(0,ia.debug)("zuplo:runtime"),od=i(n=>{let e=n.findIndex(t=>t.name===jt.name);return e>-1?[...n.splice(e),jt]:[...n,jt]},"setupSystemNoVersion"),he=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;Ue("Gateway.constructor"),_e,this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(Ue("Gateway.initialize"),!n.#e){let s=await Un.init(r),a=e(),u={...a,corsPolicies:Hs(a.corsPolicies)},c=new n(u,t,s,o);n.#e=c}if(!n.#e)throw new Q("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){Ue("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new Q("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[xn,En,be];#o;setupRoutes=()=>{Ue("Gateway.setupRoutes");let e=this.routeData,t=od(e.versions),r=new Et(t);if(e.routes.length===0)return lo(r,this),bo(r,this),ho(r,this),Zs(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(Ws(r,this),Gs(r,this)),lo(r,this),bo(r,this),ho(r,this);for(let s of qe)s instanceof Ze&&s.registerRoutes(r,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new m(`Invalid state - No handler on route for path '${s.path}'`);let u=new pe({processors:this.#r,handler:a,gateway:this}),c=new ut(s);r.addRoute(c,u.execute)}),qs(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=i((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 Ue("An error occurred in the user's errorHandler",o),this.#i(e,t,o)}}#i(e,t,r){Ue("Gateway.internalErrorResponse");let o={};if(g.instance.isWorkingCopy){if(r instanceof L&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let s=Pe(r.cause);"stack"in s&&(s.stack=Ks(s.stack)),o={cause:s}}}return T.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t,r){let{requestId:o,rayId:s}=t;na(r);let a=ra({headers:e.headers,removeAllVendorHeadersExceptListed:g.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(rt,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let j=new Headers(u.headers);j.set(Vr,"true"),u=new Request(u,{headers:j,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(o,s,r,c,u),p=new URL(u.url),h=p.pathname,y=this.#n.lookup(u.method,h);if(!y)throw new Q(`Invalid state - no route match - should have been picked up by the not found handler, path: '${h}'`);let _=new Zn(e.headers),E=new re(u,{params:y.params}),C=new qn({logger:l,route:y.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:_}),Z=y.routeConfiguration.raw();oa.trace.getActiveSpan()?.setAttributes({"http.route":C.route.path??C.route.pathPattern,"cloud.region":C.incomingRequestProperties.colo,[_e.RoutePathPattern]:C.route.pathPattern,[_e.RouteOperationId]:Z.operationId,[_e.RouteTrace]:Z["x-zuplo-trace"],[_e.RouteSystem]:gt(p)?!0:void 0});let N=ye.initialize(C,E);if(y.routeConfiguration===yo&&Ft.value?.notFoundHandler!==void 0){let j=this.#n.lookupByPathOnly(h);N.pathOnlyMatches=j.map(q=>q.routeConfiguration).filter(q=>q instanceof ut)}try{if(ne.addLogger(C,d),g.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!gt(p):!p.pathname.startsWith("/__zuplo")){let P=await Ss(E,C);if(P instanceof Response)return P;{let D=ye.getContextExtensions(C);E=P,D.latestRequest=E}}gt(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:y.routeConfiguration.path});let j=y.executableHandler;id(j,y,u),Ue("Gateway.handleRequest - call user handler");let q=await j(E,C);if(Ue("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 B;if(q.headers.get(rt)===null&&!q.webSocket){let P=new Headers(q.headers);P.set(rt,o),B=new Response(q.body,{status:q.status,statusText:q.statusText,headers:P,cf:q.cf})}else B=q;return B}catch(j){return Ue("Gateway - error executing handler",j),j instanceof L?(l.error(j),d.warn(j)):d.error(j),await this.#i(E,C,j)}}};function id(n,e,t){if(Ue("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new m(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new m(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}i(id,"checkHandler");var sa=i(async(n,e,t)=>{let r=he.instance.routeData.policies,o=zt([n],r);if(o.length===0)throw new L(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy");var Zn=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Xr);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Qr)??void 0}get city(){return this.#e.get(Gr)??this.#e.get(ds)??void 0}get continent(){return this.#e.get(Wr)??this.#e.get(ps)??void 0}get country(){return this.#e.get(Jr)??this.#e.get(ms)??void 0}get latitude(){return this.#e.get(Yr)??this.#e.get(fs)??void 0}get longitude(){return this.#e.get(Kr)??this.#e.get(gs)??void 0}get colo(){return this.#e.get(eo)??void 0}get postalCode(){return this.#e.get(cs)??this.#e.get(to)??void 0}get metroCode(){return this.#e.get(us)??this.#e.get(no)??void 0}get region(){return this.#e.get(ss)??this.#e.get(ro)??void 0}get regionCode(){return this.#e.get(as)??this.#e.get(oo)??void 0}get timezone(){return this.#e.get(ls)??this.#e.get(io)??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}}},ft=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},ht=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},ye=class n{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let 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 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,r)=>{for(let o of this.#t)await o(e,t,r)};onResponseSending=async(e,t,r)=>{let o=e;for(let s of this.#n)o=await s(e,t,r);return o}},qn=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=s,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>sa(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=i(s=>{try{typeof t=="function"?t(s):t.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var Ce=class n{static{i(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,t){n.set(e,this.#t,t)}get(e){return n.get(e,this.#t)}static set(e,t,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)}};var sd=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function ad(n){return n.startsWith("__ZUPLO")||n.startsWith("ZUPLO_")?!sd.includes(n)&&!n.startsWith("ZUPLO_PUBLIC_"):!1}i(ad,"isRestrictedEnvVariableName");function ud(n){return!!n.startsWith("ZUPLO_")}i(ud,"isZuploReadableEnvVariableName");var Re=new Proxy({},{get(n,e){let t=String(e);switch(t){case"ZUPLO_ENVIRONMENT_TYPE":return g.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return g.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return g.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return g.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return g.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return g.instance.build.BUILD_ID}if(!(ad(t)&&!ud(t)))return g.instance.runtime[t]}});var aa=require("node:async_hooks");var ua={request:new aa.AsyncLocalStorage};var cd="Error initializing gateway. Check your configuration for errors or contact support.",ld="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",Fn=class{constructor(e,t,r,o,s,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=async(e,t,r)=>{let o=e.headers.get(rt)??e.headers.get(os)??crypto.randomUUID(),s=e.headers.get(ot),a={requestId:o,rayId:s};return ua.request.run(a,async()=>{g.initialize({build:this.buildEnvironment,runtime:t});try{await As(this.runtimeInit)}catch(c){this.handleError(c,ld,e)}return Es(i(async(c,l)=>{let d;try{d=await he.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,cd,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:g.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};var ya=et(ze());function dd(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="",s=t+1;s<n.length;){var a=n.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=n[s++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:o}),t=s;continue}if(r==="("){var u=1,c="",s=t+1;if(n[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<n.length;){if(n[s]==="\\"){c+=n[s++]+n[s++];continue}if(n[s]===")"){if(u--,u===0){s++;break}}else if(n[s]==="("&&(u++,n[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));c+=n[s++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(t));if(!c)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:c}),t=s;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}i(dd,"lexer");function Mo(n,e){e===void 0&&(e={});for(var t=dd(n),r=e.prefixes,o=r===void 0?"./":r,s="[^".concat(md(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=i(function(P){if(c<t.length&&t[c].type===P)return t[c++].value},"tryConsume"),p=i(function(P){var D=d(P);if(D!==void 0)return D;var z=t[c],W=z.type,S=z.index;throw new TypeError("Unexpected ".concat(W," at ").concat(S,", expected ").concat(P))},"mustConsume"),h=i(function(){for(var P="",D;D=d("CHAR")||d("ESCAPED_CHAR");)P+=D;return P},"consumeText");c<t.length;){var y=d("CHAR"),_=d("NAME"),E=d("PATTERN");if(_||E){var C=y||"";o.indexOf(C)===-1&&(l+=C,C=""),l&&(a.push(l),l=""),a.push({name:_||u++,prefix:C,suffix:"",pattern:E||s,modifier:d("MODIFIER")||""});continue}var Z=y||d("ESCAPED_CHAR");if(Z){l+=Z;continue}l&&(a.push(l),l="");var N=d("OPEN");if(N){var C=h(),j=d("NAME")||"",q=d("PATTERN")||"",B=h();p("CLOSE"),a.push({name:j||(q?u++:""),pattern:j&&!q?s:q,prefix:C,suffix:B,modifier:d("MODIFIER")||""});continue}p("END")}return a}i(Mo,"parse");function ca(n,e){return pd(Mo(n,e),e)}i(ca,"compile");function pd(n,e){e===void 0&&(e={});var t=gd(e),r=e.encode,o=r===void 0?function(c){return c}:r,s=e.validate,a=s===void 0?!0:s,u=n.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var h=c?c[p.name]:void 0,y=p.modifier==="?"||p.modifier==="*",_=p.modifier==="*"||p.modifier==="+";if(Array.isArray(h)){if(!_)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 E=0;E<h.length;E++){var C=o(h[E],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 Z=_?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(Z))}}return l}}i(pd,"tokensToFunction");function md(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(md,"escapeString");function gd(n){return n&&n.sensitive?"":"i"}i(gd,"flags");var ma=et(ze());var fd=(0,ma.debug)("zuplo:runtime"),Uo=new TextEncoder,la={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"},hd=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],It=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:o,region:s,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=r,this.service=o,this.region=s,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,t){let r=new Ho(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){fd("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,t),a=F.fetch(o,s);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")}},Ho=class{static{i(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:r,body:o,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:h,appendSessionToken:y,allHeaders:_,singleEncode:E}){if(t==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let C,Z;(!c||!l)&&([C,Z]=yd(this.url,this.headers)),this.service=c||C||"",this.region=l||Z||"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 N=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"),N.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&N.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(q=>_||!hd.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(`
|
|
57
|
-
`),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!N.has("X-Amz-Expires")&&N.set("X-Amz-Expires","86400"),N.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),N.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),N.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,"/");
|
|
53
|
+
`,pad:c,indent:c+d}:p={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let f=i(h=>{if(u.inlineCharacterLimit===void 0)return h;let A=h.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return A.length<=u.inlineCharacterLimit?A:h.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
|
|
54
|
+
`).replace(new RegExp(p.pad,"g"),c).replace(new RegExp(p.indent,"g"),c+d)},"expandWhiteSpace");if(r.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||_s(a))return String(a);if(a instanceof Date)return`new Date('${a.toISOString()}')`;if(l>o)return"...";if(Array.isArray(a)){if(a.length===0)return"[]";r.push(a);let h="["+p.newline+a.map((A,P)=>{let C=a.length-1===P?p.newline:","+p.newlineOrSpace,H=s(A,u,c+d,l+1);return u.transform&&(H=u.transform(a,P,H)),p.indent+H+C}).join("")+p.pad+"]";return r.pop(),f(h)}if(it(a)){let h=Ls(a);if(u.filter&&(h=h.filter(P=>u.filter?.(a,P))),h.length===0)return"{}";r.push(a);let A="{"+p.newline+h.map((P,C)=>{let H=h.length-1===C?p.newline:","+p.newlineOrSpace,N=typeof P=="symbol",B=!N&&/^[a-z$_][$\w]*$/i.test(P),Z=N||B?P:s(P,u,"",l+1),$=s(a[P],u,c+d,l+1);return u.transform&&($=u.transform(a,P,$)),p.indent+String(Z)+": "+$+H}).join("")+p.pad+"}";return r.pop(),f(A)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,h=>h===`
|
|
55
|
+
`?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}i(Cn,"stringifyObject");function Ye(n){return n.map(e=>Ee(e))}i(Ye,"makeErrorsSerializable");function Rt(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:je(Ee(e))}i(Rt,"extractBestMessage");function Ks(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(Gt(t))if(t.stack)e.push(t.stack);else{let r=Cn(Ee(t));e.push(r)}else if(typeof t=="object"){let r=Cn(t);e.push(r)}else{let r=xo(t);e.push(r)}}),e.join(`
|
|
56
|
+
`)}i(Ks,"messagesToMultilineText");function je(n){return typeof n=="string"?n:JSON.stringify(n)}i(je,"stringifyNonString");function xo(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"?co(n):"unknown"}i(xo,"stringifyNonStringToText");var An=require("jose");async function Ie(n,e,t){for(let r=0;r<=n.retries;r++){let o=F.fetch(e,t);if(r===n.retries)return o;let s=await o;if(s.status<500&&s.status!==429)return s;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,r)))}throw new m("An unknown error occurred, ensure retries is not negative")}i(Ie,"fetchRetry");async function De({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=n;return await new An.SignJWT(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(De,"getTokenFromGcpServiceAccount");async function Ys(n,e,t){return Xs(n,{token:e,returnSecureToken:!0},t)}i(Ys,"exchangeFirebaseJwtForIdToken");async function _n(n,e,t){return Xs(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(_n,"exchangeGgpJwtForIdToken");async function Xs(n,e,t){let r=await Ie(t,n,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let s;try{let a=await r.text(),u=JSON.parse(a);s={cause:u.error??u}}catch{}throw new L({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(Xs,"fetchToken");var ve=class n{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),r=await(0,An.importPKCS8)(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}};var Ln=class extends me{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Yt(this.options)}},td="https://logging.googleapis.com/v2/entries:write?alt=json",To={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Yt=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=g.instance.loggingEnvironmentType,this.#i=g.instance.loggingEnvironmentStage,this.#r=g.instance.deploymentName,y("logging.google-cloud")}#e;#t;#n;#r;#o;#i;async init(){this.#t=await ve.init(this.#e)}log(e,t){if(!this.#t)throw new Y("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:Ye(e.messages)},o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:To[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&&(s.labels.rayId=e.rayId);let a=Rt(r.allMessages);s.jsonPayload={...r,message:a},this.batcher.enqueue(s),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await ve.init(this.#e));let t=await De({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await F.fetch(td,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});r.ok||console.error(r.status,r.statusText,await r.text())};batcher=new Q("google-log-transport",1,this.dispatchFunction)};var kn="gcp";function Nn(n){let e={allMessages:Ye(n.messages)},t="zuplo-production",r=Rt(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:To[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}i(Nn,"gcpLogFormat");var Xt=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===kn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Nn(e)])}else this.#e.log(JSON.stringify(e))}};var Mn=class extends me{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new Qt(this.options)}},vo="__ddtags",So="__ddattr",Oo=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),nd=i(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(Oo(r)):t.push(`${Oo(r)}:${Oo(o.toString())}`)}),t.join(",")},"formatTags"),Qt=class{static{i(this,"DataDogTransport")}constructor(e){y("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=g.instance.loggingEnvironmentType,this.#o=g.instance.loggingEnvironmentStage,this.#n=g.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[vo];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(h=>h[vo]!==void 0);a>-1&&(Object.assign(r,s[a][vo]),s.splice(a,1));let u={},c=t.custom[So];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(h=>h[So]!==void 0);l>-1&&(Object.assign(u,s[l][So]),s.splice(l,1));let d=Ye(s),f={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:Rt(d),service:e.loggingId,ddtags:nd(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(f,u),this.batcher.enqueue(f),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await F.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new Q("data-dog-transport",10,this.dispatchFunction)};var en=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===kn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Nn(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 rd=i(({url:n,remoteLogToken:e,loggingId:t,sendOnlyErrors:r})=>async o=>{let s;if(r===!0?s=o.filter(a=>a.level==="error"):s=o,s.length!==0)try{await F.fetch(`${n}/publish/${t}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:s.map(a=>({...a,messages:Ye(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":g.instance.systemUserAgent,"zp-dn":g.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Dn,Un=class{static{i(this,"RemoteLogTransport")}constructor(e){Dn||(Dn=new Q("remote-log-transport",1,rd(e)))}log(e,t){Dn.enqueue(e),t.waitUntil(Dn.waitUntilFlushed())}};var od={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},Qs=i((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:od[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var id=i(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let s=Qs(t,r);try{await F.fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":g.instance.systemUserAgent,"zp-dn":g.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Hn,Zn=class{static{i(this,"UnifiedLogTransport")}constructor(e){Hn||(Hn=new Q("unified-log-transport",1,id(e)))}async log(e,t){Hn.enqueue(e),t.waitUntil(Hn.waitUntilFlushed())}};var Co=(0,ea.debug)("zuplo:logging"),qn=class n{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(g.instance,e),r=await n.setupUserCoreLogger(g.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;Co("Gateway.setupSystemCoreLogger");let o=[],s=t.getService($t);return s?o.push(new en(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new Xt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Zn({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 Jt(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){Co("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=t.getService($t);if(a&&a.captureUserLogs===!0?r.push(new en(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new Xt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new Un({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:!e.isWorkingCopy})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new Yt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME})),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new Qt({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return Fe.forEach(u=>{u instanceof me&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new Jt(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,t,r,o,s){Co("Gateway.createRequestLoggers");let a=new On(r,o,s),u=new Kt(e,t,this.systemCoreLogger,a);return{userRequestLogger:new Kt(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var ut=class{static{i(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};var Ao=class{static{i(this,"RouterEntry")}constructor(e,t,r,o){this.fullPath=e,this.urlPattern=t,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},Pt=class{static{i(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},_o=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}},Et=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof ut||e instanceof ue))throw new Y("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(s=>s.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let s=new URLPattern({pathname:o}),a=new Ao(o,s,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new _o(`addRoute-error: Invalid path '${o}'. '${s.message}'`,{cause:s})}}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 s=r[o],u=s.urlPattern.exec({pathname:t});if(u!==null)return new Pt(s.config,s.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 Pt(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var Lo;function ta(n){Lo=n}i(ta,"setGlobalZuploEventContext");function Fn(){if(Lo===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return Lo}i(Fn,"getGlobalZuploEventContext");function na({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);ys.includes(o.toLowerCase())&&!bs.includes(r.toLowerCase())&&t.delete(r)}t.delete(os)}else hs.forEach(r=>{t.delete(r)});return t}i(na,"normalizeIncomingRequestHeaders");var Ue=(0,oa.debug)("zuplo:runtime"),sd=i(n=>{let e=n.findIndex(t=>t.name===Vt.name);return e>-1?[...n.splice(e),Vt]:[...n,Vt]},"setupSystemNoVersion"),be=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;Ue("Gateway.constructor"),_e,this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(Ue("Gateway.initialize"),!n.#e){let s=await qn.init(r),a=e(),u={...a,corsPolicies:Us(a.corsPolicies)},c=new n(u,t,s,o);n.#e=c}if(!n.#e)throw new Y("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){Ue("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new Y("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[Sn,Tn,Re];#o;setupRoutes=()=>{Ue("Gateway.setupRoutes");let e=this.routeData,t=sd(e.versions),r=new Et(t);if(e.routes.length===0)return uo(r,this),ho(r,this),go(r,this),Hs(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(Gs(r,this),Vs(r,this)),uo(r,this),ho(r,this),go(r,this);for(let s of Fe)s instanceof qe&&s.registerRoutes(r,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new m(`Invalid state - No handler on route for path '${s.path}'`);let u=new pe({processors:this.#r,handler:a,gateway:this}),c=new ut(s);r.addRoute(c,u.execute)}),Zs(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=i((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 Ue("An error occurred in the user's errorHandler",o),this.#i(e,t,o)}}#i(e,t,r){Ue("Gateway.internalErrorResponse");let o={};if(g.instance.isWorkingCopy){if(r instanceof L&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let s=Ee(r.cause);"stack"in s&&(s.stack=Js(s.stack)),o={cause:s}}}return x.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t,r){let{requestId:o,rayId:s}=t;ta(r);let a=na({headers:e.headers,removeAllVendorHeadersExceptListed:g.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(rt,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let B=new Headers(u.headers);B.set(Br,"true"),u=new Request(u,{headers:B,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(o,s,r,c,u),p=new URL(u.url),f=p.pathname,h=this.#n.lookup(u.method,f);if(!h)throw new Y(`Invalid state - no route match - should have been picked up by the not found handler, path: '${f}'`);let A=new $n(e.headers),P=new re(u,{params:h.params}),C=new jn({logger:l,route:h.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:A}),H=h.routeConfiguration.raw();ra.trace.getActiveSpan()?.setAttributes({"http.route":C.route.path??C.route.pathPattern,"cloud.region":C.incomingRequestProperties.colo,[_e.RoutePathPattern]:C.route.pathPattern,[_e.RouteOperationId]:H.operationId,[_e.RouteTrace]:H["x-zuplo-trace"],[_e.RouteSystem]:gt(p)?!0:void 0});let N=we.initialize(C,P);if(h.routeConfiguration===fo&&Bt.value?.notFoundHandler!==void 0){let B=this.#n.lookupByPathOnly(f);N.pathOnlyMatches=B.map(Z=>Z.routeConfiguration).filter(Z=>Z instanceof ut)}try{if(ee.addLogger(C,d),g.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!gt(p):!p.pathname.startsWith("/__zuplo")){let I=await vs(P,C);if(I instanceof Response)return I;{let U=we.getContextExtensions(C);P=I,U.latestRequest=P}}gt(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:h.routeConfiguration.path});let B=h.executableHandler;ad(B,h,u),Ue("Gateway.handleRequest - call user handler");let Z=await B(P,C);if(Ue("Gateway.handleRequest - user handler"),!(Z instanceof Response))throw new L(`Invalid Response type from the request handler: ${typeof Z}`);if(Z.bodyUsed)throw new L("The response object has already been used. Return a new response instead.");let $;if(Z.headers.get(rt)===null&&!Z.webSocket){let I=new Headers(Z.headers);I.set(rt,o),$=new Response(Z.body,{status:Z.status,statusText:Z.statusText,headers:I,cf:Z.cf})}else $=Z;return $}catch(B){return Ue("Gateway - error executing handler",B),B instanceof L?(l.error(B),d.warn(B)):d.error(B),await this.#i(P,C,B)}}};function ad(n,e,t){if(Ue("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new m(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new m(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}i(ad,"checkHandler");var ia=i(async(n,e,t)=>{let r=be.instance.routeData.policies,o=Wt([n],r);if(o.length===0)throw new L(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy");var $n=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Kr);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Yr)??void 0}get city(){return this.#e.get(zr)??this.#e.get(ls)??void 0}get continent(){return this.#e.get(Vr)??this.#e.get(ds)??void 0}get country(){return this.#e.get(Gr)??this.#e.get(ps)??void 0}get latitude(){return this.#e.get(Jr)??this.#e.get(gs)??void 0}get longitude(){return this.#e.get(Wr)??this.#e.get(ms)??void 0}get colo(){return this.#e.get(Xr)??void 0}get postalCode(){return this.#e.get(us)??this.#e.get(Qr)??void 0}get metroCode(){return this.#e.get(as)??this.#e.get(eo)??void 0}get region(){return this.#e.get(is)??this.#e.get(to)??void 0}get regionCode(){return this.#e.get(ss)??this.#e.get(no)??void 0}get timezone(){return this.#e.get(cs)??this.#e.get(ro)??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}}},ft=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},ht=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},we=class n{static{i(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 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,r)=>{for(let o of this.#t)await o(e,t,r)};onResponseSending=async(e,t,r)=>{let o=e;for(let s of this.#n)o=await s(e,t,r);return o}},jn=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=s,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>ia(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{we.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{we.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=i(s=>{try{typeof t=="function"?t(s):t.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var he=class n{static{i(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,t){n.set(e,this.#t,t)}get(e){return n.get(e,this.#t)}static set(e,t,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)}};var ud=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function cd(n){return n.startsWith("__ZUPLO")||n.startsWith("ZUPLO_")?!ud.includes(n)&&!n.startsWith("ZUPLO_PUBLIC_"):!1}i(cd,"isRestrictedEnvVariableName");function ld(n){return!!n.startsWith("ZUPLO_")}i(ld,"isZuploReadableEnvVariableName");var Pe=new Proxy({},{get(n,e){let t=String(e);switch(t){case"ZUPLO_ENVIRONMENT_TYPE":return g.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return g.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return g.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return g.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return g.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return g.instance.build.BUILD_ID}if(!(cd(t)&&!ld(t)))return g.instance.runtime[t]}});var sa=require("node:async_hooks");var aa={request:new sa.AsyncLocalStorage};var dd="Error initializing gateway. Check your configuration for errors or contact support.",pd="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",Bn=class{constructor(e,t,r,o,s,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=async(e,t,r)=>{let o=e.headers.get(rt)??e.headers.get(rs)??crypto.randomUUID(),s=e.headers.get(ot),a={requestId:o,rayId:s};return aa.request.run(a,async()=>{g.initialize({build:this.buildEnvironment,runtime:t});try{await Cs(this.runtimeInit)}catch(c){this.handleError(c,pd,e)}return Ps(i(async(c,l)=>{let d;try{d=await be.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,dd,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:g.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};var ha=Be(Ze());function md(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="",s=t+1;s<n.length;){var a=n.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=n[s++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:o}),t=s;continue}if(r==="("){var u=1,c="",s=t+1;if(n[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<n.length;){if(n[s]==="\\"){c+=n[s++]+n[s++];continue}if(n[s]===")"){if(u--,u===0){s++;break}}else if(n[s]==="("&&(u++,n[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));c+=n[s++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(t));if(!c)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:c}),t=s;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}i(md,"lexer");function ko(n,e){e===void 0&&(e={});for(var t=md(n),r=e.prefixes,o=r===void 0?"./":r,s="[^".concat(fd(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=i(function(I){if(c<t.length&&t[c].type===I)return t[c++].value},"tryConsume"),p=i(function(I){var U=d(I);if(U!==void 0)return U;var G=t[c],W=G.type,S=G.index;throw new TypeError("Unexpected ".concat(W," at ").concat(S,", expected ").concat(I))},"mustConsume"),f=i(function(){for(var I="",U;U=d("CHAR")||d("ESCAPED_CHAR");)I+=U;return I},"consumeText");c<t.length;){var h=d("CHAR"),A=d("NAME"),P=d("PATTERN");if(A||P){var C=h||"";o.indexOf(C)===-1&&(l+=C,C=""),l&&(a.push(l),l=""),a.push({name:A||u++,prefix:C,suffix:"",pattern:P||s,modifier:d("MODIFIER")||""});continue}var H=h||d("ESCAPED_CHAR");if(H){l+=H;continue}l&&(a.push(l),l="");var N=d("OPEN");if(N){var C=f(),B=d("NAME")||"",Z=d("PATTERN")||"",$=f();p("CLOSE"),a.push({name:B||(Z?u++:""),pattern:B&&!Z?s:Z,prefix:C,suffix:$,modifier:d("MODIFIER")||""});continue}p("END")}return a}i(ko,"parse");function ua(n,e){return gd(ko(n,e),e)}i(ua,"compile");function gd(n,e){e===void 0&&(e={});var t=hd(e),r=e.encode,o=r===void 0?function(c){return c}:r,s=e.validate,a=s===void 0?!0:s,u=n.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var f=c?c[p.name]:void 0,h=p.modifier==="?"||p.modifier==="*",A=p.modifier==="*"||p.modifier==="+";if(Array.isArray(f)){if(!A)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(f.length===0){if(h)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var P=0;P<f.length;P++){var C=o(f[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 f=="string"||typeof f=="number"){var C=o(String(f),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(!h){var H=A?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(H))}}return l}}i(gd,"tokensToFunction");function fd(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(fd,"escapeString");function hd(n){return n&&n.sensitive?"":"i"}i(hd,"flags");var pa=Be(Ze());var yd=(0,pa.debug)("zuplo:runtime"),Mo=new TextEncoder,ca={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"},bd=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],It=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:o,region:s,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=r,this.service=o,this.region=s,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,t){let r=new Do(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){yd("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,t),a=F.fetch(o,s);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")}},Do=class{static{i(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:r,body:o,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:f,appendSessionToken:h,allHeaders:A,singleEncode:P}){if(t==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let C,H;(!c||!l)&&([C,H]=wd(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=f,this.appendSessionToken=h||this.service==="iotdevicegateway",this.headers.delete("Host");let N=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"),N.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&N.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(Z=>A||!bd.includes(Z)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(Z=>Z+":"+(Z==="host"?this.url.host:(this.headers.get(Z)||"").replace(/\s+/g," "))).join(`
|
|
57
|
+
`),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!N.has("X-Amz-Expires")&&N.set("X-Amz-Expires","86400"),N.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),N.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),N.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=da(this.encodedPath);let B=new Set;this.encodedSearch=[...this.url.searchParams].filter(([Z])=>{if(!Z)return!1;if(this.service==="s3"){if(B.has(Z))return!1;B.add(Z)}return!0}).map(Z=>Z.map($=>da(encodeURIComponent($)))).sort(([Z,$],[I,U])=>Z<I?-1:Z>I?1:$<U?-1:$>U?1:0).map(Z=>Z.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(),r=this.cache.get(t);if(!r){let o=await tn("AWS4"+this.secretAccessKey,e),s=await tn(o,this.region),a=await tn(s,this.service);r=await tn(a,"aws4_request"),this.cache.set(t,r)}return No(await tn(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,No(await la(await this.canonicalString()))].join(`
|
|
58
58
|
`)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
|
|
59
59
|
`,this.signedHeaders,await this.hexBodyHash()].join(`
|
|
60
|
-
`)}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=Do(await da(this.body||""))}return e}};async function Xt(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?Uo.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,Uo.encode(e))}i(Xt,"hmac");async function da(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?Uo.encode(n):n)}i(da,"hash");function Do(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}i(Do,"buf2hex");function pa(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(pa,"encodeRfc3986");function yd(n,e){let{hostname:t,pathname:r}=n,o=t.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[s,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",s="s3";else if(s==="iot")t.startsWith("iot.")?s="execute-api":t.startsWith("data.jobs.iot.")?s="iot-jobs-data":s=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(s==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?s="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(s="autoscaling-plans")}else a==null&&s.startsWith("s3-")?(a=s.slice(3).replace(/^fips-|^external-1/,""),s="s3"):s.endsWith("-fips")?s=s.slice(0,-5):a&&/-\d$/.test(s)&&!/-\d$/.test(a)&&([s,a]=[a,s]);return s in la?[la[s],a]:[s,a]}i(yd,"guessServiceRegion");function bd(n){return n>64&&n<91?n-65:n>96&&n<123?n-71:n>47&&n<58?n+4:n===43?62:n===47?63:0}i(bd,"b64ToUint6");function ga(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,s=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=bd(t.charCodeAt(d))<<6*(3-u),u===3||r-d===1){for(a=0;a<3&&l<o;)s[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return s}i(ga,"base64Decode");function $n(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}i($n,"uint6ToB64");function fa(n){let e=2,t="",r=n.length,o=0;for(let s=0;s<r;s++)e=s%3,o|=n[s]<<(16>>>e&24),(e===2||n.length-s===1)&&(t+=String.fromCodePoint($n(o>>>18&63),$n(o>>>12&63),$n(o>>>6&63),$n(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}i(fa,"base64Encode");function xt(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}i(xt,"numberToString");function wd(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=xt(Math.floor(t/60)),s=xt(t%60);return`${r}${o}${s}`}i(wd,"getCLFOffset");function Zo(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=xt(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),s=xt(n.getHours()),a=xt(n.getMinutes()),u=xt(n.getSeconds()),c=wd(n);return`${t}/${r}/${o}:${s}:${a}:${u} ${c}`}i(Zo,"toCLFDate");var ha=(0,ya.debug)("zuplo:runtime"),Rd="X-Amzn-Trace-Id",Pd="x-amzn-errortype",ba=[],Ed=i(async(n,e,t)=>{let r=t;for await(let o of ba)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),ve=class extends L{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(Rd)??void 0,this.errorType=t.get(Pd)??void 0}},wa={addSendingAwsLambdaEventHook:n=>{ba.push(n)}};async function Ra(n,e){f("handler.aws-lambda");let{accessKeyId:t,secretAccessKey:r,region:o,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!t)throw new m("awsAccessKeyId is not set in the handler options");if(!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(!s)throw new m("functionName is not set in the handler options");let l=new It({accessKeyId:t,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(ha(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,h]=await vd(n,{binaryMediaTypes:c}),{options:y}=e.route.handler,_;y&&typeof y=="object"&&"payloadFormatVersion"in y&&y.payloadFormatVersion==="2.0"?_=Td(n,e):_=await xd(n,e,{useAwsResourcePathStyle:u}),ha("Calling onSendingAwsLambdaEvent hook");let E=await Ed(n,e,_);E.body=p,E.isBase64Encoded=h;let C=await l.fetch(d,{body:JSON.stringify(E)});try{return Id(C)}catch(Z){if(Z instanceof ve){let N=y&&typeof y=="object"&&"returnAmazonTraceIdHeader"in y&&y.returnAmazonTraceIdHeader&&Z.traceId?{AMZN_TRACE_ID_HEADER:Z.traceId}:void 0;return T.internalServerError(n,e,void 0,N)}throw Z}}i(Ra,"awsLambdaHandler");async function Id(n){let e;try{e=await n.json()}catch{throw new ve("Lambda response did not contain valid JSON",n.headers)}if(n.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new ve(e.message,n.headers):new ve(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new ve(e.errorMessage,n.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:n.status,headers:{"content-type":"application/json"}});let t=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new ve(`Response headers must be an object. Received ${typeof e.headers}`,n.headers);for(let[o,s]of Object.entries(e.headers))t.set(o,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new ve(`Response cookies must be an array. Received ${typeof e.cookies}`,n.headers);t.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new ve(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,n.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new ve("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new ve("Response was set to base64 encoded but body was not a string",n.headers);r=ga(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 ve(`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})}i(Id,"getResponse");async function xd(n,e,{useAwsResourcePathStyle:t}){let r={},o={};n.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let s=n.query,a={};for(let[l,d]of Object.entries(s))a[l]=[d];let u=new URL(n.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:n.method,headers:r,multiValueHeaders:o,queryStringParameters:s,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:n.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:n.headers.get("CF-Connecting-IP"),user:null,userAgent:n.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:Zo(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Od(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}i(xd,"buildEventVersion1");function Td(n,e){let t={};n.headers.forEach((s,a)=>{t[a]=s});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:Zo(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}i(Td,"buildEventVersion2");async function vd(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&&Sd(e,o)){let s=await n.arrayBuffer();t=fa(new Uint8Array(s)),r=!0}else t=await n.clone().text();return[t,r]}i(vd,"getBodyResult");function Sd(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}i(Sd,"matchesContentType");function Od(n,e=!1){if(!e)return n;let t=Mo(n),r=ca(n),o={};return t.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),r(o)}i(Od,"getResourcePath");var Cd=[502,503,504];async function Tt(n,e){if(Cd.includes(n.status)){let t=ne.getLogger(e),o=await n.clone().text(),s={};for(let[a,u]of n.headers)s[a]=u;t.warn(`BadGatewayResponse ${n.status}`,{status:n.status,statusText:n.statusText,body:o,headers:s})}}i(Tt,"logBadGatewayResponses");var qo;function Ye(n){if(qo===void 0){let t=g.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),qo=t}return n.log[qo]}i(Ye,"getHandlerUserLogFunction");async function Pa(n,e){f("handler.open-api");let t=g.instance.build.BUILD_ID,{buildAssetsUrl:r}=g.instance,o=e.route.handler.options,{openApiFilePath:s}=o;if(!s)throw new m("Open API Spec Handler must have 'openApiFilePath' specified");let a=Ad(s);if(!a.isValid)throw new m(a.error);let u;g.instance.isLocalDevelopment?u=`${r}/${s.substring(1)}`:u=`${r}/${t}${s.substring(1)}`;let c=await F.fetch(u,{method:n.method,body:n.body,headers:n.headers});if(c.status!==200)return T.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 Tt(l,e),l}i(Pa,"openApiSpecHandler");var Ad=i(n=>n.startsWith("./")?n.startsWith("./config")?n.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function Ea(n,e){f("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}})}i(Ea,"redirectHandler");function _d(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}`}i(_d,"join");async function Ia(n,e){f("handler.url-forward");let t=Ye(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 s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(n.url),u=r.__rewriteFunction(n,s),c=_d(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`),Tt(p,e),p}i(Ia,"urlForwardHandler");var Ld=i((n,e)=>{let t=new URL(n),r=new URL(e);for(let[o,s]of r.searchParams.entries())t.searchParams.append(o,s);return t.toString()},"addQuery");async function xa(n,e){f("handler.url-rewrite");let t=Ye(e),r=e.route.handler.options,o=r.forwardSearch!==!1,s=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?Ld(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:s?"follow":"manual"}),p=Date.now()-l;return t(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),Tt(d,e),d}i(xa,"urlRewriteHandler");async function Ta(n,e){f("handler.websocket");let t=e.route.handler.options,r=Ye(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 T.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new m("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),u=Date.now();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})}i(Ta,"webSocketHandler");var Fo=i((n,e)=>n.map((r,o)=>{let s;if(typeof r.module=="object"&&(s=r.module[r.export]),!s||typeof s!="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 s}),"getWebSocketPolicyFunctions"),va=i(async(n,e,t,r,o,s)=>{let a=n.data;if(s&&s.length>0){let u=[...s];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,t,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function Sa(n,e,t,r,o){n.addEventListener("close",()=>{e.close()}),n.addEventListener("error",s=>{r.log.error("WebSocket error: ",s),e.send(JSON.stringify(s))}),n.addEventListener("message",s=>{try{let u=i(async c=>{let l=await va(c,n,e,t,r,o);l!==void 0&&e.send(l)},"innerPipeline")(s).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}i(Sa,"wireUpListeners");async function Oa(n,e){f("handler.websocket-pipeline");let t=e.route.handler.options,r=Ye(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 T.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new m("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),u=Date.now();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(),Z=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${C}'`;throw new Error(Z)}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 _=t.policies&&t.policies.inbound?Fo(t.policies.inbound,"inbound"):[],E=t.policies&&t.policies.outbound?Fo(t.policies.outbound,"outbound"):[];return Sa(p,y,n,e,_),Sa(y,p,n,e,E),new Response(null,{status:101,webSocket:d})}i(Oa,"webSocketPipelineHandler");var jn=class extends me{constructor(t){super();this.options=t}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new $o(this.options)}},$o=class{static{i(this,"DynaTraceTransport")}constructor(e){f("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#r=g.instance.loggingEnvironmentType,this.#o=g.instance.loggingEnvironmentStage,this.#n=g.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:$e(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=>{e.length!==0&&await F.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new X("dyna-trace-log-transport",10,this.#i)};var Bn=class extends me{constructor(t){super();this.options=t}static{i(this,"LokiLoggingPlugin")}getTransport(){return new Bo(this.options)}},jo=class{static{i(this,"LokiStream")}constructor(e,t,r,o,s,a){this.level=e,this.environment=t,this.environmentType=r,this.environmentStage=o,this.requestId=a,this.job=s}job;level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function kd(n,e){return btoa(`${n}:${e}`)}i(kd,"createBasicDigest");var Bo=class{static{i(this,"LokiTransport")}constructor(e){f("logging.loki"),this.#n=e.url,this.#r=kd(e.username,e.password),this.#i=g.instance.loggingEnvironmentType,this.#s=g.instance.loggingEnvironmentStage,this.#o=g.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 jo(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(o=>{let s={stream:r,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:$e(Pe(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(s)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=e=>{let t={streams:[]};return e.forEach(r=>{let o=t.streams.find(s=>s.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:r.atomicCounter}]:[r.nanoSecondEpoch,r.message])}),t};#u=async e=>{if(e.length===0)return;let t=this.#a(e);await F.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}})};batcher=new X("loki-log-transport",10,this.#u)};var zn=class extends me{constructor(t){super();this.options=t}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new zo(this.options)}},zo=class{static{i(this,"SumoLogicTransport")}constructor(e){f("logging.sumologic"),this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=g.instance.loggingEnvironmentType,this.#r=g.instance.loggingEnvironmentStage,this.#t=g.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:$e(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(`
|
|
61
|
-
`),r=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&r.set("X-Sumo-Name",this.#i),this.#o&&r.set("X-Sumo-Category",this.#o),await F.fetch(this.#e,{method:"POST",body:t,headers:r})};batcher=new
|
|
62
|
-
`),r=await F.fetch(this.#e,{method:"POST",body:t,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new
|
|
60
|
+
`)}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=No(await la(this.body||""))}return e}};async function tn(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?Mo.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,Mo.encode(e))}i(tn,"hmac");async function la(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?Mo.encode(n):n)}i(la,"hash");function No(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}i(No,"buf2hex");function da(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(da,"encodeRfc3986");function wd(n,e){let{hostname:t,pathname:r}=n,o=t.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[s,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",s="s3";else if(s==="iot")t.startsWith("iot.")?s="execute-api":t.startsWith("data.jobs.iot.")?s="iot-jobs-data":s=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(s==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?s="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(s="autoscaling-plans")}else a==null&&s.startsWith("s3-")?(a=s.slice(3).replace(/^fips-|^external-1/,""),s="s3"):s.endsWith("-fips")?s=s.slice(0,-5):a&&/-\d$/.test(s)&&!/-\d$/.test(a)&&([s,a]=[a,s]);return s in ca?[ca[s],a]:[s,a]}i(wd,"guessServiceRegion");function Rd(n){return n>64&&n<91?n-65:n>96&&n<123?n-71:n>47&&n<58?n+4:n===43?62:n===47?63:0}i(Rd,"b64ToUint6");function ma(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,s=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=Rd(t.charCodeAt(d))<<6*(3-u),u===3||r-d===1){for(a=0;a<3&&l<o;)s[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return s}i(ma,"base64Decode");function zn(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}i(zn,"uint6ToB64");function ga(n){let e=2,t="",r=n.length,o=0;for(let s=0;s<r;s++)e=s%3,o|=n[s]<<(16>>>e&24),(e===2||n.length-s===1)&&(t+=String.fromCodePoint(zn(o>>>18&63),zn(o>>>12&63),zn(o>>>6&63),zn(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}i(ga,"base64Encode");function xt(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}i(xt,"numberToString");function Pd(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=xt(Math.floor(t/60)),s=xt(t%60);return`${r}${o}${s}`}i(Pd,"getCLFOffset");function Uo(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=xt(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),s=xt(n.getHours()),a=xt(n.getMinutes()),u=xt(n.getSeconds()),c=Pd(n);return`${t}/${r}/${o}:${s}:${a}:${u} ${c}`}i(Uo,"toCLFDate");var fa=(0,ha.debug)("zuplo:runtime"),Ed="X-Amzn-Trace-Id",Id="x-amzn-errortype",ya=[],xd=i(async(n,e,t)=>{let r=t;for await(let o of ya)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),Se=class extends L{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(Ed)??void 0,this.errorType=t.get(Id)??void 0}},ba={addSendingAwsLambdaEventHook:n=>{ya.push(n)}};async function wa(n,e){y("handler.aws-lambda");let{accessKeyId:t,secretAccessKey:r,region:o,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!t)throw new m("awsAccessKeyId is not set in the handler options");if(!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(!s)throw new m("functionName is not set in the handler options");let l=new It({accessKeyId:t,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(fa(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,f]=await Od(n,{binaryMediaTypes:c}),{options:h}=e.route.handler,A;h&&typeof h=="object"&&"payloadFormatVersion"in h&&h.payloadFormatVersion==="2.0"?A=Sd(n,e):A=await vd(n,e,{useAwsResourcePathStyle:u}),fa("Calling onSendingAwsLambdaEvent hook");let P=await xd(n,e,A);P.body=p,P.isBase64Encoded=f;let C=await l.fetch(d,{body:JSON.stringify(P)});try{return Td(C)}catch(H){if(H instanceof Se){let N=h&&typeof h=="object"&&"returnAmazonTraceIdHeader"in h&&h.returnAmazonTraceIdHeader&&H.traceId?{AMZN_TRACE_ID_HEADER:H.traceId}:void 0;return x.internalServerError(n,e,void 0,N)}throw H}}i(wa,"awsLambdaHandler");async function Td(n){let e;try{e=await n.json()}catch{throw new Se("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 Se(e.message,n.headers):new Se(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new Se(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 Se(`Response headers must be an object. Received ${typeof e.headers}`,n.headers);for(let[o,s]of Object.entries(e.headers))t.set(o,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new Se(`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 Se(`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 Se("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new Se("Response was set to base64 encoded but body was not a string",n.headers);r=ma(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 Se(`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})}i(Td,"getResponse");async function vd(n,e,{useAwsResourcePathStyle:t}){let r={},o={};n.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let s=n.query,a={};for(let[l,d]of Object.entries(s))a[l]=[d];let u=new URL(n.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:n.method,headers:r,multiValueHeaders:o,queryStringParameters:s,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:n.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:n.headers.get("CF-Connecting-IP"),user:null,userAgent:n.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:Uo(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Ad(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}i(vd,"buildEventVersion1");function Sd(n,e){let t={};n.headers.forEach((s,a)=>{t[a]=s});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:Uo(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}i(Sd,"buildEventVersion2");async function Od(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&&Cd(e,o)){let s=await n.arrayBuffer();t=ga(new Uint8Array(s)),r=!0}else t=await n.clone().text();return[t,r]}i(Od,"getBodyResult");function Cd(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}i(Cd,"matchesContentType");function Ad(n,e=!1){if(!e)return n;let t=ko(n),r=ua(n),o={};return t.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),r(o)}i(Ad,"getResourcePath");var _d=[502,503,504];async function Tt(n,e){if(_d.includes(n.status)){let t=ee.getLogger(e),o=await n.clone().text(),s={};for(let[a,u]of n.headers)s[a]=u;t.warn(`BadGatewayResponse ${n.status}`,{status:n.status,statusText:n.statusText,body:o,headers:s})}}i(Tt,"logBadGatewayResponses");var Ho;function Xe(n){if(Ho===void 0){let t=g.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),Ho=t}return n.log[Ho]}i(Xe,"getHandlerUserLogFunction");async function Ra(n,e){y("handler.open-api");let t=g.instance.build.BUILD_ID,{buildAssetsUrl:r}=g.instance,o=e.route.handler.options,{openApiFilePath:s}=o;if(!s)throw new m("Open API Spec Handler must have 'openApiFilePath' specified");let a=Ld(s);if(!a.isValid)throw new m(a.error);let u;g.instance.isLocalDevelopment?u=`${r}/${s.substring(1)}`:u=`${r}/${t}${s.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 Tt(l,e),l}i(Ra,"openApiSpecHandler");var Ld=i(n=>n.startsWith("./")?n.startsWith("./config")?n.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function Pa(n,e){y("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}})}i(Pa,"redirectHandler");function kd(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}`}i(kd,"join");async function Ea(n,e){y("handler.url-forward");let t=Xe(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 s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(n.url),u=r.__rewriteFunction(n,s),c=kd(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}),f=Date.now()-d;return t(`URL Forward received response ${p.status} - ${p.statusText} in ${f}ms`),Tt(p,e),p}i(Ea,"urlForwardHandler");var Nd=i((n,e)=>{let t=new URL(n),r=new URL(e);for(let[o,s]of r.searchParams.entries())t.searchParams.append(o,s);return t.toString()},"addQuery");async function Ia(n,e){y("handler.url-rewrite");let t=Xe(e),r=e.route.handler.options,o=r.forwardSearch!==!1,s=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?Nd(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:s?"follow":"manual"}),p=Date.now()-l;return t(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),Tt(d,e),d}i(Ia,"urlRewriteHandler");async function xa(n,e){y("handler.websocket");let t=e.route.handler.options,r=Xe(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 s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),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})}i(xa,"webSocketHandler");var Zo=i((n,e)=>n.map((r,o)=>{let s;if(typeof r.module=="object"&&(s=r.module[r.export]),!s||typeof s!="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 s}),"getWebSocketPolicyFunctions"),Ta=i(async(n,e,t,r,o,s)=>{let a=n.data;if(s&&s.length>0){let u=[...s];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,t,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function va(n,e,t,r,o){n.addEventListener("close",()=>{e.close()}),n.addEventListener("error",s=>{r.log.error("WebSocket error: ",s),e.send(JSON.stringify(s))}),n.addEventListener("message",s=>{try{let u=i(async c=>{let l=await Ta(c,n,e,t,r,o);l!==void 0&&e.send(l)},"innerPipeline")(s).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}i(va,"wireUpListeners");async function Sa(n,e){y("handler.websocket-pipeline");let t=e.route.handler.options,r=Xe(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 s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),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),f=Date.now()-u;r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${f}ms`);let h=c.webSocket;h.accept(),p.accept();let A=t.policies&&t.policies.inbound?Zo(t.policies.inbound,"inbound"):[],P=t.policies&&t.policies.outbound?Zo(t.policies.outbound,"outbound"):[];return va(p,h,n,e,A),va(h,p,n,e,P),new Response(null,{status:101,webSocket:d})}i(Sa,"webSocketPipelineHandler");var Aa=Be(Ze());function oe(n,e,t="policy",r){let o=`${t} '${e}'`;if(!it(n))throw new m(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let s=i((c,l,d)=>{let p=n[c],f=r?`${r}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new m(`Value of '${f}' 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 '${f}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new m(`Value of '${f}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new m(`Value of '${f}' 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 '${f}' on ${o} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=i((c,l)=>(s(c,l,!0),{optional:a,required:u}),"optional"),u=i((c,l)=>(s(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}i(oe,"optionValidator");var Vn=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},qo=class extends Vn{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Fo=class extends Vn{static{i(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function Md(n,e){if(Ns(n))throw new qo(e)}i(Md,"throwIfUndefinedOrNull");function nn(n,e){if(Md(n,e),!Te(n))throw new Fo(e,"string")}i(nn,"throwIfNotString");var Gn=class n{static{i(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 nn(e,"redisClientUrl"),nn(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}){nn(e,"url");let s=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=s.headers.get("Content-Type")?.includes("application/json")?await s.json():await s.text();if(s.ok)return a;throw s.status===401?new Y("Rate limiting service failed with 401: Unauthorized"):new Y(`Rate limiting service failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},Wn=class{static{i(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:t,method:r}){if(nn(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:s,key:a}=JSON.parse(t),u=Date.now()+s*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 Y("The in-memory rate limit client does not support this request")}};var Dd=i(n=>{let e=n.headers.get("x-real-ip")??n.headers.get("true-client-ip")??n.headers.get("cf-connecting-ip");if(e)return e;let t=n.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP");function vt(n,e){return{function:qd(e,"RateLimitInboundPolicy",n),user:Hd,ip:Ud,all:Zd}[e.rateLimitBy??"ip"]}i(vt,"getRateLimitByFunctions");var Ud=i(async n=>({key:`ip-${Dd(n)}`}),"getIP"),Hd=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),Zd=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Jn;function St(n,e){let t;if(Jn)return Jn;if(g.instance.isLocalDevelopment)return e.info("Using in-memory rate limit client for local development."),t=new Wn,Jn=t,t;let{authApiJWT:r,redisURL:o}=g.instance;if(!Te(o))throw new Y(`RateLimitClient used in policy '${n}' - rate limit service URL not configured`);if(!Te(r))throw new Y(`RateLimitClient used in policy '${n}' - service authentication not configured`);if(o&&(t=Gn.initialize(o,r,g.instance.deploymentName??"unknown",g.instance.systemUserAgent)),!t||!t.isEnabled())throw new Y(`RateLimitClient used in policy '${n}' - no remote rate limiting service enabled`);return Jn=t,t}i(St,"getRedisClient");async function Kn(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})}i(Kn,"getCountAndUpdateExpiry");async function Oa(n,e,t){return(await e.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:n}),requestId:t})).data}i(Oa,"multiCount");async function Ca(n,e,t){return(await e.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:n}),requestId:t})).data}i(Ca,"multiIncrement");function qd(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 i(async(s,a,u)=>{let c=await r(s,a,u);if(!c.key){let l=`${e} '${u}' - Custom rate limit function must return a valid key property '${JSON.stringify(c,null,2)}'`;throw a.log.error(l),new L(l)}return c},"outerFunction")}i(qd,"wrapUserFunction");var Ot="Retry-After";var Fd=(0,Aa.debug)("zuplo:policies:ComplexRateLimitInboundPolicy"),$o=Symbol("complex-rate-limit-counters"),Yn=class n extends fe{static{i(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let r=he.get(e,$o)??{};Object.assign(r,t),he.set(e,$o,t)}static getIncrements(e){return he.get(e,$o)??{}}ttlSeconds;constructor(e,t){super(e,t),oe(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&&oe(e.identifier,t,"policy","identifier").required("export","object").required("module","string");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}'.`);this.ttlSeconds=this.options.timeWindowMinutes*60}async handler(e,t){let r=Date.now(),o=ee.getLogger(t),s=St(this.policyName,o),a=i((c,l)=>{if(this.options.throwOnFailure)throw new Y(c,{cause:l});o.error(c,l)},"throwOrLog"),u=i((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[Ot]=l.toString()),x.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let d=(await vt(this.policyName,this.options)(e,t,this.policyName)).key,p=g.instance.isTestMode?g.instance.build.BUILD_ID:"",f=Object.entries(this.options.limits??{}).map(([C,H])=>({key:`complex-rate-limit${p}/${this.policyName}/${d}/${C}`,ttlSeconds:this.ttlSeconds,cost:H})),h=this.options.headerMode??"retry-after";t.addResponseSendingFinalHook(async()=>{try{let C=n.getIncrements(t),H=f.map(({key:B,ttlSeconds:Z,cost:$})=>({key:B,ttlSeconds:Z,cost:C[B]??$})),N=Ca(H,s,t.requestId);t.waitUntil(N),await N}catch(C){t.log.error(C)}});let A=await Oa(f,s,t.requestId);return $d(A,this.options.limits).length>0?u(h,this.ttlSeconds):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-r;Fd(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function $d(n,e){let t=[];for(let r of n){let o=e[r.key]||0;r.count>o&&t.push(r)}return t}i($d,"findOverLimits");var Xn=class extends me{constructor(t){super();this.options=t}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new jo(this.options)}},jo=class{static{i(this,"DynaTraceTransport")}constructor(e){y("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#r=g.instance.loggingEnvironmentType,this.#o=g.instance.loggingEnvironmentStage,this.#n=g.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:je(Ee(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=>{e.length!==0&&await F.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new Q("dyna-trace-log-transport",10,this.#i)};var Qn=class extends me{constructor(t){super();this.options=t}static{i(this,"LokiLoggingPlugin")}getTransport(){return new zo(this.options)}},Bo=class{static{i(this,"LokiStream")}constructor(e,t,r,o,s,a){this.level=e,this.environment=t,this.environmentType=r,this.environmentStage=o,this.requestId=a,this.job=s}job;level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function jd(n,e){return btoa(`${n}:${e}`)}i(jd,"createBasicDigest");var zo=class{static{i(this,"LokiTransport")}constructor(e){y("logging.loki"),this.#n=e.url,this.#r=jd(e.username,e.password),this.#i=g.instance.loggingEnvironmentType,this.#s=g.instance.loggingEnvironmentStage,this.#o=g.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 Bo(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(o=>{let s={stream:r,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:je(Ee(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(s)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=e=>{let t={streams:[]};return e.forEach(r=>{let o=t.streams.find(s=>s.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:r.atomicCounter}]:[r.nanoSecondEpoch,r.message])}),t};#u=async e=>{if(e.length===0)return;let t=this.#a(e);await F.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}})};batcher=new Q("loki-log-transport",10,this.#u)};var er=class extends me{constructor(t){super();this.options=t}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new Vo(this.options)}},Vo=class{static{i(this,"SumoLogicTransport")}constructor(e){y("logging.sumologic"),this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=g.instance.loggingEnvironmentType,this.#r=g.instance.loggingEnvironmentStage,this.#t=g.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:je(Ee(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(`
|
|
61
|
+
`),r=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&r.set("X-Sumo-Name",this.#i),this.#o&&r.set("X-Sumo-Category",this.#o),await F.fetch(this.#e,{method:"POST",body:t,headers:r})};batcher=new Q("sumo-logic-log-transport",10,this.#s)};var Bd="d3a5b78f823648f5b1df4fe269d41172",tr=class extends me{constructor(t){super();this.options=t}static{i(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new Go(this.options)}},Go=class{static{i(this,"VMWareLogInsightTransport")}constructor(e){y("logging.vmware-loginsight");let t;try{t=new URL(e.url),t.pathname==="/"&&(t.pathname=`/api/v1/events/ingest/${e.agentId??Bd}`)}catch{throw new m(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=t.toString(),this.#r=g.instance.loggingEnvironmentType,this.#o=g.instance.loggingEnvironmentStage,this.#n=g.instance.deploymentName,this.#i=e.onMessageSending,this.#t=e.textReplacements,e.fields&&(this.#s=Object.entries(e.fields).map(([r,o])=>({name:r,content:o})))}#e;#t;#n;#r;#o;#i;#s;log(e,t){let r=this.buildEntry(e,t);this.batcher.enqueue(r),t.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,t){let r=Ks(e.messages);this.#t?.forEach(s=>{r=r.replaceAll(s[0],s[1])});let o={timestamp:Date.now(),text:r,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#r},{name:"environment_stage",content:this.#o},{name:"log_source",content:e.logSource},{name:"atomic_counter",content:e.vectorClock}]};return e.rayId&&o.fields.push({name:"request_ray_id",content:e.rayId}),this.#n&&o.fields.push({name:"environment",content:this.#n}),this.#s&&o.fields.push(...this.#s),t.custom&&Object.entries(t.custom).forEach(([s,a])=>{let u=xo(a);u&&o.fields.push({name:s,content:u})}),this.#i&&(o=this.#i(o)),o}#a=async e=>{if(e.length===0)return;let t=await F.fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});if(t.status!==200)try{let r=await t.text();console.error("Error logging to Log Insight",r)}catch(r){console.error(r)}};batcher=new Q("vmware-log-insights-log-transport",10,this.#a)};var nr=class extends me{constructor(t){super();this.options=t}static{i(this,"AWSLoggingPlugin")}getTransport(){return new Wo(this.options)}},Wo=class{static{i(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new Q("aws-log-transport",10,async e=>{if(e.length===0)return;let t=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});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}})});constructor({accessKeyId:e,logStreamName:t,logGroupName:r,secretAccessKey:o,region:s}){y("logging.aws"),this.awsClient=new It({accessKeyId:e,secretAccessKey:o,service:"logs",region:s}),this.logGroupName=r,this.logStreamName=t,this.region=s,this.environmentType=g.instance.loggingEnvironmentType,this.environment=g.instance.deploymentName}log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:je(Ee(r)),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(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}};var Jo=new WeakMap,zd={tags:[]},rr=class extends Ke{constructor(t){super();this.options=t;y("metrics.datadog")}static{i(this,"DataDogMetricsPlugin")}getTransport(){return new Ko(this.options)}static setContext(t,r){let o=Jo.get(t);o||(o=zd);let s=Object.assign({...o},r);Jo.set(t,s)}},Ko=class{static{i(this,"DataDogMetricsTransport")}#e;#t;#n;#r;#o;#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.#o=e.include??{},this.#r=e.tags??[]}pushMetrics(e,t){this.#i===void 0&&(this.#i=new Q("data-dog-metrics-transport",10,this.dispatchFunction,ee.getLogger(t)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(Jo.get(t)?.tags??[]);if(this.#o.country&&o.push(`country:${e.country}`),this.#o.httpMethod&&o.push(`httpMethod:${e.method}`),this.#o.statusCode&&o.push(`statusCode:${e.statusCode}`),this.#o.path){let s=e.systemRouteName||e.routePath;o.push(`path:${s}`)}this.#n.latency&&this.#i.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:r,value:e.durationMs}],tags:o}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:r,value:e.requestContentLength}],tags:o}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:r,value:e.responseContentLength}],tags:o}),t.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let t=JSON.stringify({series:e}),r=await F.fetch(this.#t,{method:"POST",body:t,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new Yo(await r.text())}},Yo=class n extends Error{static{i(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var Xo=new WeakMap,Vd={dimensions:[]},or=class extends Ke{constructor(t){super();this.options=t;y("metrics.dynatrace")}static{i(this,"DynatraceMetricsPlugin")}getTransport(){return new Qo(this.options)}static setContext(t,r){let o=Xo.get(t);o||(o=Vd);let s=Object.assign({...o},r);Xo.set(t,s)}},Qo=class{static{i(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#n;#r=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.#r===void 0&&(this.#r=new Q("dynatrace-metrics-transport",10,this.dispatchFunction,ee.getLogger(t)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(Xo.get(t)?.dimensions??[]);if(this.#n.country&&o.push(`country="${e.country}"`),this.#n.httpMethod&&o.push(`http_method="${e.method}"`),this.#n.statusCode&&o.push(`status_code="${e.statusCode}"`),this.#n.path){let a=e.systemRouteName||e.routePath;o.push(`path="${a}"`)}let s=o.join(",");this.#t.latency&&this.#r.enqueue(`zuplo.request.latency,${s} ${e.durationMs} ${r}`),this.#t.requestContentLength&&e.requestContentLength&&this.#r.enqueue(`zuplo.request.content_length,${s} ${e.requestContentLength} ${r}`),this.#t.responseContentLength&&e.responseContentLength&&this.#r.enqueue(`zuplo.response.content_length,${s} ${e.responseContentLength} ${r}`),t.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let t=e.join(`
|
|
62
|
+
`),r=await F.fetch(this.#e,{method:"POST",body:t,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new ei(await r.text())}},ei=class n extends Error{static{i(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var ir=class{static{i(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e,y("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 sr=class extends qe{static{i(this,"AuditLogPlugin")}constructor(e,t){super(),this.#e=e,this.#t=t,y("audit-logs")}#e;#t;async initialize(e){new ti(e,this.#e,this.#t)}},_a=i(n=>{let e={};return n.forEach((t,r)=>{e[r]=t}),e},"serializableHeaders"),Gd={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},ti=class{static{i(this,"AuditPluginImpl")}constructor(e,t,r){this.#t=t;let o={...Gd};r?.requestFilter&&(o.requestFilter=r.requestFilter),r?.include?.request&&Object.assign(o,r.include.request),r?.include?.response&&Object.assign(o,r.include.response),this.#e=o,e.addRequestHook(this.#i),this.#n=new Q("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,t,r,o,s,a)=>{try{let u={timestamp:o,durationMs:s,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:t.url,method:t.method,headers:this.#e.include?.request?.headers?_a(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?_a(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(u),r.waitUntil(this.#n.waitUntilFlushed())}catch(u){r.log.error(u)}};#i=async(e,t)=>{try{if(!await this.#e.requestFilter(e,t))return e;let o=new Date,s=Date.now(),a=e.clone();return t.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#o(d,a,t,o,l-s,c.user?.sub).catch(f=>{t.log.error(f)});t.waitUntil(p)}),e}catch(r){return t.log.error(r),e}}};var ni=class extends Error{static{i(this,"StripeError")}message;type;raw;rawType;headers;requestId;code;doc_url;param;detail;statusCode;charge;decline_code;payment_method_type;payment_intent;payment_method;setup_intent;source;constructor(e={}){super(e.message),this.type=this.constructor.name,this.raw=e,this.rawType=e.type,this.code=e.code,this.doc_url=e.doc_url,this.param=e.param,this.detail=e.detail,this.headers=e.headers,this.requestId=e.requestId,this.statusCode=e.statusCode,this.message=e.message,this.charge=e.charge,this.decline_code=e.decline_code,this.payment_intent=e.payment_intent,this.payment_method=e.payment_method,this.payment_method_type=e.payment_method_type,this.setup_intent=e.setup_intent,this.source=e.source}},He=class extends ni{static{i(this,"StripeSignatureVerificationError")}header;payload;constructor(e,t,r={}){super(r),this.header=e,this.payload=t}};var Wd="v1",Jd=300;async function La(n,e,t,r=Jd,o){return await Yd(n,e,t,r,o),n instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(n)):JSON.parse(n)}i(La,"constructEventAsync");function Kd(n,e){return`${e.timestamp}.${n}`}i(Kd,"makeHMACContent");async function Yd(n,e,t,r,o){let{decodedHeader:s,decodedPayload:a,details:u,suspectPayloadType:c}=Xd(n,e,Wd),l=/\s/.test(t),d=await np(Kd(a,u),t);return Qd(a,s,u,d,r,c,l,o)}i(Yd,"verifyHeaderAsync");function Xd(n,e,t){if(!n)throw new He(e,n,{message:"No webhook payload was provided."});let r=typeof n!="string"&&!(n instanceof Uint8Array),o=new TextDecoder("utf8"),s=n instanceof Uint8Array?o.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 He(e,n,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=ep(a,t);if(!u||u.timestamp===-1)throw new He(a,s,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new He(a,s,{message:"No signatures found with expected scheme"});return{decodedPayload:s,decodedHeader:a,details:u,suspectPayloadType:r}}i(Xd,"parseEventDetails");function Qd(n,e,t,r,o,s,a,u){let c=!!t.signatures.filter(f=>tp(f,r)).length,l=`
|
|
63
63
|
Learn more about webhook signing and explore webhook integration examples for various frameworks at https://github.com/stripe/stripe-node#webhook-signing`,d=a?`
|
|
64
64
|
|
|
65
65
|
Note: The provided signing secret contains whitespace. This often indicates an extra newline or space is in the value`:"";if(!c)throw s?new He(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.
|
|
@@ -68,8 +68,8 @@ Signature verification is impossible without access to the original signed mater
|
|
|
68
68
|
`+d}):new He(e,n,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
|
|
69
69
|
If a webhook request is being forwarded by a third-party tool, ensure that the exact request body, including JSON formatting and new line style, is preserved.
|
|
70
70
|
`+l+`
|
|
71
|
-
`+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new He(e,n,{message:"Timestamp outside the tolerance zone"});return!0}i(jd,"validateComputedSignature");function Bd(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:[]})}i(Bd,"parseHeader");function zd(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}i(zd,"secureCompare");async function Vd(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)),s=new Uint8Array(o),a=new Array(s.length);for(let u=0;u<s.length;u++)a[u]=ni[s[u]];return a.join("")}i(Vd,"computeHMACSignatureAsync");var ni=new Array(256);for(let n=0;n<ni.length;n++)ni[n]=n.toString(16).padStart(2,"0");function ie(n,e,t="policy",r){let o=`${t} '${e}'`;if(!it(n))throw new m(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let s=i((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=i((c,l)=>(s(c,l,!0),{optional:a,required:u}),"optional"),u=i((c,l)=>(s(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}i(ie,"optionValidator");var vt=class extends we{static{i(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),f("policy.inbound.stripe-webhook-verification")}async handler(e,t){ie(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 Aa(o,r,this.options.signingSecret)}catch(o){let s=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a,s.startsWith("No signatures found matching the expected signature for payload")&&(s="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",s),T.badRequest(e,t,{title:"Webhook Error",detail:s})}return e}};function _a(n){return n!==null&&typeof n=="object"&&"id"in n&&xe(n.id)&&"type"in n&&xe(n.type)}i(_a,"isStripeWebhookEvent");var Gd={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 s="Error retrieving subscription from Stripe API.";throw t.error(s,o),new L(s)}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 s="Error retrieving customer from Stripe API.";throw t.error(s,o),new L(s)}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 s="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(s,o),new L(s)}return o}},Xn=Gd;var ri="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",La="My API Key";async function ka({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=g.instance,c=new URL(`/v1/buckets/${n}/consumers`,ri);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:La,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await Ee({retryDelayMs:5,retries:2,logger:ne.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 L(y)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(ka,"createConsumer");async function Na({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=g.instance,u=new URL(`/v1/buckets/${n}/consumers`,ri);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:La,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await Ee({retryDelayMs:5,retries:2,logger:ne.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let h="Error creating API Key Consumer";throw s.log.error(h,p),new L(h)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(Na,"createConsumerInvite");async function Ma({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=g.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,ri);o.searchParams.set("with-api-key","true");let s=await Ee({retryDelayMs:5,retries:2,logger:ne.getLogger(t)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new L(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(Ma,"deleteConsumer");async function Da({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:r,meteringBucketId:o,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[t],customerKey: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}=g.instance;if(!yt(p))throw new Q("No Zuplo JWT token set.");let y=await Ee({retryDelayMs:5,retries:2,logger:ne.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 _=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,E,C="";try{E=await y.json(),C=E.detail??E.title}catch{E={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:y.status,detail:y.statusText}}throw n.log.error(_,E),new L(`${_} ${C}`)}n.log.info("Successfully created monetization subscription.",d)}i(Da,"createSubscription");async function St({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=g.instance;if(!yt(o))throw new Q("No Zuplo JWT token set.");let a=await Ee({retryDelayMs:5,retries:2,logger:ne.getLogger(n)},`${s}/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 L(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}i(St,"updateSubscription");async function Ot({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=g.instance;if(!yt(o))throw new Q("No Zuplo JWT token set.");let a=await Ee({retryDelayMs:5,retries:2,logger:ne.getLogger(n)},`${s}/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 L(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(c),new L(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(c),new L(c)}return u.data[0]}i(Ot,"getSubscription");var se="Skipping since we're unable to process the webhook event.",Xe="Successfully processed the webhook event",Ie="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function Qn(n){return n.replaceAll("_","-")}i(Qn,"stripeStatusToMeteringStatus");function ct(n){return new Date(n*1e3).toISOString()}i(ct,"unixTimestampToISOString");async function oi(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.`),T.ok(n,e,{title:se,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),T.ok(n,e,{title:se,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}'`),T.ok(n,e,{title:se,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!==g.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}'.`),T.ok(n,e,{title:se,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=s.product,c,l,d;try{if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_email&&t.data.object.metadata.zuplo_created_by_sub)l=t.data.object.metadata.zuplo_created_by_email,d=t.data.object.metadata.zuplo_created_by_sub,c=await ka({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await Xn.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.`),T.ok(n,e,{title:se,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Na({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}`),T.ok(n,e,{title:se,detail:p.message})}if(!c)return T.ok(n,e,{title:se,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=Qn(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:ct(t.data.object.trial_end),trialStartDate:ct(t.data.object.trial_start)}),await Da({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 Ma({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),T.ok(n,e,{title:se,detail:p.message})}return T.ok(n,e,{title:Xe})}i(oi,"onCustomerSubscriptionCreated");async function ii(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.`),T.ok(n,e,{title:se,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),T.ok(n,e,{title:se,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!==g.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}'.`),T.ok(n,e,{title:se,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 Ot({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});await St({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return T.ok(n,e,{title:se,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 T.ok(n,e,{title:Xe})}i(ii,"onCustomerSubscriptionDeleted");async function si(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.`),T.ok(n,e,{title:se,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),T.ok(n,e,{title:se,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!==g.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}'.`),T.ok(n,e,{title:se,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 Ot({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=Qn(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=ct(t.data.object.trial_end)),await St({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return T.ok(n,e,{title:se,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 T.ok(n,e,{title:Xe})}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 Ot({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await Xn.getUpcomingInvoice({customerId:s,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 St({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return T.ok(n,e,{title:se,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 T.ok(n,e,{title:Xe})}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 Ot({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?ct(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?ct(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await St({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return T.ok(n,e,{title:se,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 T.ok(n,e,{title:Xe})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),T.ok(n,e,{title:se,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})}i(si,"onCustomerSubscriptionUpdated");var ai=class extends dn{constructor(t){super();this.options=t;f("monetization.stripe")}static{i(this,"StripeMonetizationPlugin")}registerRoutes(t,r){let o=i(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(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(!g.instance.build.ACCOUNT_NAME)throw new Q("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let h=this.options.primaryDataRegion??"us-central1";if(!Wd(h))throw new m(`StripeMonetizationPlugin - The value '${h}' on the property 'primaryDataRegion' is invalid.`);let y=await c.json();if(!_a(y))return T.ok(c,l,{title:se,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 oi(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await si(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await ii(c,l,y,{meteringBucketId:d});default:return T.ok(c,l,{title:se,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"),s=$s({inboundPolicies:[new vt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});ie(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new pe({processors:[be,s],handler:o,gateway:r}),u=new ue({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function Wd(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}i(Wd,"isMetricsRegion");var Ha=new WeakMap,Ua={},er=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){Ha.set(e,t)}};async function Za(n,e,t,r){if(f("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=bt(t.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=Ha.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=st(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=Ua[t.apiKey];if(!h){let y=t.apiKey,_=n.headers.get("zm-test-id")??"";h=new X("amberflo-ingest-meter",10,async E=>{try{let C=t.url??"https://app.amberflo.io/ingest",Z=await F.fetch(C,{method:"POST",body:JSON.stringify(E),headers:{"content-type":"application/json","x-api-key":y,"zm-test-id":_}});Z.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${Z.status}: ${await Z.text()}`)}catch(C){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${C.message}`),C}}),Ua[y]=h}h.enqueue(p),e.waitUntil(h.waitUntilFlushed())}}),n}i(Za,"AmberfloMeteringInboundPolicy");async function tr(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("")}i(tr,"sha256");var qa=new Map;async function ge(n,e,t){let r,o=`${n}-${e}`,s=qa.get(o);return s!==void 0?r=s:(r=`zuplo-policy-${await tr(JSON.stringify({policyName:n,options:t}))}`,qa.set(n,r)),r}i(ge,"getPolicyCacheName");var Fa="key-metadata-cache-type";function Jd(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}i(Jd,"getKeyValue");async function nr(n,e,t,r){if(f("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 s=i(C=>o.allowUnauthenticatedRequests?n:T.unauthorized(n,e,{detail:C}),"unauthorizedResponse"),a=n.headers.get(o.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=Jd(a,o);if(!u||u==="")return s("No key present");let c=await Kd(u),l=await ge(r,void 0,o),d=new de(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!==Fa&&ne.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let h={key:u},y=await Ee({retryDelayMs:5,retries:2,logger:ne.getLogger(e)},`${g.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":g.instance.deploymentName??"unknown","User-Agent":g.instance.systemUserAgent},body:JSON.stringify(h)});if(y.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(y.status!==200){try{let C=await y.text(),Z=JSON.parse(C);e.log.error("Unexpected response from key service",Z)}catch{e.log.error("Invalid response from key service")}throw new L(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${y.status}`)}let _=await y.json(),E={isValid:!0,typeId:Fa,user:{sub:_.name,data:_.metadata}};return n.user=E.user,d.put(c,E,o.cacheTtlSeconds),n}i(nr,"ApiKeyInboundPolicy");async function Kd(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Kd,"hashValue");var $a=nr;var Qt=require("jose");var ja=require("jose");var ui=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{i(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,t){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,t)}catch(r){if(r instanceof ci&&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",g.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=(0,ja.createLocalJWKSet)(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 s,a,u=!1;typeof AbortController=="function"&&(s=new AbortController,a=setTimeout(()=>{u=!0,s.abort()},t));let c=await F.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new li("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new Ct("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 Ct("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function Ba(n,e,t){let r=new ui(n,e,t);return async(o,s)=>r.getKey(o,s)}i(Ba,"createRemoteJWKSet");var Ct=class extends L{static{i(this,"JWKSError")}},ci=class extends Ct{static{i(this,"JWKSNoMatchingKey")}},li=class extends Ct{static{i(this,"JWKSTimeout")}};var rr={},Yd=i((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");if(!rr[r.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(s=r.useExperimentalInMemoryCache),s){let a=await ge(n,void 0,r),u=new de(a,e);rr[r.jwkUrl]=Ba(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else rr[r.jwkUrl]=(0,Qt.createRemoteJWKSet)(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await(0,Qt.jwtVerify)(t,rr[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),Xd=i(async(n,e)=>{let t;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);t=new Uint8Array(s)}else t=e.secret;let{payload:r}=await(0,Qt.jwtVerify)(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),fe=i(async(n,e,t,r)=>{f("policy.inbound.open-id-jwt-auth");let o=n.headers.get("Authorization"),s="bearer ",a=i(h=>T.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?Yd(r,e):Xd,l=await i(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let h=o.substring(s.length);if(!h||h.length===0)return a("No bearer token on authorization header");try{return await u(h,t)}catch(y){let _=new URL(n.url);return"code"in y&&y.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${_.pathname} `,y):e.log.warn(`Invalid token on: ${n.method} ${_.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 za=i(async(n,e,t,r)=>(f("policy.inbound.auth0-jwt-auth"),fe(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"Auth0JwtInboundPolicy");var or=class{constructor(e){this.options=e;this.authHeader=`Bearer ${btoa(e.pdpUsername+":"+e.pdpPassword)}`,this.authorizationUrl=new URL("/authorize",e.pdpUrl).toString()}static{i(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(e){let t=await F.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!t.ok)throw new Error(`Request to PDP service failed with response status ${t.status}.`);return await t.json()}};var Qd=[],ir=class n extends we{static{i(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static attributeMap;static setXacmlAttributes(e,t){n.attributeMap||(n.attributeMap=new WeakMap),n.attributeMap.set(e,{Request:t})}constructor(e,t){super(e,t),f("policy.inbound.axiomatics-authz"),ie(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new or(e)}async handler(e,t){let r=i(a=>this.options.allowUnauthorizedRequests?e:T.forbidden(e,t,{detail:a}),"forbiddenResponse");if(e.user===void 0)return t.log.debug("No user found in request. If this is unexpected, check that you have an authentication policy before this one."),this.options.allowUnauthorizedRequests?e:T.unauthorized(e,t);let o=new URL(e.url),s=n.attributeMap?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1){let a={Attribute:[{AttributeId:"request.user.sub",Value:e.user.sub}]};s.Request.AccessSubject?s.Request.AccessSubject.push(a):s.Request.AccessSubject=[a]}if(this.options.includeDefaultActionAttributes!==!1){let a={Attribute:[{AttributeId:"request.method",Value:e.method}]};s.Request.Action?s.Request.Action.push(a):s.Request.Action=[a]}if(this.options.includeDefaultResourceAttributes!==!1){let a={Attribute:[{AttributeId:"request.scheme",Value:o.protocol},{AttributeId:"request.host",Value:o.host},{AttributeId:"request.pathname",Value:o.pathname}]};Object.entries(e.params).forEach(([u,c])=>{a.Attribute.push({AttributeId:`request.params.${u}`,Value:c})}),o.searchParams.forEach((u,c)=>{a.Attribute.push({AttributeId:`request.query.${c}`,Value:u})}),s.Request.Action?s.Request.Action.push(a):s.Request.Action=[a]}this.populateAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:s,request:e,context:t}),this.populateAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:s,request:e,context:t}),this.populateAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:s,request:e,context:t});for(let a of Qd)s=await a(e,t,s);try{let a=await this.pdpService.makePdpRequest(s);return 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),T.internalServerError(e,t)}}populateAttributes({optionName:e,authzRequestCategory:t,authzRequest:r,request:o,context:s}){let a=this.options[e];if(a){let u={Attribute:[]};a.forEach(c=>{let l;if("value"in c)l=c.value;else try{l=Us(o,c.valueSelector)}catch(d){throw d instanceof m?new m(`${this.policyType} '${this.policyName}' - ${d.message}`):new L(`${this.policyType} '${this.policyName}' - ${d.message}`)}l?u.Attribute.push({AttributeId:c.attributeId,Value:l}):s.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${c.attributeId} has no value. If using a selector, check that the selector is correct.`)}),r.Request[t]?r.Request[t].push(u):r.Request[t]=[u]}}};var Va=i(async(n,e,t)=>{f("policy.inbound.basic-auth");let r=n.headers.get("Authorization"),o="basic ",s=i(l=>T.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!r)return await s("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await s("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let h=d.substring(0,p),y=d.substring(p+1),_=t.accounts.find(E=>E.username===h&&E.password===y);return _||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return t.allowUnauthenticatedRequests?n:u;let c=u.username;return n.user={sub:c,data:u.data},n},"BasicAuthInboundPolicy");function sr(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}i(sr,"extractDateElements");function Ga(n,e){return new Date(n,e+1,0).getDate()}i(Ga,"getDaysInMonth");function di(n,e){return n<=e?e-n:6-n+e+1}i(di,"getDaysBetweenWeekdays");var ar=class{static{i(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:r,days:o,months:s,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!t||t.size===0)throw new Error("There must be at least one allowed minute.");if(!r||r.size===0)throw new Error("There must be at least one allowed hour.");if(!s||s.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!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(s).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=i((c,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${c} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");u("seconds",this.seconds,{min:0,max:59}),u("minutes",this.minutes,{min:0,max:59}),u("hours",this.hours,{min:0,max:23}),u("days",this.days,{min:1,max:31}),u("months",this.months,{min:0,max:11}),u("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(c=>c).reverse(),minutes:this.minutes.map(c=>c).reverse(),hours:this.hours.map(c=>c).reverse(),days:this.days.map(c=>c).reverse(),months:this.months.map(c=>c).reverse(),weekdays:this.weekdays.map(c=>c).reverse()}}findAllowedHour(e,t){return e==="next"?this.hours.find(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 s=this.findAllowedSecond(e,t.second);if(s!==void 0)return{hour:r,minute:o,second:s};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 s=Ga(t,r),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return o>s?e==="next"?void 0:s:o;let c;a&&(c=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),c!==void 0&&c>s&&(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"?di(d,p):di(p,d);l=e==="next"?o+h:o-h,(l>s||l<1)&&(l=void 0)}}if(c!==void 0&&l!==void 0)return e==="next"?Math.min(c,l):Math.max(c,l);if(c!==void 0)return c;if(l!==void 0)return l}getNextDate(e=new Date){let t=sr(e),r=t.year,o=this.months.findIndex(a=>a>=t.month);o===-1&&(o=0,r++);let s=this.months.length*5;for(let a=0;a<s;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 s=0;s<e;s++)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=sr(e),r=t.year,o=this.reversed.months.findIndex(a=>a<=t.month);o===-1&&(o=0,r--);let s=this.reversed.months.length*5;for(let a=0;a<s;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 s=0;s<e;s++)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:s,month:a,weekday:u}=sr(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(s)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(s)!==-1&&this.weekdays.indexOf(u)!==-1}};var ep={min:0,max:59},tp={min:0,max:59},np={min:0,max:23},rp={min:1,max:31},op={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"}},ip={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},sp={"@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 lt(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=>{lt(d,e).forEach(h=>t.add(h))}),t;let o=i(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${n}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${n}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),s=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(s===null)return t.add(o(n)),t;let a=s[1]==="*"?e.min:o(s[3]),u=s[1]==="*"?e.max:o(s[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=s[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}i(lt,"parseElement");function pi(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=sp[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],s=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],u=e.length===6?e[5]:e[4];return new ar({seconds:lt(t,ep),minutes:lt(r,tp),hours:lt(o,np),days:lt(s,rp),months:new Set(Array.from(lt(a,op)).map(c=>c-1)),weekdays:new Set(Array.from(lt(u,ip)).map(c=>c%7))})}i(pi,"parseCronExpression");var ur=class extends we{static{i(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),f("policy.inbound.brownout"),ie(e,t).optional("problem","object"),e.problem&&ie(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=[pi(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>pi(r))}async handler(e,t){let r=new Date;if(r.setSeconds(0),r.setMilliseconds(0),this.crons.some(s=>s.matchDate(r))){let s=T.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 T.format(s,e,t)}return e}};var ap=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function up(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(up,"digestMessage");var cp=i(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 up(JSON.stringify(r)),s=new URL(n.url),a=new URLSearchParams(s.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=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function Wa(n,e,t,r){f("policy.inbound.caching");let o=await ge(r,t.cacheId,t),s=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await cp(n,t),c=await s.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=t.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(n.method.toUpperCase()))return;let h=t?.expirationSecondsTtl??60,y=new Response(p.body,p);ap.forEach(_=>y.headers.delete(_)),y.headers.set("cache-control",`s-maxage=${h}`),e.waitUntil(s.put(u,y))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}i(Wa,"CachingInboundPolicy");var Ja=i(async(n,e,t,r)=>{if(f("policy.inbound.change-method"),!t.method)throw new m(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new re(n,{method:t.method})},"ChangeMethodInboundPolicy");var Ka=i(async(n,e,t)=>{f("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 re(n,{headers:o})},"ClearHeadersInboundPolicy");var Ya=i(async(n,e,t,r)=>{f("policy.outbound.clear-headers");let o=[...r.exclude??[]],s=new Headers;return o.forEach(u=>{let c=n.headers.get(u);c&&s.set(u,c)}),new Response(n.body,{headers:s,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var Xa=i(async(n,e,t,r)=>{f("policy.inbound.clerk-jwt-auth");let o=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),s=new URL(o);return s.pathname="/.well-known/jwks.json",fe(n,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var Qa=i(async(n,e,t,r)=>{if(f("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 fe(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 eu=i(async(n,e,t,r)=>{if(f("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new m(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=he.instance,s=zt(t.policies,o?.routeData.policies);return Io(s)(n,e)},"CompositeInboundPolicy");var tu=i(async(n,e,t,r)=>{f("policy.inbound.curity-phantom-token-auth");let o=n.headers.get("Authorization");if(!o)return T.unauthorized(n,e,{detail:"No authorization header"});let s=lp(o);if(!s)return T.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await ge(r,void 0,t),u=new de(a,e),c=await u.get(s);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="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(s,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),T.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):T.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function lp(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(lp,"getToken");var nu=i(async(n,e,t,r)=>(f("policy.inbound.firebase-jwt-auth"),ie(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),fe(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 ru=i(async(n,e,t)=>{f("policy.inbound.form-data-to-json");let r="application/x-www-form-urlencoded",o="multipart/form-data",s=n.headers.get("content-type")?.toLowerCase();if(!s||![o,r].includes(s))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 re(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var At="__unknown__",ou=i(async(n,e,t,r)=>{f("policy.inbound.geo-filter");let o={allow:{countries:Lt(t.allow?.countries,"allow.countries",r),regionCodes:Lt(t.allow?.regionCodes,"allow.regionCode",r),asns:Lt(t.allow?.asns,"allow.asOrganization",r)},block:{countries:Lt(t.block?.countries,"block.countries",r),regionCodes:Lt(t.block?.regionCodes,"block.regionCode",r),asns:Lt(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??At,a=e.incomingRequestProperties.regionCode?.toLowerCase()??At,u=e.incomingRequestProperties.asn?.toString()??At,c=o.ignoreUnknown&&s===At,l=o.ignoreUnknown&&a===At,d=o.ignoreUnknown&&u===At,p=o.allow.countries,h=o.allow.regionCodes,y=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||h.length>0&&!h.includes(a)&&!l||y.length>0&&!y.includes(u)&&!d)return _t(n,e,r,s,a,u);let _=o.block.countries,E=o.block.regionCodes,C=o.block.asns;return _.length>0&&_.includes(s)&&!c||E.length>0&&E.includes(a)&&!l||C.length>0&&C.includes(u)&&!d?_t(n,e,r,s,a,u):n},"GeoFilterInboundPolicy");function _t(n,e,t,r,o,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${s}')`),T.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:s}})}i(_t,"blockedResponse");function Lt(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[]`)}i(Lt,"toLowerStringArray");var iu=i(async(n,e,t)=>{f("policy.inbound.jwt-scope-validation");let r=n.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(r,t.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var au=i(async(n,e,t,r)=>{f("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return mi(r,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(o),a=[];if(s.length===0)return mi(r,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{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 su(a[u])}else return a.length>0?su(a[0]):mi(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 su(n){let e=JSON.stringify(n.exampleValue,null,2),t=new Headers;switch(t.set("Content-Type",n.contentName),n.responseName){case"1XX":return new Response(e,{status:100,headers:t});case"2XX":return new Response(e,{status:200,headers:t});case"3XX":return new Response(e,{status:300,headers:t});case"4XX":return new Response(e,{status:400,headers:t});case"5XX":case"default":return new Response(e,{status:500,headers:t});default:return new Response(e,{status:Number(n.responseName),headers:t})}}i(su,"generateResponse");var mi=i((n,e,t,r)=>{let o=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${r}`;return T.internalServerError(e,t,{detail:o})},"getProblemDetailResponse");var dp="Incoming",pp={logRequestBody:!0,logResponseBody:!0};function uu(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}i(uu,"headersToObject");function cu(){return new Date().toISOString()}i(cu,"timestamp");var gi=new WeakMap,mp={};function pu(n,e){let t=gi.get(n);t||(t=mp);let r=Object.assign({...t},e);gi.set(n,r)}i(pu,"setMoesifContext");async function lu(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}i(lu,"readBody");var gp={},fi;function du(){if(!fi)throw new L("Invalid State - no _lastLogger");return fi}i(du,"getLastLogger");function fp(n){let e=gp[n];return e||(e=new X("moesif-inbound",100,async t=>{let r=JSON.stringify(t);du().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||du().error({status:o.status,body:await o.text()})})),e}i(fp,"getDispatcher");async function mu(n,e,t,r){f("policy.inbound.moesif-analytics"),fi=e.log;let o=cu(),s=Object.assign(pp,t);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await lu(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=fp(s.applicationId),d=n.headers.get("true-client-ip"),p=gi.get(e)??{},h={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:uu(n.headers)},y=s.logResponseBody?await lu(u,e):void 0,_={time:cu(),status:u.status,headers:uu(u.headers),body:y},E={request:h,response:_,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:dp};l.enqueue(E),e.waitUntil(l.waitUntilFlushed())}),n}i(mu,"MoesifInboundPolicy");async function gu(n,e,t,r){let o=ne.getLogger(n),{authApiJWT:s,meteringServiceUrl:a}=g.instance,u;try{let l=await F.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error loading subscription. ${l.status} - ${p}`),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]}i(gu,"loadSubscription");async function fu(n,e,t,r,o){let{authApiJWT:s,meteringServiceUrl:a}=g.instance,u=ne.getLogger(n);try{let c=await F.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"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)}}i(fu,"consumeSubcriptionQuotas");var hp=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function cr(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}}i(cr,"validateMeters");function hu(n,e){if(n)try{if(n.length===0)throw new m("Must set valid subscription statuses");let t=at(n),r=[];for(let o of t)hp.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"]}i(hu,"parseAllowedSubscriptionStatuses");function yu(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}}i(yu,"compareMeters");var lr=class extends we{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return Ce.get(e,Ht)}static setMeters(e,t){cr(t,"setMeters"),Ce.set(e,ln,t)}constructor(e,t){super(e,t),f("policy.inbound.monetization")}async handler(e,t){ie(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=bt(this.options.meterOnStatusCodes),s=Ce.get(t,ln),a={...this.options.meters,...s};cr(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=hu(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(E,C,Z)=>{let N=Ce.get(Z,Ht);if((this.options.allowRequestsWithoutSubscription??!1)&&!N){Z.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=Ce.get(Z,ln),B={...this.options.meters,...q};if(cr(B,this.policyName),o.includes(E.status)&&N&&B){Z.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${N.id}' with meters '${JSON.stringify(B)} on response status '${E.status}'`);let{metersInSubscription:P,metersNotInSubscription:D}=yu(N.meters,B);if(D&&Object.keys(D).length>0){let z=Object.keys(D);Z.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${z}'`)}await fu(Z,N.id,this.policyName,this.options.bucketId,P)}});let l=e.user;if(!l)return u?e:T.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 gu(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:T.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.`),T.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`),Ce.set(t,Ht,p));let h=Ce.get(t,Ht);if(!h)return u?e:(t.log.warn("Subscription is not available for user"),T.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}'`),T.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let _=Object.keys(a).filter(E=>!Object.keys(h.meters).includes(E));if(_.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${_.join(", ")}`),T.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${_.join(", ")}`,title:"Quota Exceeded"});for(let E of Object.keys(a))if(h.meters[E].available<=0&&!r)return T.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${E}'`,title:"Quota Exceeded"});return e}};var bu=i(async(n,e,t,r)=>(f("policy.inbound.okta-jwt-auth"),fe(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"OktaJwtInboundPolicy");var wu=require("jose");var hi,Ru=i(async(n,e,t,r)=>{if(f("policy.inbound.propel-auth-jwt-auth"),!hi)try{hi=await(0,wu.importSPKI)(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return fe(n,e,{issuer:t.authUrl,secret:hi,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Tu=et(ze());var Eu=et(ze());var dr=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},yi=class extends dr{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},bi=class extends dr{static{i(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function yp(n,e){if(Ms(n))throw new yi(e)}i(yp,"throwIfUndefinedOrNull");function en(n,e){if(yp(n,e),!xe(n))throw new bi(e,"string")}i(en,"throwIfNotString");var pr=class n{static{i(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 en(e,"redisClientUrl"),en(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}){en(e,"url");let s=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=s.headers.get("Content-Type")?.includes("application/json")?await s.json():await s.text();if(s.ok)return a;throw s.status===401?new Q("Rate limiting service failed with 401: Unauthorized"):new Q(`Rate limiting service failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},mr=class{static{i(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:t,method:r}){if(en(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:s,key:a}=JSON.parse(t),u=Date.now()+s*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 Q("The in-memory redis client only supports /rate-limit calls")}};var bp=i(n=>{let e=n.headers.get("x-real-ip")??n.headers.get("true-client-ip")??n.headers.get("cf-connecting-ip");if(e)return e;let t=n.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP"),fr=i(async n=>({key:`ip-${bp(n)}`}),"getIP"),hr=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),yr=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),gr;function br(n,e){let t;if(gr)return gr;if(g.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),t=new mr,gr=t,t;let{authApiJWT:r,redisURL:o}=g.instance;if(!xe(o))throw new Q(`RateLimitInboundPolicy '${n}' - rate limit service URL not configured`);if(!xe(r))throw new Q(`RateLimitInboundPolicy '${n}' - service authentication not configured`);if(o&&(t=pr.initialize(o,r,g.instance.deploymentName??"unknown",g.instance.systemUserAgent)),!t||!t.isEnabled())throw new Q(`RateLimitInboundPolicy '${n}' - no redis ('${t}') or redis.isEnabled ('${t?.isEnabled}) is false`);return gr=t,t}i(br,"getRedisClient");async function wr(n,e,t,r,o){let s=Math.floor(e*60);return await t.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:s,key:n}),requestId:o})}i(wr,"getCountAndUpdateExpiry");function Rr(n,e){let t;if(n.rateLimitBy==="function"){if(!n.identifier)throw new m(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module)throw new m(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new m(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(t=n.identifier.module[n.identifier.export],!t||typeof t!="function")throw new m(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return i(async(o,s,a)=>{let u=await t(o,s,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw s.log.error(c),new L(c)}return u},"outerFunction")}i(Rr,"wrapUserFunction");var Pr="Retry-After";var Pu=(0,Eu.debug)("zuplo:policies:RateLimitInboundPolicy"),Iu=i(async(n,e,t,r)=>{let o=ne.getLogger(e),s=i((P,D)=>{let z={};return(!P||P==="retry-after")&&(z[Pr]=D.toString()),T.tooManyRequests(n,e,void 0,z)},"rateLimited"),u={function:Rr(t,r),user:hr,ip:fr,all:yr}[t.rateLimitBy],c=await u(n,e,r),l=c.key,d=c.requestsAllowed??t.requestsAllowed,p=c.timeWindowMinutes??t.timeWindowMinutes,h=t.headerMode??"retry-after",y=br(r,o),E=`bucket/${g.instance.build.BUILD_ID}/${r}/${l}`,C=await ge(r,void 0,t),Z=new de(C,e),N=wr(E,p,y,o,e.requestId),j;i(async()=>{let P=await N;if(P.count>d){let D=Date.now()+P.ttlSeconds*1e3;Z.put(E,D,P.ttlSeconds),Pu(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${E}' (async mode)`),j=s(h,P.ttlSeconds)}},"asyncCheck")();let B=await Z.get(E);if(B!==void 0&&B>Date.now()){Pu(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${E}' (async mode)`);let P=Math.round((B-Date.now())/1e3);return s(h,P)}return e.addResponseSendingHook(async P=>j??P),n},"AsyncRateLimitInboundPolicy");var xu=(0,Tu.debug)("zuplo:policies:RateLimitInboundPolicy"),wp="strict",wi=i(async(n,e,t,r)=>{if(f("policy.inbound.rate-limit"),(t.mode??wp)==="async")return Iu(n,e,t,r);let s=Date.now(),a=ne.getLogger(e),u=i((l,d)=>{if(t.throwOnFailure)throw new Q(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[Pr]=d.toString()),T.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d={function:Rr(t,r),user:hr,ip:fr,all:yr}[t.rateLimitBy],p=await d(n,e,r),h=p.key,y=p.requestsAllowed??t.requestsAllowed,_=p.timeWindowMinutes??t.timeWindowMinutes,E=t.headerMode??"retry-after",C=br(r,a),N=`bucket/${g.instance.build.BUILD_ID}/${r}/${h}`,j=await wr(N,_,C,a,e.requestId);return j.count>y?(xu(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${N}' (strict mode)`),c(E,j.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-s;xu(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var Ri;function vu(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}i(vu,"headersToNameValuePairs");function Rp(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}i(Rp,"queryToNameValueParis");function Pp(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}i(Pp,"parseIntOrUndefined");var Su={};async function Ou(n,e,t,r){f("policy.inbound.readme-metrics");let o=new Date,s=Date.now();return Ri||(Ri={name:"zuplo",version:g.instance.build.ZUPLO_VERSION,comment:`zuplo/${g.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?st(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?st(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:g.instance.isWorkingCopy||g.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:Ri,entries:[{startedDateTime:o.toISOString(),time:Date.now()-s,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:vu(n.headers),queryString:Rp(n.query)},response:{status:a.status,statusText:a.statusText,headers:vu(a.headers),content:{size:Pp(n.headers.get("content-length"))}}}]}}},d=Su[t.apiKey];if(!d){let p=t.apiKey;d=new X("readme-metering-inbound-policy",10,async h=>{try{let y=t.url??"https://metrics.readme.io/request",_=await F.fetch(y,{method:"POST",body:JSON.stringify(h),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});_.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${_.status}: '${await _.text()}'`)}catch(y){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${y.message}'`),y}}),Su[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}i(Ou,"ReadmeMetricsInboundPolicy");var Cu=i(async(n,e,t,r)=>{f("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 s=new Headers(n.headers);return o.forEach(u=>{s.delete(u)}),new re(n,{headers:s})},"RemoveHeadersInboundPolicy");var Au=i(async(n,e,t,r,o)=>{f("policy.outbound.remove-headers");let s=r?.headers;if(!s||!Array.isArray(s)||s.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 s.forEach(c=>{a.delete(c)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var _u=i(async(n,e,t,r)=>{f("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 s=new URL(n.url);return o.forEach(u=>{s.searchParams.delete(u)}),new re(s.toString(),n)},"RemoveQueryParamsInboundPolicy");var Lu=i(async(n,e,t,r)=>{f("policy.outbound.replace-string");let o=await n.text(),s=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(s,r.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var ku=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Nu=i(async(n,e,t)=>{f("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"),s=o!==null?parseInt(o):void 0;return s&&!isNaN(s)&&s>t.maxSizeInBytes?ku():s&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?ku():n},"RequestSizeLimitInboundPolicy");function Mu(n,e,t){return`_${Qe(n+"_"+e+"_"+t)}`}i(Mu,"getRawOperationDataIdentifierName");function Er(n,e,t,r){return`_${Qe(n.toLowerCase())}_`+e.toLowerCase()+"_"+t.toLowerCase()+`_${r.toLowerCase()}`}i(Er,"getIdForParameterSchema");function Ir(n,e,t){return`_${Qe(n.toLowerCase())}_`+e.toLowerCase()+`_rb_${Qe(t.toLowerCase())}`}i(Ir,"getIdForRequestBodySchema");function Du(n,e){return`_${Qe(n)}__${Qe(e)}`}i(Du,"getIdForRefSchema");function Qe(n){let e=[];for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(n.charAt(t)):e.push("_")}return e.join("")}i(Qe,"sanitizedIdentifierName");var kt=i(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"),Nt=i((n,e,t,r,o)=>{let s=[],a=!0,u=[];return n.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,s.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=Er(t,r,o,c.name),p=he.instance.schemaValidator[d],h=p(e[c.name]),y=Pi(p.errors);h||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${y.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),Le=i((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),ke=i(n=>n==="log-only"||n==="reject-and-log","shouldLog"),Ne=i(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),Pi=i(n=>n?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function Uu(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(y){let _=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,E=T.badRequest(e,n,{detail:`${_}, see errors property for more details`,errors:`${y}`});if(ke(t.validateBody)&&Le(n,t.logLevel??"info",_,[r],y),Ne(t.validateBody))return E}if(!e.headers.get("Content-Type")){let y=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,_=T.badRequest(e,n,{detail:y});return ke(t.validateBody)&&Le(n,t.logLevel??"info",y,[r],[y]),Ne(t.validateBody)?_:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=Ir(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")}`,_=T.badRequest(e,n,{detail:y});return ke(t.validateBody)&&Le(n,t.logLevel??"info",y,[r],[y]),Ne(t.validateBody)?_:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Pi(l),h=T.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(ke(t.validateBody)&&Le(n,t.logLevel??"info",d,[r],p),Ne(t.validateBody))return h}i(Uu,"handleBodyValidation");function Hu(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=kt(n),s=Nt(o.filter(a=>a.location==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=T.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:s.errors});if(ke(t.validateHeaders)&&Le(n,t.logLevel??"info",a,s.invalidValues,s.errors),Ne(t.validateHeaders))return u}}i(Hu,"handleHeadersValidation");function Zu(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=kt(n),o=Nt(r.filter(s=>s.location==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let s="Path parameters validation failed",a=T.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(ke(t.validatePathParameters)&&Le(n,t.logLevel??"info",s,o.invalidValues,o.errors),Ne(t.validatePathParameters))return a}}i(Zu,"handlePathParameterValidation");function qu(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=kt(n),o=Nt(r.filter(s=>s.location==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let s="Query parameters validation failed",a=T.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(ke(t.validateQueryParameters)&&Le(n,t.logLevel??"info",s,o.invalidValues,o.errors),Ne(t.validateQueryParameters))return a}}i(qu,"handleQueryParameterValidation");var Ei=i(async(n,e,t)=>{f("policy.inbound.request-validation");let r=qu(e,n,t);if(r!==void 0||(r=Zu(e,n,t),r!==void 0)||(r=Hu(e,n,t),r!==void 0))return r;let o=await Uu(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),Fu=Ei;var $u=i(async(n,e,t,r)=>{if(f("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 s=n.headers.get("origin");if(!s||!o.includes(s)){let a=t.failureDetail??"Forbidden";return T.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var ju=i(async(n,e,t)=>(f("policy.inbound.set-body"),new re(n,{body:t.body})),"SetBodyInboundPolicy");var Bu=i(async(n,e,t,r)=>{f("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 s=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;(!s.has(u.name)||c)&&s.set(u.name,u.value)}),new re(n,{headers:s})},"SetHeadersInboundPolicy");var zu=i(async(n,e,t,r,o)=>{f("policy.outbound.set-headers");let s=r.headers;if(!s||!Array.isArray(s)||s.length==0)throw new m(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return s.forEach(c=>{if(!c.name||c.name.length===0)throw new m(`SetHeadersOutboundPolicy '${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 Vu=i(async(n,e,t,r)=>{f("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 s=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;(!s.searchParams.has(u.name)||c)&&s.searchParams.set(u.name,u.value)}),new re(s.toString(),n)},"SetQueryParamsInboundPolicy");var Gu=i(async(n,e,t,r,o)=>{if(f("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 Ep=i(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),Wu=i(async(n,e,t,r)=>{if(f("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 Ep(t.sleepInMs),n},"SleepInboundPolicy");var Ju=i(async(n,e,t,r)=>{f("policy.inbound.supabase-jwt-auth"),ie(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},s=await fe(n,e,o,r);if(s instanceof Response)return s;if(!(s instanceof re))throw new Q("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return s;let u=n.user?.data.app_metadata;if(!u)throw new L(`SupabaseJwtInboundPolicy policy '${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?T.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var Ku=i(async(n,e,t,r)=>{f("policy.inbound.upstream-azure-ad-service-auth"),ie(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await ge(r,void 0,t),s=new de(o,e),a=await s.get(r);if(!a){let u=await Ip(t,e);s.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 Ip(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await Ee({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 s=await r.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new L("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 L("Response returned from Azure AD is not in the expected format.")}i(Ip,"getAccessToken");var Yu="https://accounts.google.com/o/oauth2/token",Ii,Xu=i(async(n,e,t,r)=>{f("policy.inbound.upstream-firebase-admin-auth"),ie(t,r).required("serviceAccountJson","string"),Ii||(Ii=await Te.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(" ")},s=await ge(r,void 0,t),a=new de(s,e),u=await a.get(r);if(!u){let c=await De({serviceAccount:Ii,audience:Yu,payload:o}),l=await On(Yu,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(r,u,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var xp="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Tp=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],xi,Qu=i(async(n,e,t,r)=>{if(f("policy.inbound.upstream-firebase-user-auth"),ie(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(Tp.indexOf(p)!==-1)throw new m(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}xi||(xi=await Te.init(t.serviceAccountJson));let s=t.userId;if(!s&&!t.userIdPropertyPath){if(!n.user)throw new L("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new L(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=st(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new L(`Unable to determine user from for the policy ${r}`);let a=await ge(r,void 0,t),u=new de(a,e),c={uid:s,claims:o},l=await tr(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await De({serviceAccount:xi,audience:xp,payload:c}),h=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,y=await Xs(h,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 Ti,ec=i(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-jwt"),ie(t,r).required("audience","string").required("serviceAccountJson","string"),Ti||(Ti=await Te.init(t.serviceAccountJson));let o=await De({serviceAccount:Ti,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var tc="https://www.googleapis.com/oauth2/v4/token",vi,nc=i(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-service-auth"),ie(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),vi||(vi=await Te.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=at(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 s=await ge(r,void 0,t),a;t.useMemoryCacheOnly?a=new dt(s):a=new de(s,e);let u=await a.get(r);if(!u){let c=await De({serviceAccount:vi,audience:tc,payload:o}),l=await On(tc,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(r,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var rc=i(async(n,e,t)=>{f("policy.inbound.validate-json-schema");let r=n.clone(),o;try{o=await r.json()}catch{return T.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 Q("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 T.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var oc=i(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=i((E,C)=>e(E,"name",{value:C,configurable:!0}),"__name"),o=i((E,C)=>i(function(){return C||(0,E[t(E)[0]])((C={exports:{}}).exports,C),C.exports},"__require"),"__commonJS"),s=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(E){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(N,j){return j},attributeValueProcessor:function(N,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(N,j,q){return N}},Z=r(function(N){return Object.assign({},C,N)},"buildOptions");E.buildOptions=Z,E.defaultOptions=C}}),a=o({"node_modules/fast-xml-parser/src/util.js"(E){"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",Z=C+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",N="["+C+"]["+Z+"]*",j=new RegExp("^"+N+"$"),q=r(function(P,D){let z=[],W=D.exec(P);for(;W;){let S=[];S.startIndex=D.lastIndex-W[0].length;let x=W.length;for(let H=0;H<x;H++)S.push(W[H]);z.push(S),W=D.exec(P)}return z},"getAllMatches"),B=r(function(P){let D=j.exec(P);return!(D===null||typeof D>"u")},"isName");E.isExist=function(P){return typeof P<"u"},E.isEmptyObject=function(P){return Object.keys(P).length===0},E.merge=function(P,D,z){if(D){let W=Object.keys(D),S=W.length;for(let x=0;x<S;x++)z==="strict"?P[W[x]]=[D[W[x]]]:P[W[x]]=D[W[x]]}},E.getValue=function(P){return E.isExist(P)?P:""},E.isName=B,E.getAllMatches=q,E.nameRegexp=N}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(E,C){"use strict";var Z=class{static{i(this,"XmlNode")}static{r(this,"XmlNode")}constructor(N){this.tagname=N,this.child=[],this[":@"]={}}add(N,j){N==="__proto__"&&(N="#__proto__"),this.child.push({[N]:j})}addChild(N){N.tagname==="__proto__"&&(N.tagname="#__proto__"),N[":@"]&&Object.keys(N[":@"]).length>0?this.child.push({[N.tagname]:N.child,":@":N[":@"]}):this.child.push({[N.tagname]:N.child})}};C.exports=Z}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(E,C){var Z=a();function N(S,x){let H={};if(S[x+3]==="O"&&S[x+4]==="C"&&S[x+5]==="T"&&S[x+6]==="Y"&&S[x+7]==="P"&&S[x+8]==="E"){x=x+9;let ce=1,Y=!1,ee=!1,Se="";for(;x<S.length;x++)if(S[x]==="<"&&!ee){if(Y&&B(S,x))x+=7,[entityName,val,x]=j(S,x+1),val.indexOf("&")===-1&&(H[W(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(Y&&P(S,x))x+=8;else if(Y&&D(S,x))x+=8;else if(Y&&z(S,x))x+=9;else if(q)ee=!0;else throw new Error("Invalid DOCTYPE");ce++,Se=""}else if(S[x]===">"){if(ee?S[x-1]==="-"&&S[x-2]==="-"&&(ee=!1,ce--):ce--,ce===0)break}else S[x]==="["?Y=!0:Se+=S[x];if(ce!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:H,i:x}}i(N,"readDocType"),r(N,"readDocType");function j(S,x){let H="";for(;x<S.length&&S[x]!=="'"&&S[x]!=='"';x++)H+=S[x];if(H=H.trim(),H.indexOf(" ")!==-1)throw new Error("External entites are not supported");let ce=S[x++],Y="";for(;x<S.length&&S[x]!==ce;x++)Y+=S[x];return[H,Y,x]}i(j,"readEntityExp"),r(j,"readEntityExp");function q(S,x){return S[x+1]==="!"&&S[x+2]==="-"&&S[x+3]==="-"}i(q,"isComment"),r(q,"isComment");function B(S,x){return S[x+1]==="!"&&S[x+2]==="E"&&S[x+3]==="N"&&S[x+4]==="T"&&S[x+5]==="I"&&S[x+6]==="T"&&S[x+7]==="Y"}i(B,"isEntity"),r(B,"isEntity");function P(S,x){return S[x+1]==="!"&&S[x+2]==="E"&&S[x+3]==="L"&&S[x+4]==="E"&&S[x+5]==="M"&&S[x+6]==="E"&&S[x+7]==="N"&&S[x+8]==="T"}i(P,"isElement"),r(P,"isElement");function D(S,x){return S[x+1]==="!"&&S[x+2]==="A"&&S[x+3]==="T"&&S[x+4]==="T"&&S[x+5]==="L"&&S[x+6]==="I"&&S[x+7]==="S"&&S[x+8]==="T"}i(D,"isAttlist"),r(D,"isAttlist");function z(S,x){return S[x+1]==="!"&&S[x+2]==="N"&&S[x+3]==="O"&&S[x+4]==="T"&&S[x+5]==="A"&&S[x+6]==="T"&&S[x+7]==="I"&&S[x+8]==="O"&&S[x+9]==="N"}i(z,"isNotation"),r(z,"isNotation");function W(S){if(Z.isName(S))return S;throw new Error(`Invalid entity name ${S}`)}i(W,"validateEntityName"),r(W,"validateEntityName"),C.exports=N}}),l=o({"../../node_modules/strnum/strnum.js"(E,C){var Z=/^[-+]?0x[a-fA-F0-9]+$/,N=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var j={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function q(P,D={}){if(D=Object.assign({},j,D),!P||typeof P!="string")return P;let z=P.trim();if(D.skipLike!==void 0&&D.skipLike.test(z))return P;if(D.hex&&Z.test(z))return Number.parseInt(z,16);{let W=N.exec(z);if(W){let S=W[1],x=W[2],H=B(W[3]),ce=W[4]||W[6];if(!D.leadingZeros&&x.length>0&&S&&z[2]!==".")return P;if(!D.leadingZeros&&x.length>0&&!S&&z[1]!==".")return P;{let Y=Number(z),ee=""+Y;return ee.search(/[eE]/)!==-1||ce?D.eNotation?Y:P:z.indexOf(".")!==-1?ee==="0"&&H===""||ee===H||S&&ee==="-"+H?Y:P:x?H===ee||S+H===ee?Y:P:z===ee||z===S+ee?Y:P}}else return P}}i(q,"toNumber"),r(q,"toNumber");function B(P){return P&&P.indexOf(".")!==-1&&(P=P.replace(/0+$/,""),P==="."?P="0":P[0]==="."?P="0"+P:P[P.length-1]==="."&&(P=P.substr(0,P.length-1))),P}i(B,"trimZeros"),r(B,"trimZeros"),C.exports=q}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(E,C){"use strict";var Z=a(),N=u(),j=c(),q=l(),B=class{static{i(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=P,this.parseXml=x,this.parseTextData=D,this.resolveNameSpace=z,this.buildAttributesMap=S,this.isItStopNode=ee,this.replaceEntitiesValue=ce,this.readStopNodeData=G,this.saveTextToParentTag=Y,this.addChild=H}};function P(R){let I=Object.keys(R);for(let A=0;A<I.length;A++){let V=I[A];this.lastEntities[V]={regex:new RegExp("&"+V+";","g"),val:R[V]}}}i(P,"addExternalEntities"),r(P,"addExternalEntities");function D(R,I,A,V,k,M,te){if(R!==void 0&&(this.options.trimValues&&!V&&(R=R.trim()),R.length>0)){te||(R=this.replaceEntitiesValue(R));let $=this.options.tagValueProcessor(I,R,A,k,M);return $==null?R:typeof $!=typeof R||$!==R?$:this.options.trimValues?le(R,this.options.parseTagValue,this.options.numberParseOptions):R.trim()===R?le(R,this.options.parseTagValue,this.options.numberParseOptions):R}}i(D,"parseTextData"),r(D,"parseTextData");function z(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}i(z,"resolveNameSpace"),r(z,"resolveNameSpace");var W=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function S(R,I,A){if(!this.options.ignoreAttributes&&typeof R=="string"){let V=Z.getAllMatches(R,W),k=V.length,M={};for(let te=0;te<k;te++){let $=this.resolveNameSpace(V[te][1]),U=V[te][4],ae=this.options.attributeNamePrefix+$;if($.length)if(this.options.transformAttributeName&&(ae=this.options.transformAttributeName(ae)),ae==="__proto__"&&(ae="#__proto__"),U!==void 0){this.options.trimValues&&(U=U.trim()),U=this.replaceEntitiesValue(U);let oe=this.options.attributeValueProcessor($,U,I);oe==null?M[ae]=U:typeof oe!=typeof U||oe!==U?M[ae]=oe:M[ae]=le(U,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(M[ae]=!0)}if(!Object.keys(M).length)return;if(this.options.attributesGroupName){let te={};return te[this.options.attributesGroupName]=M,te}return M}}i(S,"buildAttributesMap"),r(S,"buildAttributesMap");var x=r(function(R){R=R.replace(/\r\n?/g,`
|
|
72
|
-
`);let
|
|
73
|
-
`&&b[
|
|
74
|
-
`||b==="\r"}i(N,"isWhiteSpace"),r(N,"isWhiteSpace");function
|
|
71
|
+
`+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new He(e,n,{message:"Timestamp outside the tolerance zone"});return!0}i(Qd,"validateComputedSignature");function ep(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:[]})}i(ep,"parseHeader");function tp(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}i(tp,"secureCompare");async function np(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)),s=new Uint8Array(o),a=new Array(s.length);for(let u=0;u<s.length;u++)a[u]=ri[s[u]];return a.join("")}i(np,"computeHMACSignatureAsync");var ri=new Array(256);for(let n=0;n<ri.length;n++)ri[n]=n.toString(16).padStart(2,"0");var Ct=class extends fe{static{i(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),y("policy.inbound.stripe-webhook-verification")}async handler(e,t){oe(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 La(o,r,this.options.signingSecret)}catch(o){let s=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a,s.startsWith("No signatures found matching the expected signature for payload")&&(s="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",s),x.badRequest(e,t,{title:"Webhook Error",detail:s})}return e}};function ka(n){return n!==null&&typeof n=="object"&&"id"in n&&Te(n.id)&&"type"in n&&Te(n.type)}i(ka,"isStripeWebhookEvent");var rp={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 s="Error retrieving subscription from Stripe API.";throw t.error(s,o),new L(s)}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 s="Error retrieving customer from Stripe API.";throw t.error(s,o),new L(s)}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 s="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(s,o),new L(s)}return o}},ar=rp;var oi="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Na="My API Key";async function Ma({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=g.instance,c=new URL(`/v1/buckets/${n}/consumers`,oi);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Na,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await Ie({retryDelayMs:5,retries:2,logger:ee.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 h="Error creating API Key Consumer";throw a.log.error(h,f),new L(h)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(Ma,"createConsumer");async function Da({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=g.instance,u=new URL(`/v1/buckets/${n}/consumers`,oi);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:Na,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await Ie({retryDelayMs:5,retries:2,logger:ee.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let f="Error creating API Key Consumer";throw s.log.error(f,p),new L(f)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(Da,"createConsumerInvite");async function Ua({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=g.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,oi);o.searchParams.set("with-api-key","true");let s=await Ie({retryDelayMs:5,retries:2,logger:ee.getLogger(t)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new L(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(Ua,"deleteConsumer");async function Ha({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:r,meteringBucketId:o,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[t],customerKey: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:f}=g.instance;if(!yt(p))throw new Y("No Zuplo JWT token set.");let h=await Ie({retryDelayMs:5,retries:2,logger:ee.getLogger(n)},`${f}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!h.ok){let A=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,P,C="";try{P=await h.json(),C=P.detail??P.title}catch{P={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:h.status,detail:h.statusText}}throw n.log.error(A,P),new L(`${A} ${C}`)}n.log.info("Successfully created monetization subscription.",d)}i(Ha,"createSubscription");async function At({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=g.instance;if(!yt(o))throw new Y("No Zuplo JWT token set.");let a=await Ie({retryDelayMs:5,retries:2,logger:ee.getLogger(n)},`${s}/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 L(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}i(At,"updateSubscription");async function _t({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=g.instance;if(!yt(o))throw new Y("No Zuplo JWT token set.");let a=await Ie({retryDelayMs:5,retries:2,logger:ee.getLogger(n)},`${s}/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 L(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(c),new L(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(c),new L(c)}return u.data[0]}i(_t,"getSubscription");var se="Skipping since we're unable to process the webhook event.",Qe="Successfully processed the webhook event",xe="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function ur(n){return n.replaceAll("_","-")}i(ur,"stripeStatusToMeteringStatus");function ct(n){return new Date(n*1e3).toISOString()}i(ct,"unixTimestampToISOString");async function ii(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:se,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),x.ok(n,e,{title:se,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:se,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!==g.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:se,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.`+xe});let u=s.product,c,l,d;try{if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_email&&t.data.object.metadata.zuplo_created_by_sub)l=t.data.object.metadata.zuplo_created_by_email,d=t.data.object.metadata.zuplo_created_by_sub,c=await Ma({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await ar.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:se,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Da({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:se,detail:p.message})}if(!c)return x.ok(n,e,{title:se,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=ur(t.data.object.status),f;l&&d&&(f={subscriber:{sub:d,email:l}});let h;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")&&(h={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:ct(t.data.object.trial_end),trialStartDate:ct(t.data.object.trial_start)}),await Ha({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:f,trial:h})}catch(p){return await Ua({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),x.ok(n,e,{title:se,detail:p.message})}return x.ok(n,e,{title:Qe})}i(ii,"onCustomerSubscriptionCreated");async function si(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:se,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:se,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!==g.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:se,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.`+xe});try{let a=await _t({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});await At({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return x.ok(n,e,{title:se,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. `+xe})}return x.ok(n,e,{title:Qe})}i(si,"onCustomerSubscriptionDeleted");async function ai(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:se,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:se,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!==g.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:se,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.`+xe});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 _t({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=ur(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=ct(t.data.object.trial_end)),await At({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return x.ok(n,e,{title:se,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. `+xe})}return x.ok(n,e,{title:Qe})}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 _t({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await ar.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:r.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 At({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return x.ok(n,e,{title:se,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. `+xe})}return x.ok(n,e,{title:Qe})}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 _t({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?ct(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?ct(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await At({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:se,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. `+xe})}return x.ok(n,e,{title:Qe})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),x.ok(n,e,{title:se,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."+xe})}i(ai,"onCustomerSubscriptionUpdated");var ui=class extends gn{constructor(t){super();this.options=t;y("monetization.stripe")}static{i(this,"StripeMonetizationPlugin")}registerRoutes(t,r){let o=i(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!g.instance.build.ACCOUNT_NAME)throw new Y("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let f=this.options.primaryDataRegion??"us-central1";if(!op(f))throw new m(`StripeMonetizationPlugin - The value '${f}' on the property 'primaryDataRegion' is invalid.`);let h=await c.json();if(!ka(h))return x.ok(c,l,{title:se,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+xe});switch(l.log.info(`Received Stripe webhook event of type '${h.type}' with ID '${h.id}'.`),h.type){case"customer.subscription.created":return await ii(c,l,h,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:f,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await ai(c,l,h,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:f,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await si(c,l,h,{meteringBucketId:d});default:return x.ok(c,l,{title:se,detail:`Event '${h.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.`+xe})}},"stripeWebhookHandler"),s=Fs({inboundPolicies:[new Ct({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});oe(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new pe({processors:[Re,s],handler:o,gateway:r}),u=new ue({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function op(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}i(op,"isMetricsRegion");var qa=new WeakMap,Za={},cr=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){qa.set(e,t)}};async function Fa(n,e,t,r){if(y("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=bt(t.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=qa.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=st(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)},f=Za[t.apiKey];if(!f){let h=t.apiKey,A=n.headers.get("zm-test-id")??"";f=new Q("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":h,"zm-test-id":A}});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}}),Za[h]=f}f.enqueue(p),e.waitUntil(f.waitUntilFlushed())}}),n}i(Fa,"AmberfloMeteringInboundPolicy");async function lr(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("")}i(lr,"sha256");var $a=new Map;async function ge(n,e,t){let r,o=`${n}-${e}`,s=$a.get(o);return s!==void 0?r=s:(r=`zuplo-policy-${await lr(JSON.stringify({policyName:n,options:t}))}`,$a.set(n,r)),r}i(ge,"getPolicyCacheName");var ja="key-metadata-cache-type";function ip(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}i(ip,"getKeyValue");async function dr(n,e,t,r){if(y("policy.inbound.api-key"),!t.bucketName)if(Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m(`ApiKeyInboundPolicy '${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 s=i(C=>o.allowUnauthenticatedRequests?n:x.unauthorized(n,e,{detail:C}),"unauthorizedResponse"),a=n.headers.get(o.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=ip(a,o);if(!u||u==="")return s("No key present");let c=await sp(u),l=await ge(r,void 0,o),d=new de(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!==ja&&ee.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let f={key:u},h=await Ie({retryDelayMs:5,retries:2,logger:ee.getLogger(e)},`${g.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":g.instance.deploymentName??"unknown","User-Agent":g.instance.systemUserAgent},body:JSON.stringify(f)});if(h.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(h.status!==200){try{let C=await h.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 L(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${h.status}`)}let A=await h.json(),P={isValid:!0,typeId:ja,user:{sub:A.name,data:A.metadata}};return n.user=P.user,d.put(c,P,o.cacheTtlSeconds),n}i(dr,"ApiKeyInboundPolicy");async function sp(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(sp,"hashValue");var Ba=dr;var rn=require("jose");var za=require("jose");var ci=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{i(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,t){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,t)}catch(r){if(r instanceof li&&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",g.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=(0,za.createLocalJWKSet)(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 s,a,u=!1;typeof AbortController=="function"&&(s=new AbortController,a=setTimeout(()=>{u=!0,s.abort()},t));let c=await F.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new di("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new Lt("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 Lt("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function Va(n,e,t){let r=new ci(n,e,t);return async(o,s)=>r.getKey(o,s)}i(Va,"createRemoteJWKSet");var Lt=class extends L{static{i(this,"JWKSError")}},li=class extends Lt{static{i(this,"JWKSNoMatchingKey")}},di=class extends Lt{static{i(this,"JWKSTimeout")}};var pr={},ap=i((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");if(!pr[r.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(s=r.useExperimentalInMemoryCache),s){let a=await ge(n,void 0,r),u=new de(a,e);pr[r.jwkUrl]=Va(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else pr[r.jwkUrl]=(0,rn.createRemoteJWKSet)(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await(0,rn.jwtVerify)(t,pr[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),up=i(async(n,e)=>{let t;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);t=new Uint8Array(s)}else t=e.secret;let{payload:r}=await(0,rn.jwtVerify)(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),ye=i(async(n,e,t,r)=>{y("policy.inbound.open-id-jwt-auth");let o=n.headers.get("Authorization"),s="bearer ",a=i(f=>x.unauthorized(n,e,{detail:f}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${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?ap(r,e):up,l=await i(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let f=o.substring(s.length);if(!f||f.length===0)return a("No bearer token on authorization header");try{return await u(f,t)}catch(h){let A=new URL(n.url);return"code"in h&&h.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${A.pathname} `,h):e.log.warn(`Invalid token on: ${n.method} ${A.pathname}`,h),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 Ga=i(async(n,e,t,r)=>(y("policy.inbound.auth0-jwt-auth"),ye(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"Auth0JwtInboundPolicy");var mr=class{constructor(e){this.options=e;this.authHeader=`Bearer ${btoa(e.pdpUsername+":"+e.pdpPassword)}`,this.authorizationUrl=new URL("/authorize",e.pdpUrl).toString()}static{i(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(e){let t=await F.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!t.ok)throw new Error(`Request to PDP service failed with response status ${t.status}.`);return await t.json()}};var cp=[],gr=class n extends fe{static{i(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static attributeMap;static setXacmlAttributes(e,t){n.attributeMap||(n.attributeMap=new WeakMap),n.attributeMap.set(e,{Request:t})}constructor(e,t){super(e,t),y("policy.inbound.axiomatics-authz"),oe(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new mr(e)}async handler(e,t){let r=i(a=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:a}),"forbiddenResponse");if(e.user===void 0)return t.log.debug("No user found in request. If this is unexpected, check that you have an authentication policy before this one."),this.options.allowUnauthorizedRequests?e:x.unauthorized(e,t);let o=new URL(e.url),s=n.attributeMap?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1){let a={Attribute:[{AttributeId:"request.user.sub",Value:e.user.sub}]};s.Request.AccessSubject?s.Request.AccessSubject.push(a):s.Request.AccessSubject=[a]}if(this.options.includeDefaultActionAttributes!==!1){let a={Attribute:[{AttributeId:"request.method",Value:e.method}]};s.Request.Action?s.Request.Action.push(a):s.Request.Action=[a]}if(this.options.includeDefaultResourceAttributes!==!1){let a={Attribute:[{AttributeId:"request.scheme",Value:o.protocol},{AttributeId:"request.host",Value:o.host},{AttributeId:"request.pathname",Value:o.pathname}]};Object.entries(e.params).forEach(([u,c])=>{a.Attribute.push({AttributeId:`request.params.${u}`,Value:c})}),o.searchParams.forEach((u,c)=>{a.Attribute.push({AttributeId:`request.query.${c}`,Value:u})}),s.Request.Action?s.Request.Action.push(a):s.Request.Action=[a]}this.populateAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:s,request:e,context:t}),this.populateAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:s,request:e,context:t}),this.populateAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:s,request:e,context:t});for(let a of cp)s=await a(e,t,s);try{let a=await this.pdpService.makePdpRequest(s);return 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)}}populateAttributes({optionName:e,authzRequestCategory:t,authzRequest:r,request:o,context:s}){let a=this.options[e];if(a){let u={Attribute:[]};a.forEach(c=>{let l;if("value"in c)l=c.value;else try{l=Ds(o,c.valueSelector)}catch(d){throw d instanceof m?new m(`${this.policyType} '${this.policyName}' - ${d.message}`):new L(`${this.policyType} '${this.policyName}' - ${d.message}`)}l?u.Attribute.push({AttributeId:c.attributeId,Value:l}):s.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${c.attributeId} has no value. If using a selector, check that the selector is correct.`)}),r.Request[t]?r.Request[t].push(u):r.Request[t]=[u]}}};var Wa=i(async(n,e,t)=>{y("policy.inbound.basic-auth");let r=n.headers.get("Authorization"),o="basic ",s=i(l=>x.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!r)return await s("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await s("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let f=d.substring(0,p),h=d.substring(p+1),A=t.accounts.find(P=>P.username===f&&P.password===h);return A||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return t.allowUnauthenticatedRequests?n:u;let c=u.username;return n.user={sub:c,data:u.data},n},"BasicAuthInboundPolicy");function fr(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}i(fr,"extractDateElements");function Ja(n,e){return new Date(n,e+1,0).getDate()}i(Ja,"getDaysInMonth");function pi(n,e){return n<=e?e-n:6-n+e+1}i(pi,"getDaysBetweenWeekdays");var hr=class{static{i(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:r,days:o,months:s,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!t||t.size===0)throw new Error("There must be at least one allowed minute.");if(!r||r.size===0)throw new Error("There must be at least one allowed hour.");if(!s||s.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!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(s).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=i((c,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${c} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");u("seconds",this.seconds,{min:0,max:59}),u("minutes",this.minutes,{min:0,max:59}),u("hours",this.hours,{min:0,max:23}),u("days",this.days,{min:1,max:31}),u("months",this.months,{min:0,max:11}),u("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(c=>c).reverse(),minutes:this.minutes.map(c=>c).reverse(),hours:this.hours.map(c=>c).reverse(),days:this.days.map(c=>c).reverse(),months:this.months.map(c=>c).reverse(),weekdays:this.weekdays.map(c=>c).reverse()}}findAllowedHour(e,t){return e==="next"?this.hours.find(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 s=this.findAllowedSecond(e,t.second);if(s!==void 0)return{hour:r,minute:o,second:s};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 s=Ja(t,r),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return o>s?e==="next"?void 0:s:o;let c;a&&(c=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),c!==void 0&&c>s&&(c=void 0));let l;if(u){let d=new Date(t,r,o).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"?pi(d,p):pi(p,d);l=e==="next"?o+f:o-f,(l>s||l<1)&&(l=void 0)}}if(c!==void 0&&l!==void 0)return e==="next"?Math.min(c,l):Math.max(c,l);if(c!==void 0)return c;if(l!==void 0)return l}getNextDate(e=new Date){let t=fr(e),r=t.year,o=this.months.findIndex(a=>a>=t.month);o===-1&&(o=0,r++);let s=this.months.length*5;for(let a=0;a<s;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 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 r=[],o;for(let s=0;s<e;s++)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=fr(e),r=t.year,o=this.reversed.months.findIndex(a=>a<=t.month);o===-1&&(o=0,r--);let s=this.reversed.months.length*5;for(let a=0;a<s;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 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 r=[],o;for(let s=0;s<e;s++)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:s,month:a,weekday:u}=fr(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(s)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(s)!==-1&&this.weekdays.indexOf(u)!==-1}};var lp={min:0,max:59},dp={min:0,max:59},pp={min:0,max:23},mp={min:1,max:31},gp={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"}},fp={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},hp={"@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 lt(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=>{lt(d,e).forEach(f=>t.add(f))}),t;let o=i(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${n}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${n}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),s=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(s===null)return t.add(o(n)),t;let a=s[1]==="*"?e.min:o(s[3]),u=s[1]==="*"?e.max:o(s[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=s[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}i(lt,"parseElement");function mi(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=hp[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],s=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],u=e.length===6?e[5]:e[4];return new hr({seconds:lt(t,lp),minutes:lt(r,dp),hours:lt(o,pp),days:lt(s,mp),months:new Set(Array.from(lt(a,gp)).map(c=>c-1)),weekdays:new Set(Array.from(lt(u,fp)).map(c=>c%7))})}i(mi,"parseCronExpression");var yr=class extends fe{static{i(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),y("policy.inbound.brownout"),oe(e,t).optional("problem","object"),e.problem&&oe(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=[mi(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>mi(r))}async handler(e,t){let r=new Date;if(r.setSeconds(0),r.setMilliseconds(0),this.crons.some(s=>s.matchDate(r))){let s=x.getProblemFromStatus(this.options.problem?.status??400,{detail:"This API is performing a scheduled brownout in advance of its pending deprecation. Please upgrade to a later version.",...this.options.problem});return x.format(s,e,t)}return e}};var yp=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function bp(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(bp,"digestMessage");var wp=i(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 bp(JSON.stringify(r)),s=new URL(n.url),a=new URLSearchParams(s.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=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function Ka(n,e,t,r){y("policy.inbound.caching");let o=await ge(r,t.cacheId,t),s=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await wp(n,t),c=await s.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=t.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(n.method.toUpperCase()))return;let f=t?.expirationSecondsTtl??60,h=new Response(p.body,p);yp.forEach(A=>h.headers.delete(A)),h.headers.set("cache-control",`s-maxage=${f}`),e.waitUntil(s.put(u,h))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}i(Ka,"CachingInboundPolicy");var Ya=i(async(n,e,t,r)=>{if(y("policy.inbound.change-method"),!t.method)throw new m(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new re(n,{method:t.method})},"ChangeMethodInboundPolicy");var Xa=i(async(n,e,t)=>{y("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 re(n,{headers:o})},"ClearHeadersInboundPolicy");var Qa=i(async(n,e,t,r)=>{y("policy.outbound.clear-headers");let o=[...r.exclude??[]],s=new Headers;return o.forEach(u=>{let c=n.headers.get(u);c&&s.set(u,c)}),new Response(n.body,{headers:s,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var eu=i(async(n,e,t,r)=>{y("policy.inbound.clerk-jwt-auth");let o=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),s=new URL(o);return s.pathname="/.well-known/jwks.json",ye(n,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var tu=i(async(n,e,t,r)=>{if(y("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 ye(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 nu=i(async(n,e,t,r)=>{if(y("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new m(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=be.instance,s=Wt(t.policies,o?.routeData.policies);return Po(s)(n,e)},"CompositeInboundPolicy");var ru=i(async(n,e,t,r)=>{y("policy.inbound.curity-phantom-token-auth");let o=n.headers.get("Authorization");if(!o)return x.unauthorized(n,e,{detail:"No authorization header"});let s=Rp(o);if(!s)return x.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await ge(r,void 0,t),u=new de(a,e),c=await u.get(s);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="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(s,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),x.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):x.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function Rp(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(Rp,"getToken");var ou=i(async(n,e,t,r)=>(y("policy.inbound.firebase-jwt-auth"),oe(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),ye(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 iu=i(async(n,e,t)=>{y("policy.inbound.form-data-to-json");let r="application/x-www-form-urlencoded",o="multipart/form-data",s=n.headers.get("content-type")?.toLowerCase();if(!s||![o,r].includes(s))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 re(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var kt="__unknown__",su=i(async(n,e,t,r)=>{y("policy.inbound.geo-filter");let o={allow:{countries:Mt(t.allow?.countries,"allow.countries",r),regionCodes:Mt(t.allow?.regionCodes,"allow.regionCode",r),asns:Mt(t.allow?.asns,"allow.asOrganization",r)},block:{countries:Mt(t.block?.countries,"block.countries",r),regionCodes:Mt(t.block?.regionCodes,"block.regionCode",r),asns:Mt(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??kt,a=e.incomingRequestProperties.regionCode?.toLowerCase()??kt,u=e.incomingRequestProperties.asn?.toString()??kt,c=o.ignoreUnknown&&s===kt,l=o.ignoreUnknown&&a===kt,d=o.ignoreUnknown&&u===kt,p=o.allow.countries,f=o.allow.regionCodes,h=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||f.length>0&&!f.includes(a)&&!l||h.length>0&&!h.includes(u)&&!d)return Nt(n,e,r,s,a,u);let A=o.block.countries,P=o.block.regionCodes,C=o.block.asns;return A.length>0&&A.includes(s)&&!c||P.length>0&&P.includes(a)&&!l||C.length>0&&C.includes(u)&&!d?Nt(n,e,r,s,a,u):n},"GeoFilterInboundPolicy");function Nt(n,e,t,r,o,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${s}')`),x.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:s}})}i(Nt,"blockedResponse");function Mt(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[]`)}i(Mt,"toLowerStringArray");var au=i(async(n,e,t)=>{y("policy.inbound.jwt-scope-validation");let r=n.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(r,t.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var cu=i(async(n,e,t,r)=>{y("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return gi(r,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(o),a=[];if(s.length===0)return gi(r,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[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 uu(a[u])}else return a.length>0?uu(a[0]):gi(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 uu(n){let e=JSON.stringify(n.exampleValue,null,2),t=new Headers;switch(t.set("Content-Type",n.contentName),n.responseName){case"1XX":return new Response(e,{status:100,headers:t});case"2XX":return new Response(e,{status:200,headers:t});case"3XX":return new Response(e,{status:300,headers:t});case"4XX":return new Response(e,{status:400,headers:t});case"5XX":case"default":return new Response(e,{status:500,headers:t});default:return new Response(e,{status:Number(n.responseName),headers:t})}}i(uu,"generateResponse");var gi=i((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 Pp="Incoming",Ep={logRequestBody:!0,logResponseBody:!0};function lu(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}i(lu,"headersToObject");function du(){return new Date().toISOString()}i(du,"timestamp");var fi=new WeakMap,Ip={};function gu(n,e){let t=fi.get(n);t||(t=Ip);let r=Object.assign({...t},e);fi.set(n,r)}i(gu,"setMoesifContext");async function pu(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}i(pu,"readBody");var xp={},hi;function mu(){if(!hi)throw new L("Invalid State - no _lastLogger");return hi}i(mu,"getLastLogger");function Tp(n){let e=xp[n];return e||(e=new Q("moesif-inbound",100,async t=>{let r=JSON.stringify(t);mu().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||mu().error({status:o.status,body:await o.text()})})),e}i(Tp,"getDispatcher");async function fu(n,e,t,r){y("policy.inbound.moesif-analytics"),hi=e.log;let o=du(),s=Object.assign(Ep,t);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await pu(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Tp(s.applicationId),d=n.headers.get("true-client-ip"),p=fi.get(e)??{},f={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:lu(n.headers)},h=s.logResponseBody?await pu(u,e):void 0,A={time:du(),status:u.status,headers:lu(u.headers),body:h},P={request:f,response:A,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Pp};l.enqueue(P),e.waitUntil(l.waitUntilFlushed())}),n}i(fu,"MoesifInboundPolicy");async function hu(n,e,t,r){let o=ee.getLogger(n),{authApiJWT:s,meteringServiceUrl:a}=g.instance,u;try{let l=await F.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error loading subscription. ${l.status} - ${p}`),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]}i(hu,"loadSubscription");async function yu(n,e,t,r,o){let{authApiJWT:s,meteringServiceUrl:a}=g.instance,u=ee.getLogger(n);try{let c=await F.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"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)}}i(yu,"consumeSubcriptionQuotas");var vp=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function br(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}}i(br,"validateMeters");function bu(n,e){if(n)try{if(n.length===0)throw new m("Must set valid subscription statuses");let t=at(n),r=[];for(let o of t)vp.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"]}i(bu,"parseAllowedSubscriptionStatuses");function wu(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}}i(wu,"compareMeters");var wr=class extends fe{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return he.get(e,Ft)}static setMeters(e,t){br(t,"setMeters"),he.set(e,mn,t)}constructor(e,t){super(e,t),y("policy.inbound.monetization")}async handler(e,t){oe(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=bt(this.options.meterOnStatusCodes),s=he.get(t,mn),a={...this.options.meters,...s};br(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=bu(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(P,C,H)=>{let N=he.get(H,Ft);if((this.options.allowRequestsWithoutSubscription??!1)&&!N){H.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let Z=he.get(H,mn),$={...this.options.meters,...Z};if(br($,this.policyName),o.includes(P.status)&&N&&$){H.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${N.id}' with meters '${JSON.stringify($)} on response status '${P.status}'`);let{metersInSubscription:I,metersNotInSubscription:U}=wu(N.meters,$);if(U&&Object.keys(U).length>0){let G=Object.keys(U);H.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${G}'`)}await yu(H,N.id,this.policyName,this.options.bucketId,I)}});let l=e.user;if(!l)return u?e:x.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await hu(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`),he.set(t,Ft,p));let f=he.get(t,Ft);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 A=Object.keys(a).filter(P=>!Object.keys(f.meters).includes(P));if(A.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${A.join(", ")}`),x.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${A.join(", ")}`,title:"Quota Exceeded"});for(let P of Object.keys(a))if(f.meters[P].available<=0&&!r)return x.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${P}'`,title:"Quota Exceeded"});return e}};var Ru=i(async(n,e,t,r)=>(y("policy.inbound.okta-jwt-auth"),ye(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"OktaJwtInboundPolicy");var Pu=require("jose");var yi,Eu=i(async(n,e,t,r)=>{if(y("policy.inbound.propel-auth-jwt-auth"),!yi)try{yi=await(0,Pu.importSPKI)(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return ye(n,e,{issuer:t.authUrl,secret:yi,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Su=Be(Ze());var xu=Be(Ze());var Iu=(0,xu.debug)("zuplo:policies:RateLimitInboundPolicy"),Tu=i(async(n,e,t,r)=>{let o=ee.getLogger(e),s=i(($,I)=>{let U={};return(!$||$==="retry-after")&&(U[Ot]=I.toString()),x.tooManyRequests(n,e,void 0,U)},"rateLimited"),u=await vt(r,t)(n,e,r),c=u.key,l=u.requestsAllowed??t.requestsAllowed,d=u.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",f=St(r,o),A=`rate-limit${g.instance.isTestMode?g.instance.build.BUILD_ID:""}/${r}/${c}`,P=await ge(r,void 0,t),C=new de(P,e),H=Kn(A,d,f,e.requestId),N;i(async()=>{let $=await H;if($.count>l){let I=Date.now()+$.ttlSeconds*1e3;C.put(A,I,$.ttlSeconds),Iu(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${A}' (async mode)`),N=s(p,$.ttlSeconds)}},"asyncCheck")();let Z=await C.get(A);if(Z!==void 0&&Z>Date.now()){Iu(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${A}' (async mode)`);let $=Math.round((Z-Date.now())/1e3);return s(p,$)}return e.addResponseSendingHook(async $=>N??$),n},"AsyncRateLimitInboundPolicy");var vu=(0,Su.debug)("zuplo:policies:RateLimitInboundPolicy"),Sp="strict",bi=i(async(n,e,t,r)=>{if(y("policy.inbound.rate-limit"),(t.mode??Sp)==="async")return Tu(n,e,t,r);let s=Date.now(),a=ee.getLogger(e),u=i((l,d)=>{if(t.throwOnFailure)throw new Y(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[Ot]=d.toString()),x.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await vt(r,t)(n,e,r),p=d.key,f=d.requestsAllowed??t.requestsAllowed,h=d.timeWindowMinutes??t.timeWindowMinutes,A=t.headerMode??"retry-after",P=St(r,a),H=`rate-limit${g.instance.isTestMode?g.instance.build.BUILD_ID:""}/${r}/${p}`,N=await Kn(H,h,P,e.requestId);return N.count>f?(vu(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${H}' (strict mode)`),c(A,N.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-s;vu(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var wi;function Ou(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}i(Ou,"headersToNameValuePairs");function Op(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}i(Op,"queryToNameValueParis");function Cp(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}i(Cp,"parseIntOrUndefined");var Cu={};async function Au(n,e,t,r){y("policy.inbound.readme-metrics");let o=new Date,s=Date.now();return wi||(wi={name:"zuplo",version:g.instance.build.ZUPLO_VERSION,comment:`zuplo/${g.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?st(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?st(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:g.instance.isWorkingCopy||g.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:wi,entries:[{startedDateTime:o.toISOString(),time:Date.now()-s,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:Ou(n.headers),queryString:Op(n.query)},response:{status:a.status,statusText:a.statusText,headers:Ou(a.headers),content:{size:Cp(n.headers.get("content-length"))}}}]}}},d=Cu[t.apiKey];if(!d){let p=t.apiKey;d=new Q("readme-metering-inbound-policy",10,async f=>{try{let h=t.url??"https://metrics.readme.io/request",A=await F.fetch(h,{method:"POST",body:JSON.stringify(f),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});A.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${A.status}: '${await A.text()}'`)}catch(h){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${h.message}'`),h}}),Cu[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}i(Au,"ReadmeMetricsInboundPolicy");var _u=i(async(n,e,t,r)=>{y("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 s=new Headers(n.headers);return o.forEach(u=>{s.delete(u)}),new re(n,{headers:s})},"RemoveHeadersInboundPolicy");var Lu=i(async(n,e,t,r,o)=>{y("policy.outbound.remove-headers");let s=r?.headers;if(!s||!Array.isArray(s)||s.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 s.forEach(c=>{a.delete(c)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var ku=i(async(n,e,t,r)=>{y("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 s=new URL(n.url);return o.forEach(u=>{s.searchParams.delete(u)}),new re(s.toString(),n)},"RemoveQueryParamsInboundPolicy");var Nu=i(async(n,e,t,r)=>{y("policy.outbound.replace-string");let o=await n.text(),s=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(s,r.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var Mu=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Du=i(async(n,e,t)=>{y("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"),s=o!==null?parseInt(o):void 0;return s&&!isNaN(s)&&s>t.maxSizeInBytes?Mu():s&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?Mu():n},"RequestSizeLimitInboundPolicy");function Uu(n,e,t){return`_${et(n+"_"+e+"_"+t)}`}i(Uu,"getRawOperationDataIdentifierName");function Rr(n,e,t,r){return`_${et(n.toLowerCase())}_`+e.toLowerCase()+"_"+t.toLowerCase()+`_${r.toLowerCase()}`}i(Rr,"getIdForParameterSchema");function Pr(n,e,t){return`_${et(n.toLowerCase())}_`+e.toLowerCase()+`_rb_${et(t.toLowerCase())}`}i(Pr,"getIdForRequestBodySchema");function Hu(n,e){return`_${et(n)}__${et(e)}`}i(Hu,"getIdForRefSchema");function et(n){let e=[];for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(n.charAt(t)):e.push("_")}return e.join("")}i(et,"sanitizedIdentifierName");var Dt=i(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"),Ut=i((n,e,t,r,o)=>{let s=[],a=!0,u=[];return n.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,s.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=Rr(t,r,o,c.name),p=be.instance.schemaValidator[d],f=p(e[c.name]),h=Ri(p.errors);f||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${h.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),Le=i((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),ke=i(n=>n==="log-only"||n==="reject-and-log","shouldLog"),Ne=i(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),Ri=i(n=>n?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function Zu(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(h){let A=`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:`${A}, see errors property for more details`,errors:`${h}`});if(ke(t.validateBody)&&Le(n,t.logLevel??"info",A,[r],h),Ne(t.validateBody))return P}if(!e.headers.get("Content-Type")){let h=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,A=x.badRequest(e,n,{detail:h});return ke(t.validateBody)&&Le(n,t.logLevel??"info",h,[r],[h]),Ne(t.validateBody)?A:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=Pr(n.route.path,e.method,o),u=be.instance.schemaValidator[a];if(!u){let h=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,A=x.badRequest(e,n,{detail:h});return ke(t.validateBody)&&Le(n,t.logLevel??"info",h,[r],[h]),Ne(t.validateBody)?A:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Ri(l),f=x.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(ke(t.validateBody)&&Le(n,t.logLevel??"info",d,[r],p),Ne(t.validateBody))return f}i(Zu,"handleBodyValidation");function qu(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Dt(n),s=Ut(o.filter(a=>a.location==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=x.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:s.errors});if(ke(t.validateHeaders)&&Le(n,t.logLevel??"info",a,s.invalidValues,s.errors),Ne(t.validateHeaders))return u}}i(qu,"handleHeadersValidation");function Fu(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=Dt(n),o=Ut(r.filter(s=>s.location==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let s="Path parameters validation failed",a=x.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(ke(t.validatePathParameters)&&Le(n,t.logLevel??"info",s,o.invalidValues,o.errors),Ne(t.validatePathParameters))return a}}i(Fu,"handlePathParameterValidation");function $u(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=Dt(n),o=Ut(r.filter(s=>s.location==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let s="Query parameters validation failed",a=x.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(ke(t.validateQueryParameters)&&Le(n,t.logLevel??"info",s,o.invalidValues,o.errors),Ne(t.validateQueryParameters))return a}}i($u,"handleQueryParameterValidation");var Pi=i(async(n,e,t)=>{y("policy.inbound.request-validation");let r=$u(e,n,t);if(r!==void 0||(r=Fu(e,n,t),r!==void 0)||(r=qu(e,n,t),r!==void 0))return r;let o=await Zu(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),ju=Pi;var Bu=i(async(n,e,t,r)=>{if(y("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 s=n.headers.get("origin");if(!s||!o.includes(s)){let a=t.failureDetail??"Forbidden";return x.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var zu=i(async(n,e,t)=>(y("policy.inbound.set-body"),new re(n,{body:t.body})),"SetBodyInboundPolicy");var Vu=i(async(n,e,t,r)=>{y("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 s=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;(!s.has(u.name)||c)&&s.set(u.name,u.value)}),new re(n,{headers:s})},"SetHeadersInboundPolicy");var Gu=i(async(n,e,t,r,o)=>{y("policy.outbound.set-headers");let s=r.headers;if(!s||!Array.isArray(s)||s.length==0)throw new m(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return s.forEach(c=>{if(!c.name||c.name.length===0)throw new m(`SetHeadersOutboundPolicy '${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 Wu=i(async(n,e,t,r)=>{y("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 s=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;(!s.searchParams.has(u.name)||c)&&s.searchParams.set(u.name,u.value)}),new re(s.toString(),n)},"SetQueryParamsInboundPolicy");var Ju=i(async(n,e,t,r,o)=>{if(y("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 Ap=i(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),Ku=i(async(n,e,t,r)=>{if(y("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 Ap(t.sleepInMs),n},"SleepInboundPolicy");var Yu=i(async(n,e,t,r)=>{y("policy.inbound.supabase-jwt-auth"),oe(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},s=await ye(n,e,o,r);if(s instanceof Response)return s;if(!(s instanceof re))throw new Y("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return s;let u=n.user?.data.app_metadata;if(!u)throw new L(`SupabaseJwtInboundPolicy policy '${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(", ")}`}):s},"SupabaseJwtInboundPolicy");var Xu=i(async(n,e,t,r)=>{y("policy.inbound.upstream-azure-ad-service-auth"),oe(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await ge(r,void 0,t),s=new de(o,e),a=await s.get(r);if(!a){let u=await _p(t,e);s.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 _p(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await Ie({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 s=await r.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new L("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 L("Response returned from Azure AD is not in the expected format.")}i(_p,"getAccessToken");var Qu="https://accounts.google.com/o/oauth2/token",Ei,ec=i(async(n,e,t,r)=>{y("policy.inbound.upstream-firebase-admin-auth"),oe(t,r).required("serviceAccountJson","string"),Ei||(Ei=await ve.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(" ")},s=await ge(r,void 0,t),a=new de(s,e),u=await a.get(r);if(!u){let c=await De({serviceAccount:Ei,audience:Qu,payload:o}),l=await _n(Qu,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(r,u,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var Lp="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",kp=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Ii,tc=i(async(n,e,t,r)=>{if(y("policy.inbound.upstream-firebase-user-auth"),oe(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(kp.indexOf(p)!==-1)throw new m(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}Ii||(Ii=await ve.init(t.serviceAccountJson));let s=t.userId;if(!s&&!t.userIdPropertyPath){if(!n.user)throw new L("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new L(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=st(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new L(`Unable to determine user from for the policy ${r}`);let a=await ge(r,void 0,t),u=new de(a,e),c={uid:s,claims:o},l=await lr(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await De({serviceAccount:Ii,audience:Lp,payload:c}),f=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,h=await Ys(f,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!h.idToken)throw new L("Invalid token response from Firebase");d=h.idToken,u.put(l,d,(h.expiresIn?parseInt(h.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var xi,nc=i(async(n,e,t,r)=>{y("policy.inbound.upstream-gcp-jwt"),oe(t,r).required("audience","string").required("serviceAccountJson","string"),xi||(xi=await ve.init(t.serviceAccountJson));let o=await De({serviceAccount:xi,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var rc="https://www.googleapis.com/oauth2/v4/token",Ti,oc=i(async(n,e,t,r)=>{y("policy.inbound.upstream-gcp-service-auth"),oe(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Ti||(Ti=await ve.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=at(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 s=await ge(r,void 0,t),a;t.useMemoryCacheOnly?a=new dt(s):a=new de(s,e);let u=await a.get(r);if(!u){let c=await De({serviceAccount:Ti,audience:rc,payload:o}),l=await _n(rc,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(r,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var ic=i(async(n,e,t)=>{y("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 Y("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 sc=i(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=i((P,C)=>e(P,"name",{value:C,configurable:!0}),"__name"),o=i((P,C)=>i(function(){return C||(0,P[t(P)[0]])((C={exports:{}}).exports,C),C.exports},"__require"),"__commonJS"),s=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(N,B){return B},attributeValueProcessor:function(N,B){return B},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(N,B,Z){return N}},H=r(function(N){return Object.assign({},C,N)},"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",N="["+C+"]["+H+"]*",B=new RegExp("^"+N+"$"),Z=r(function(I,U){let G=[],W=U.exec(I);for(;W;){let S=[];S.startIndex=U.lastIndex-W[0].length;let T=W.length;for(let q=0;q<T;q++)S.push(W[q]);G.push(S),W=U.exec(I)}return G},"getAllMatches"),$=r(function(I){let U=B.exec(I);return!(U===null||typeof U>"u")},"isName");P.isExist=function(I){return typeof I<"u"},P.isEmptyObject=function(I){return Object.keys(I).length===0},P.merge=function(I,U,G){if(U){let W=Object.keys(U),S=W.length;for(let T=0;T<S;T++)G==="strict"?I[W[T]]=[U[W[T]]]:I[W[T]]=U[W[T]]}},P.getValue=function(I){return P.isExist(I)?I:""},P.isName=$,P.getAllMatches=Z,P.nameRegexp=N}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(P,C){"use strict";var H=class{static{i(this,"XmlNode")}static{r(this,"XmlNode")}constructor(N){this.tagname=N,this.child=[],this[":@"]={}}add(N,B){N==="__proto__"&&(N="#__proto__"),this.child.push({[N]:B})}addChild(N){N.tagname==="__proto__"&&(N.tagname="#__proto__"),N[":@"]&&Object.keys(N[":@"]).length>0?this.child.push({[N.tagname]:N.child,":@":N[":@"]}):this.child.push({[N.tagname]:N.child})}};C.exports=H}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(P,C){var H=a();function N(S,T){let q={};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 ce=1,X=!1,te=!1,Oe="";for(;T<S.length;T++)if(S[T]==="<"&&!te){if(X&&$(S,T))T+=7,[entityName,val,T]=B(S,T+1),val.indexOf("&")===-1&&(q[W(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(X&&I(S,T))T+=8;else if(X&&U(S,T))T+=8;else if(X&&G(S,T))T+=9;else if(Z)te=!0;else throw new Error("Invalid DOCTYPE");ce++,Oe=""}else if(S[T]===">"){if(te?S[T-1]==="-"&&S[T-2]==="-"&&(te=!1,ce--):ce--,ce===0)break}else S[T]==="["?X=!0:Oe+=S[T];if(ce!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:q,i:T}}i(N,"readDocType"),r(N,"readDocType");function B(S,T){let q="";for(;T<S.length&&S[T]!=="'"&&S[T]!=='"';T++)q+=S[T];if(q=q.trim(),q.indexOf(" ")!==-1)throw new Error("External entites are not supported");let ce=S[T++],X="";for(;T<S.length&&S[T]!==ce;T++)X+=S[T];return[q,X,T]}i(B,"readEntityExp"),r(B,"readEntityExp");function Z(S,T){return S[T+1]==="!"&&S[T+2]==="-"&&S[T+3]==="-"}i(Z,"isComment"),r(Z,"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"}i($,"isEntity"),r($,"isEntity");function I(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"}i(I,"isElement"),r(I,"isElement");function U(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"}i(U,"isAttlist"),r(U,"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"}i(G,"isNotation"),r(G,"isNotation");function W(S){if(H.isName(S))return S;throw new Error(`Invalid entity name ${S}`)}i(W,"validateEntityName"),r(W,"validateEntityName"),C.exports=N}}),l=o({"../../node_modules/strnum/strnum.js"(P,C){var H=/^[-+]?0x[a-fA-F0-9]+$/,N=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var B={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function Z(I,U={}){if(U=Object.assign({},B,U),!I||typeof I!="string")return I;let G=I.trim();if(U.skipLike!==void 0&&U.skipLike.test(G))return I;if(U.hex&&H.test(G))return Number.parseInt(G,16);{let W=N.exec(G);if(W){let S=W[1],T=W[2],q=$(W[3]),ce=W[4]||W[6];if(!U.leadingZeros&&T.length>0&&S&&G[2]!==".")return I;if(!U.leadingZeros&&T.length>0&&!S&&G[1]!==".")return I;{let X=Number(G),te=""+X;return te.search(/[eE]/)!==-1||ce?U.eNotation?X:I:G.indexOf(".")!==-1?te==="0"&&q===""||te===q||S&&te==="-"+q?X:I:T?q===te||S+q===te?X:I:G===te||G===S+te?X:I}}else return I}}i(Z,"toNumber"),r(Z,"toNumber");function $(I){return I&&I.indexOf(".")!==-1&&(I=I.replace(/0+$/,""),I==="."?I="0":I[0]==="."?I="0"+I:I[I.length-1]==="."&&(I=I.substr(0,I.length-1))),I}i($,"trimZeros"),r($,"trimZeros"),C.exports=Z}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(P,C){"use strict";var H=a(),N=u(),B=c(),Z=l(),$=class{static{i(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:(E,_)=>String.fromCharCode(Number.parseInt(_,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(E,_)=>String.fromCharCode(Number.parseInt(_,16))}},this.addExternalEntities=I,this.parseXml=T,this.parseTextData=U,this.resolveNameSpace=G,this.buildAttributesMap=S,this.isItStopNode=te,this.replaceEntitiesValue=ce,this.readStopNodeData=V,this.saveTextToParentTag=X,this.addChild=q}};function I(R){let E=Object.keys(R);for(let _=0;_<E.length;_++){let z=E[_];this.lastEntities[z]={regex:new RegExp("&"+z+";","g"),val:R[z]}}}i(I,"addExternalEntities"),r(I,"addExternalEntities");function U(R,E,_,z,k,M,ne){if(R!==void 0&&(this.options.trimValues&&!z&&(R=R.trim()),R.length>0)){ne||(R=this.replaceEntitiesValue(R));let j=this.options.tagValueProcessor(E,R,_,k,M);return j==null?R:typeof j!=typeof R||j!==R?j:this.options.trimValues?le(R,this.options.parseTagValue,this.options.numberParseOptions):R.trim()===R?le(R,this.options.parseTagValue,this.options.numberParseOptions):R}}i(U,"parseTextData"),r(U,"parseTextData");function G(R){if(this.options.removeNSPrefix){let E=R.split(":"),_=R.charAt(0)==="/"?"/":"";if(E[0]==="xmlns")return"";E.length===2&&(R=_+E[1])}return R}i(G,"resolveNameSpace"),r(G,"resolveNameSpace");var W=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function S(R,E,_){if(!this.options.ignoreAttributes&&typeof R=="string"){let z=H.getAllMatches(R,W),k=z.length,M={};for(let ne=0;ne<k;ne++){let j=this.resolveNameSpace(z[ne][1]),D=z[ne][4],ae=this.options.attributeNamePrefix+j;if(j.length)if(this.options.transformAttributeName&&(ae=this.options.transformAttributeName(ae)),ae==="__proto__"&&(ae="#__proto__"),D!==void 0){this.options.trimValues&&(D=D.trim()),D=this.replaceEntitiesValue(D);let ie=this.options.attributeValueProcessor(j,D,E);ie==null?M[ae]=D:typeof ie!=typeof D||ie!==D?M[ae]=ie:M[ae]=le(D,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(M[ae]=!0)}if(!Object.keys(M).length)return;if(this.options.attributesGroupName){let ne={};return ne[this.options.attributesGroupName]=M,ne}return M}}i(S,"buildAttributesMap"),r(S,"buildAttributesMap");var T=r(function(R){R=R.replace(/\r\n?/g,`
|
|
72
|
+
`);let E=new N("!xml"),_=E,z="",k="";for(let M=0;M<R.length;M++)if(R[M]==="<")if(R[M+1]==="/"){let j=b(R,">",M,"Closing Tag is not closed."),D=R.substring(M+2,j).trim();if(this.options.removeNSPrefix){let Ae=D.indexOf(":");Ae!==-1&&(D=D.substr(Ae+1))}this.options.transformTagName&&(D=this.options.transformTagName(D)),_&&(z=this.saveTextToParentTag(z,_,k));let ae=k.substring(k.lastIndexOf(".")+1);if(D&&this.options.unpairedTags.indexOf(D)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${D}>`);let ie=0;ae&&this.options.unpairedTags.indexOf(ae)!==-1?(ie=k.lastIndexOf(".",k.lastIndexOf(".")-1),this.tagsNodeStack.pop()):ie=k.lastIndexOf("."),k=k.substring(0,ie),_=this.tagsNodeStack.pop(),z="",M=j}else if(R[M+1]==="?"){let j=O(R,M,!1,"?>");if(!j)throw new Error("Pi Tag is not closed.");if(z=this.saveTextToParentTag(z,_,k),!(this.options.ignoreDeclaration&&j.tagName==="?xml"||this.options.ignorePiTags)){let D=new N(j.tagName);D.add(this.options.textNodeName,""),j.tagName!==j.tagExp&&j.attrExpPresent&&(D[":@"]=this.buildAttributesMap(j.tagExp,k,j.tagName)),this.addChild(_,D,k)}M=j.closeIndex+1}else if(R.substr(M+1,3)==="!--"){let j=b(R,"-->",M+4,"Comment is not closed.");if(this.options.commentPropName){let D=R.substring(M+4,j-2);z=this.saveTextToParentTag(z,_,k),_.add(this.options.commentPropName,[{[this.options.textNodeName]:D}])}M=j}else if(R.substr(M+1,2)==="!D"){let j=B(R,M);this.docTypeEntities=j.entities,M=j.i}else if(R.substr(M+1,2)==="!["){let j=b(R,"]]>",M,"CDATA is not closed.")-2,D=R.substring(M+9,j);z=this.saveTextToParentTag(z,_,k);let ae=this.parseTextData(D,_.tagname,k,!0,!1,!0,!0);ae==null&&(ae=""),this.options.cdataPropName?_.add(this.options.cdataPropName,[{[this.options.textNodeName]:D}]):_.add(this.options.textNodeName,ae),M=j+2}else{let j=O(R,M,this.options.removeNSPrefix),D=j.tagName,ae=j.rawTagName,ie=j.tagExp,Ae=j.attrExpPresent,Si=j.closeIndex;this.options.transformTagName&&(D=this.options.transformTagName(D)),_&&z&&_.tagname!=="!xml"&&(z=this.saveTextToParentTag(z,_,k,!1));let Oi=_;if(Oi&&this.options.unpairedTags.indexOf(Oi.tagname)!==-1&&(_=this.tagsNodeStack.pop(),k=k.substring(0,k.lastIndexOf("."))),D!==E.tagname&&(k+=k?"."+D:D),this.isItStopNode(this.options.stopNodes,k,D)){let Ce="";if(ie.length>0&&ie.lastIndexOf("/")===ie.length-1)M=j.closeIndex;else if(this.options.unpairedTags.indexOf(D)!==-1)M=j.closeIndex;else{let _r=this.readStopNodeData(R,ae,Si+1);if(!_r)throw new Error(`Unexpected end of ${ae}`);M=_r.i,Ce=_r.tagContent}let Ar=new N(D);D!==ie&&Ae&&(Ar[":@"]=this.buildAttributesMap(ie,k,D)),Ce&&(Ce=this.parseTextData(Ce,D,k,!0,Ae,!0,!0)),k=k.substr(0,k.lastIndexOf(".")),Ar.add(this.options.textNodeName,Ce),this.addChild(_,Ar,k)}else{if(ie.length>0&&ie.lastIndexOf("/")===ie.length-1){D[D.length-1]==="/"?(D=D.substr(0,D.length-1),k=k.substr(0,k.length-1),ie=D):ie=ie.substr(0,ie.length-1),this.options.transformTagName&&(D=this.options.transformTagName(D));let Ce=new N(D);D!==ie&&Ae&&(Ce[":@"]=this.buildAttributesMap(ie,k,D)),this.addChild(_,Ce,k),k=k.substr(0,k.lastIndexOf("."))}else{let Ce=new N(D);this.tagsNodeStack.push(_),D!==ie&&Ae&&(Ce[":@"]=this.buildAttributesMap(ie,k,D)),this.addChild(_,Ce,k),_=Ce}z="",M=Si}}else z+=R[M];return E.child},"parseXml");function q(R,E,_){let z=this.options.updateTag(E.tagname,_,E[":@"]);z===!1||(typeof z=="string"&&(E.tagname=z),R.addChild(E))}i(q,"addChild"),r(q,"addChild");var ce=r(function(R){if(this.options.processEntities){for(let E in this.docTypeEntities){let _=this.docTypeEntities[E];R=R.replace(_.regx,_.val)}for(let E in this.lastEntities){let _=this.lastEntities[E];R=R.replace(_.regex,_.val)}if(this.options.htmlEntities)for(let E in this.htmlEntities){let _=this.htmlEntities[E];R=R.replace(_.regex,_.val)}R=R.replace(this.ampEntity.regex,this.ampEntity.val)}return R},"replaceEntitiesValue");function X(R,E,_,z){return R&&(z===void 0&&(z=Object.keys(E.child).length===0),R=this.parseTextData(R,E.tagname,_,!1,E[":@"]?Object.keys(E[":@"]).length!==0:!1,z),R!==void 0&&R!==""&&E.add(this.options.textNodeName,R),R=""),R}i(X,"saveTextToParentTag"),r(X,"saveTextToParentTag");function te(R,E,_){let z="*."+_;for(let k in R){let M=R[k];if(z===M||E===M)return!0}return!1}i(te,"isItStopNode"),r(te,"isItStopNode");function Oe(R,E,_=">"){let z,k="";for(let M=E;M<R.length;M++){let ne=R[M];if(z)ne===z&&(z="");else if(ne==='"'||ne==="'")z=ne;else if(ne===_[0])if(_[1]){if(R[M+1]===_[1])return{data:k,index:M}}else return{data:k,index:M};else ne===" "&&(ne=" ");k+=ne}}i(Oe,"tagExpWithClosingIndex"),r(Oe,"tagExpWithClosingIndex");function b(R,E,_,z){let k=R.indexOf(E,_);if(k===-1)throw new Error(z);return k+E.length-1}i(b,"findClosingIndex"),r(b,"findClosingIndex");function O(R,E,_,z=">"){let k=Oe(R,E+1,z);if(!k)return;let M=k.data,ne=k.index,j=M.search(/\s/),D=M,ae=!0;j!==-1&&(D=M.substring(0,j),M=M.substring(j+1).trimStart());let ie=D;if(_){let Ae=D.indexOf(":");Ae!==-1&&(D=D.substr(Ae+1),ae=D!==k.data.substr(Ae+1))}return{tagName:D,tagExp:M,closeIndex:ne,attrExpPresent:ae,rawTagName:ie}}i(O,"readTagExp"),r(O,"readTagExp");function V(R,E,_){let z=_,k=1;for(;_<R.length;_++)if(R[_]==="<")if(R[_+1]==="/"){let M=b(R,">",_,`${E} is not closed`);if(R.substring(_+2,M).trim()===E&&(k--,k===0))return{tagContent:R.substring(z,_),i:M};_=M}else if(R[_+1]==="?")_=b(R,"?>",_+1,"StopNode is not closed.");else if(R.substr(_+1,3)==="!--")_=b(R,"-->",_+3,"StopNode is not closed.");else if(R.substr(_+1,2)==="![")_=b(R,"]]>",_,"StopNode is not closed.")-2;else{let M=O(R,_,">");M&&((M&&M.tagName)===E&&M.tagExp[M.tagExp.length-1]!=="/"&&k++,_=M.closeIndex)}}i(V,"readStopNodeData"),r(V,"readStopNodeData");function le(R,E,_){if(E&&typeof R=="string"){let z=R.trim();return z==="true"?!0:z==="false"?!1:Z(R,_)}else return H.isExist(R)?R:""}i(le,"parseValue"),r(le,"parseValue"),C.exports=$}}),p=o({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(P){"use strict";function C($,I){return H($,I)}i(C,"prettify"),r(C,"prettify");function H($,I,U){let G,W={};for(let S=0;S<$.length;S++){let T=$[S],q=N(T),ce="";if(U===void 0?ce=q:ce=U+"."+q,q===I.textNodeName)G===void 0?G=T[q]:G+=""+T[q];else{if(q===void 0)continue;if(T[q]){let X=H(T[q],I,ce),te=Z(X,I);T[":@"]?B(X,T[":@"],ce,I):Object.keys(X).length===1&&X[I.textNodeName]!==void 0&&!I.alwaysCreateTextNode?X=X[I.textNodeName]:Object.keys(X).length===0&&(I.alwaysCreateTextNode?X[I.textNodeName]="":X=""),W[q]!==void 0&&W.hasOwnProperty(q)?(Array.isArray(W[q])||(W[q]=[W[q]]),W[q].push(X)):I.isArray(q,ce,te)?W[q]=[X]:W[q]=X}}}return typeof G=="string"?G.length>0&&(W[I.textNodeName]=G):G!==void 0&&(W[I.textNodeName]=G),W}i(H,"compress"),r(H,"compress");function N($){let I=Object.keys($);for(let U=0;U<I.length;U++){let G=I[U];if(G!==":@")return G}}i(N,"propName"),r(N,"propName");function B($,I,U,G){if(I){let W=Object.keys(I),S=W.length;for(let T=0;T<S;T++){let q=W[T];G.isArray(q,U+"."+q,!0,!0)?$[q]=[I[q]]:$[q]=I[q]}}}i(B,"assignAttributes"),r(B,"assignAttributes");function Z($,I){let{textNodeName:U}=I,G=Object.keys($).length;return!!(G===0||G===1&&($[U]||typeof $[U]=="boolean"||$[U]===0))}i(Z,"isLeafTag"),r(Z,"isLeafTag"),P.prettify=C}}),f=o({"node_modules/fast-xml-parser/src/validator.js"(P){"use strict";var C=a(),H={allowBooleanAttributes:!1,unpairedTags:[]};P.validate=function(b,O){O=Object.assign({},H,O);let V=[],le=!1,R=!1;b[0]==="\uFEFF"&&(b=b.substr(1));for(let E=0;E<b.length;E++)if(b[E]==="<"&&b[E+1]==="?"){if(E+=2,E=B(b,E),E.err)return E}else if(b[E]==="<"){let _=E;if(E++,b[E]==="!"){E=Z(b,E);continue}else{let z=!1;b[E]==="/"&&(z=!0,E++);let k="";for(;E<b.length&&b[E]!==">"&&b[E]!==" "&&b[E]!==" "&&b[E]!==`
|
|
73
|
+
`&&b[E]!=="\r";E++)k+=b[E];if(k=k.trim(),k[k.length-1]==="/"&&(k=k.substring(0,k.length-1),E--),!X(k)){let j;return k.trim().length===0?j="Invalid space after '<'.":j="Tag '"+k+"' is an invalid name.",q("InvalidTag",j,te(b,E))}let M=U(b,E);if(M===!1)return q("InvalidAttr","Attributes for '"+k+"' have open quote.",te(b,E));let ne=M.value;if(E=M.index,ne[ne.length-1]==="/"){let j=E-ne.length;ne=ne.substring(0,ne.length-1);let D=W(ne,O);if(D===!0)le=!0;else return q(D.err.code,D.err.msg,te(b,j+D.err.line))}else if(z)if(M.tagClosed){if(ne.trim().length>0)return q("InvalidTag","Closing tag '"+k+"' can't have attributes or invalid starting.",te(b,_));{let j=V.pop();if(k!==j.tagName){let D=te(b,j.tagStartPos);return q("InvalidTag","Expected closing tag '"+j.tagName+"' (opened in line "+D.line+", col "+D.col+") instead of closing tag '"+k+"'.",te(b,_))}V.length==0&&(R=!0)}}else return q("InvalidTag","Closing tag '"+k+"' doesn't have proper closing.",te(b,E));else{let j=W(ne,O);if(j!==!0)return q(j.err.code,j.err.msg,te(b,E-ne.length+j.err.line));if(R===!0)return q("InvalidXml","Multiple possible root nodes found.",te(b,E));O.unpairedTags.indexOf(k)!==-1||V.push({tagName:k,tagStartPos:_}),le=!0}for(E++;E<b.length;E++)if(b[E]==="<")if(b[E+1]==="!"){E++,E=Z(b,E);continue}else if(b[E+1]==="?"){if(E=B(b,++E),E.err)return E}else break;else if(b[E]==="&"){let j=T(b,E);if(j==-1)return q("InvalidChar","char '&' is not expected.",te(b,E));E=j}else if(R===!0&&!N(b[E]))return q("InvalidXml","Extra text at the end",te(b,E));b[E]==="<"&&E--}}else{if(N(b[E]))continue;return q("InvalidChar","char '"+b[E]+"' is not expected.",te(b,E))}if(le){if(V.length==1)return q("InvalidTag","Unclosed tag '"+V[0].tagName+"'.",te(b,V[0].tagStartPos));if(V.length>0)return q("InvalidXml","Invalid '"+JSON.stringify(V.map(E=>E.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return q("InvalidXml","Start tag expected.",1);return!0};function N(b){return b===" "||b===" "||b===`
|
|
74
|
+
`||b==="\r"}i(N,"isWhiteSpace"),r(N,"isWhiteSpace");function B(b,O){let V=O;for(;O<b.length;O++)if(b[O]=="?"||b[O]==" "){let le=b.substr(V,O-V);if(O>5&&le==="xml")return q("InvalidXml","XML declaration allowed only at the start of the document.",te(b,O));if(b[O]=="?"&&b[O+1]==">"){O++;break}else continue}return O}i(B,"readPI"),r(B,"readPI");function Z(b,O){if(b.length>O+5&&b[O+1]==="-"&&b[O+2]==="-"){for(O+=3;O<b.length;O++)if(b[O]==="-"&&b[O+1]==="-"&&b[O+2]===">"){O+=2;break}}else if(b.length>O+8&&b[O+1]==="D"&&b[O+2]==="O"&&b[O+3]==="C"&&b[O+4]==="T"&&b[O+5]==="Y"&&b[O+6]==="P"&&b[O+7]==="E"){let V=1;for(O+=8;O<b.length;O++)if(b[O]==="<")V++;else if(b[O]===">"&&(V--,V===0))break}else if(b.length>O+9&&b[O+1]==="["&&b[O+2]==="C"&&b[O+3]==="D"&&b[O+4]==="A"&&b[O+5]==="T"&&b[O+6]==="A"&&b[O+7]==="["){for(O+=8;O<b.length;O++)if(b[O]==="]"&&b[O+1]==="]"&&b[O+2]===">"){O+=2;break}}return O}i(Z,"readCommentAndCDATA"),r(Z,"readCommentAndCDATA");var $='"',I="'";function U(b,O){let V="",le="",R=!1;for(;O<b.length;O++){if(b[O]===$||b[O]===I)le===""?le=b[O]:le!==b[O]||(le="");else if(b[O]===">"&&le===""){R=!0;break}V+=b[O]}return le!==""?!1:{value:V,index:O,tagClosed:R}}i(U,"readAttributeStr"),r(U,"readAttributeStr");var G=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function W(b,O){let V=C.getAllMatches(b,G),le={};for(let R=0;R<V.length;R++){if(V[R][1].length===0)return q("InvalidAttr","Attribute '"+V[R][2]+"' has no space in starting.",Oe(V[R]));if(V[R][3]!==void 0&&V[R][4]===void 0)return q("InvalidAttr","Attribute '"+V[R][2]+"' is without value.",Oe(V[R]));if(V[R][3]===void 0&&!O.allowBooleanAttributes)return q("InvalidAttr","boolean attribute '"+V[R][2]+"' is not allowed.",Oe(V[R]));let E=V[R][2];if(!ce(E))return q("InvalidAttr","Attribute '"+E+"' is an invalid name.",Oe(V[R]));if(!le.hasOwnProperty(E))le[E]=1;else return q("InvalidAttr","Attribute '"+E+"' is repeated.",Oe(V[R]))}return!0}i(W,"validateAttributeString"),r(W,"validateAttributeString");function S(b,O){let V=/\d/;for(b[O]==="x"&&(O++,V=/[\da-fA-F]/);O<b.length;O++){if(b[O]===";")return O;if(!b[O].match(V))break}return-1}i(S,"validateNumberAmpersand"),r(S,"validateNumberAmpersand");function T(b,O){if(O++,b[O]===";")return-1;if(b[O]==="#")return O++,S(b,O);let V=0;for(;O<b.length;O++,V++)if(!(b[O].match(/\w/)&&V<20)){if(b[O]===";")break;return-1}return O}i(T,"validateAmpersand"),r(T,"validateAmpersand");function q(b,O,V){return{err:{code:b,msg:O,line:V.line||V,col:V.col}}}i(q,"getErrorObject"),r(q,"getErrorObject");function ce(b){return C.isName(b)}i(ce,"validateAttrName"),r(ce,"validateAttrName");function X(b){return C.isName(b)}i(X,"validateTagName"),r(X,"validateTagName");function te(b,O){let V=b.substring(0,O).split(/\r?\n/);return{line:V.length,col:V[V.length-1].length+1}}i(te,"getLineNumberForPosition"),r(te,"getLineNumberForPosition");function Oe(b){return b.startIndex+b[1].length}i(Oe,"getPositionFromMatch"),r(Oe,"getPositionFromMatch")}}),h=o({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(P,C){var{buildOptions:H}=s(),N=d(),{prettify:B}=p(),Z=f(),$=class{static{i(this,"XMLParser")}static{r(this,"XMLParser")}constructor(I){this.externalEntities={},this.options=H(I)}parse(I,U){if(typeof I!="string")if(I.toString)I=I.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(U){U===!0&&(U={});let S=Z.validate(I,U);if(S!==!0)throw Error(`${S.err.msg}:${S.err.line}:${S.err.col}`)}let G=new N(this.options);G.addExternalEntities(this.externalEntities);let W=G.parseXml(I);return this.options.preserveOrder||W===void 0?W:B(W,this.options)}addEntity(I,U){if(U.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(I.indexOf("&")!==-1||I.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");if(U==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[I]=U}};C.exports=$}});let A=h();return new A(n)},"getXmlParser");var Er=class extends $e{static{i(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),y("policy.outbound.xml-to-json"),oe(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?bt(e.parseOnStatusCodes):void 0,this.parser=sc({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 L(c)}let s=new Headers(e.headers);return s.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:s})}};var Ir=class{static{i(this,"ServiceProviderImpl")}services=new Map;addService(e,t){if(this.services.get(e))throw new Y(`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 xr=class{static{i(this,"BackgroundDispatcher")}#e;constructor(e,t){if(!t||t.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new Q(t.name??"",t.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),Fn().waitUntil(this.#e.waitUntilFlushed())}};var ac=10,uc=3e4,Tr=class{static{i(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=uc,this.#r=ac}else{let r=t;this.#n=r.ttlSeconds*1e3,this.#o=r.loaderTimeoutSeconds?r.loaderTimeoutSeconds*1e3:uc,this.#r=ac}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 Np(()=>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);Fn().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 Np(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)}}i(Np,"waitUntilTrue");var vi=["sha-1","sha-256","sha-384","sha-512"],vr=class{static{i(this,"BaseCryptoBeta")}};var Sr=class extends vr{static{i(this,"WorkerCryptoBeta")}async digest(e,t){if(!vi.includes(e.toLowerCase()))throw new L(`Algorithm ${e} is not supported. Try using ${vi.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 Or=class{constructor(e){this.context=e}static{i(this,"BaseKeyValueStore")}};var Cr=class extends Or{static{i(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let t=g.instance.runtime.ZUPLO_KV;if(!t)throw new dn("The Key Value Store feature is not enabled for this project.");this.#e=t,y("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)}};
|
|
75
75
|
/*! For license information please see index.js.LEGAL.txt */
|