@zuplo/runtime 5.2152.0 → 5.2154.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.
Files changed (32) hide show
  1. package/{index.min.cjs → out/cjs/index.js} +1 -1
  2. package/{internal.min.cjs → out/cjs/internal/index.js} +1 -1
  3. package/{mocks.min.cjs → out/cjs/mocks/index.js} +1 -1
  4. package/out/cjs/policies/axiomatics-authz-inbound/exports.js +36 -0
  5. package/out/cjs/policies/axiomatics-authz-inbound/exports.js.LEGAL.txt +10 -0
  6. package/out/esm/chunk-4DUPDUSC.js +26 -0
  7. package/out/esm/chunk-CI735RIK.js +36 -0
  8. package/out/esm/chunk-CI735RIK.js.LEGAL.txt +10 -0
  9. package/out/esm/chunk-HPMPWPKQ.js +26 -0
  10. package/out/esm/chunk-HPMPWPKQ.js.LEGAL.txt +0 -0
  11. package/out/esm/chunk-QSL25HFO.js +26 -0
  12. package/out/esm/chunk-QSL25HFO.js.LEGAL.txt +0 -0
  13. package/out/esm/index.js +65 -0
  14. package/{index.min.js.LEGAL.txt → out/esm/index.js.LEGAL.txt} +0 -10
  15. package/out/esm/internal/index.js +26 -0
  16. package/out/esm/internal/index.js.LEGAL.txt +0 -0
  17. package/out/esm/mocks/index.js +26 -0
  18. package/out/esm/mocks/index.js.LEGAL.txt +0 -0
  19. package/out/esm/policies/axiomatics-authz-inbound/exports.js +26 -0
  20. package/out/esm/policies/axiomatics-authz-inbound/exports.js.LEGAL.txt +0 -0
  21. package/out/types/policies/axiomatics-authz-inbound/exports.d.ts +106 -0
  22. package/package.json +16 -24
  23. package/index.min.js +0 -75
  24. package/mocks.min.js +0 -26
  25. package/types-public.d.ts +0 -3796
  26. /package/{index.min.cjs.LEGAL.txt → out/cjs/index.js.LEGAL.txt} +0 -0
  27. /package/{internal.min.cjs.LEGAL.txt → out/cjs/internal/index.js.LEGAL.txt} +0 -0
  28. /package/{mocks.min.cjs.LEGAL.txt → out/cjs/mocks/index.js.LEGAL.txt} +0 -0
  29. /package/{mocks.min.js.LEGAL.txt → out/esm/chunk-4DUPDUSC.js.LEGAL.txt} +0 -0
  30. /package/{types-beta.d.ts → out/types/index.d.ts} +0 -0
  31. /package/{internal.d.ts → out/types/internal/index.d.ts} +0 -0
  32. /package/{mocks.d.ts → out/types/mocks/index.d.ts} +0 -0
package/index.min.js DELETED
@@ -1,75 +0,0 @@
1
-
2
- /*---------------------------------------------------------------------------------------------
3
- * Copyright (c) Zuplo, Inc. All rights reserved.
4
- *
5
- * This software and associated documentation files (the "Software") is intended to be used
6
- * only by Zuplo customers solely to develop and test applications that will be deployed
7
- * to Zuplo hosted services. You and others in your organization may use these files on your
8
- * Development Devices solely for the above stated purpose.
9
- *
10
- * Outside of uses stated above, no license is granted for any other purpose including
11
- * without limitation the rights to use, copy, modify, merge, publish, distribute,
12
- * sublicense, host, and/or sell copies of the Software.
13
- *
14
- * The software may include third party components with separate legal notices or governed by
15
- * other agreements, as described in licenses either embedded in or accompanying the Software.
16
- *
17
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
18
- * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
19
- * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
20
- * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
21
- * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22
- * DEALINGS IN THE SOFTWARE.
23
- *--------------------------------------------------------------------------------------------*/
24
-
25
- var Qa=Object.create;var Xn=Object.defineProperty;var eu=Object.getOwnPropertyDescriptor;var tu=Object.getOwnPropertyNames;var nu=Object.getPrototypeOf,ru=Object.prototype.hasOwnProperty;var i=(n,e)=>Xn(n,"name",{value:e,configurable:!0});var Tt=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var ou=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of tu(e))!ru.call(n,o)&&o!==t&&Xn(n,o,{get:()=>e[o],enumerable:!(r=eu(e,o))||r.enumerable});return n};var Ke=(n,e,t)=>(t=n!=null?Qa(nu(n)):{},ou(e||!n||!n.__esModule?Xn(t,"default",{value:n,enumerable:!0}):t,n));var Ai=Tt(T=>{"use strict";Object.defineProperty(T,"__esModule",{value:!0});T.generateColor=T.colorFunctions=T.stripColor=T.bgRgb24=T.rgb24=T.bgRgb8=T.rgb8=T.bgBrightWhite=T.bgBrightCyan=T.bgBrightMagenta=T.bgBrightBlue=T.bgBrightYellow=T.bgBrightGreen=T.bgBrightRed=T.bgBrightBlack=T.bgWhite=T.bgCyan=T.bgMagenta=T.bgBlue=T.bgYellow=T.bgGreen=T.bgRed=T.bgBlack=T.brightWhite=T.brightCyan=T.brightMagenta=T.brightBlue=T.brightYellow=T.brightGreen=T.brightRed=T.brightBlack=T.gray=T.white=T.cyan=T.magenta=T.blue=T.yellow=T.green=T.red=T.black=T.strikethrough=T.hidden=T.inverse=T.underline=T.italic=T.dim=T.bold=T.reset=T.getColorEnabled=T.setColorEnabled=void 0;var Ei=!0,Qn=!Ei;function iu(n){Ei||(Qn=n)}i(iu,"setColorEnabled");T.setColorEnabled=iu;function su(){return Qn}i(su,"getColorEnabled");T.getColorEnabled=su;function W(n,e){return{open:`\x1B[${n.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}i(W,"code");function J(n,e){return Qn?`${e.open}${n.replace(e.regexp,e.open)}${e.close}`:n}i(J,"run");function au(n){return J(n,W([0],0))}i(au,"reset");T.reset=au;function uu(n){return J(n,W([1],22))}i(uu,"bold");T.bold=uu;function cu(n){return J(n,W([2],22))}i(cu,"dim");T.dim=cu;function lu(n){return J(n,W([3],23))}i(lu,"italic");T.italic=lu;function du(n){return J(n,W([4],24))}i(du,"underline");T.underline=du;function pu(n){return J(n,W([7],27))}i(pu,"inverse");T.inverse=pu;function mu(n){return J(n,W([8],28))}i(mu,"hidden");T.hidden=mu;function gu(n){return J(n,W([9],29))}i(gu,"strikethrough");T.strikethrough=gu;function fu(n){return J(n,W([30],39))}i(fu,"black");T.black=fu;function Ii(n){return J(n,W([31],39))}i(Ii,"red");T.red=Ii;function xi(n){return J(n,W([32],39))}i(xi,"green");T.green=xi;function Ti(n){return J(n,W([33],39))}i(Ti,"yellow");T.yellow=Ti;function vi(n){return J(n,W([34],39))}i(vi,"blue");T.blue=vi;function Si(n){return J(n,W([35],39))}i(Si,"magenta");T.magenta=Si;function Oi(n){return J(n,W([36],39))}i(Oi,"cyan");T.cyan=Oi;function hu(n){return J(n,W([37],39))}i(hu,"white");T.white=hu;function yu(n){return Ci(n)}i(yu,"gray");T.gray=yu;function Ci(n){return J(n,W([90],39))}i(Ci,"brightBlack");T.brightBlack=Ci;function bu(n){return J(n,W([91],39))}i(bu,"brightRed");T.brightRed=bu;function wu(n){return J(n,W([92],39))}i(wu,"brightGreen");T.brightGreen=wu;function Ru(n){return J(n,W([93],39))}i(Ru,"brightYellow");T.brightYellow=Ru;function Pu(n){return J(n,W([94],39))}i(Pu,"brightBlue");T.brightBlue=Pu;function Eu(n){return J(n,W([95],39))}i(Eu,"brightMagenta");T.brightMagenta=Eu;function Iu(n){return J(n,W([96],39))}i(Iu,"brightCyan");T.brightCyan=Iu;function xu(n){return J(n,W([97],39))}i(xu,"brightWhite");T.brightWhite=xu;function Tu(n){return J(n,W([40],49))}i(Tu,"bgBlack");T.bgBlack=Tu;function vu(n){return J(n,W([41],49))}i(vu,"bgRed");T.bgRed=vu;function Su(n){return J(n,W([42],49))}i(Su,"bgGreen");T.bgGreen=Su;function Ou(n){return J(n,W([43],49))}i(Ou,"bgYellow");T.bgYellow=Ou;function Cu(n){return J(n,W([44],49))}i(Cu,"bgBlue");T.bgBlue=Cu;function Au(n){return J(n,W([45],49))}i(Au,"bgMagenta");T.bgMagenta=Au;function _u(n){return J(n,W([46],49))}i(_u,"bgCyan");T.bgCyan=_u;function Lu(n){return J(n,W([47],49))}i(Lu,"bgWhite");T.bgWhite=Lu;function ku(n){return J(n,W([100],49))}i(ku,"bgBrightBlack");T.bgBrightBlack=ku;function Nu(n){return J(n,W([101],49))}i(Nu,"bgBrightRed");T.bgBrightRed=Nu;function Mu(n){return J(n,W([102],49))}i(Mu,"bgBrightGreen");T.bgBrightGreen=Mu;function Du(n){return J(n,W([103],49))}i(Du,"bgBrightYellow");T.bgBrightYellow=Du;function Uu(n){return J(n,W([104],49))}i(Uu,"bgBrightBlue");T.bgBrightBlue=Uu;function Hu(n){return J(n,W([105],49))}i(Hu,"bgBrightMagenta");T.bgBrightMagenta=Hu;function Zu(n){return J(n,W([106],49))}i(Zu,"bgBrightCyan");T.bgBrightCyan=Zu;function qu(n){return J(n,W([107],49))}i(qu,"bgBrightWhite");T.bgBrightWhite=qu;function $e(n,e=255,t=0){return Math.trunc(Math.max(Math.min(n,e),t))}i($e,"clampAndTruncate");function $u(n,e){return J(n,W([38,5,$e(e)],39))}i($u,"rgb8");T.rgb8=$u;function Fu(n,e){return J(n,W([48,5,$e(e)],49))}i(Fu,"bgRgb8");T.bgRgb8=Fu;function ju(n,e){return typeof e=="number"?J(n,W([38,2,e>>16&255,e>>8&255,e&255],39)):J(n,W([38,2,$e(e.r),$e(e.g),$e(e.b)],39))}i(ju,"rgb24");T.rgb24=ju;function Bu(n,e){return typeof e=="number"?J(n,W([48,2,e>>16&255,e>>8&255,e&255],49)):J(n,W([48,2,$e(e.r),$e(e.g),$e(e.b)],49))}i(Bu,"bgRgb24");T.bgRgb24=Bu;var zu=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 Vu(n){return n.replace(zu,"")}i(Vu,"stripColor");T.stripColor=Vu;T.colorFunctions=[Ii,xi,Ti,vi,Si,Oi];function Gu(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(Gu,"hashCode");function Wu(n){let e=Math.abs(Gu(n));return T.colorFunctions[e%T.colorFunctions.length]}i(Wu,"generateColor");T.generateColor=Wu});var _i=Tt(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.format=void 0;function Ju(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(Ju,"format");Wt.format=Ju});var Ui=Tt(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.inspect=void 0;function Ye(n,e,t,r){let o={seen:[],stylize:Ku,showHidden:e??!1,depth:t??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=Xu),Jt(o,n,o.depth)}i(Ye,"inspect");Kt.inspect=Ye;Ye.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]};Ye.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function Ku(n,e){return n}i(Ku,"stylizeNoColor");function Yu(n){return typeof n=="boolean"}i(Yu,"isBoolean");function ki(n){return n===void 0}i(ki,"isUndefined");function Xu(n,e){let t=Ye.styles[e];return t?"\x1B["+Ye.colors[t][0]+"m"+n+"\x1B["+Ye.colors[t][1]+"m":n}i(Xu,"stylizeWithColor");function er(n){return typeof n=="function"}i(er,"isFunction");function Ni(n){return typeof n=="string"}i(Ni,"isString");function Qu(n){return typeof n=="number"}i(Qu,"isNumber");function Mi(n){return n===null}i(Mi,"isNull");function Di(n,e){return Object.prototype.hasOwnProperty.call(n,e)}i(Di,"hasOwn");function tr(n){return ir(n)&&sr(n)==="[object RegExp]"}i(tr,"isRegExp");function ir(n){return typeof n=="object"&&n!==null}i(ir,"isObject");function nr(n){return ir(n)&&(sr(n)==="[object Error]"||n instanceof Error)}i(nr,"isError");function Li(n){return ir(n)&&sr(n)==="[object Date]"}i(Li,"isDate");function sr(n){return Object.prototype.toString.call(n)}i(sr,"objectToString");function ec(n){let e={};return n.forEach(function(t,r){e[t]=!0}),e}i(ec,"arrayToHash");function tc(n,e,t,r,o){let s=[];for(let a=0,u=e.length;a<u;++a)Di(e,String(a))?s.push(or(n,e,t,r,String(a),!0)):s.push("");return o.forEach(function(a){a.match(/^\d+$/)||s.push(or(n,e,t,r,a,!0))}),s}i(tc,"formatArray");function rr(n){return"["+Error.prototype.toString.call(n)+"]"}i(rr,"formatError");function Jt(n,e,t){if(n.customInspect&&e&&er(e.inspect)&&e.inspect!==Ye&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(t,n);return Ni(d)||(d=Jt(n,d,t)),d}let r=nc(n,e);if(r)return r;let o=Object.keys(e),s=ec(o);try{n.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(nr(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return rr(e);if(o.length===0){if(er(e)){let d=e.name?": "+e.name:"";return n.stylize("[Function"+d+"]","special")}if(tr(e))return n.stylize(RegExp.prototype.toString.call(e),"regexp");if(Li(e))return n.stylize(Date.prototype.toString.call(e),"date");if(nr(e))return rr(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),er(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),tr(e)&&(a=" "+RegExp.prototype.toString.call(e)),Li(e)&&(a=" "+Date.prototype.toUTCString.call(e)),nr(e)&&(a=" "+rr(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(t<0)return tr(e)?n.stylize(RegExp.prototype.toString.call(e),"regexp"):n.stylize("[Object]","special");n.seen.push(e);let l;return u?l=tc(n,e,t,s,o):l=o.map(function(d){return or(n,e,t,s,d,u)}),n.seen.pop(),rc(l,a,c)}i(Jt,"formatValue");function or(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")),Di(r,o)||(a="["+o+"]"),u||(n.seen.indexOf(c.value)<0?(Mi(t)?u=Jt(n,c.value,null):u=Jt(n,c.value,t-1),u.indexOf(`
27
- `)>-1&&(s?u=u.split(`
28
- `).map(function(l){return" "+l}).join(`
29
- `).substr(2):u=`
30
- `+u.split(`
31
- `).map(function(l){return" "+l}).join(`
32
- `))):u=n.stylize("[Circular]","special")),ki(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(or,"formatProperty");function nc(n,e){if(ki(e))return n.stylize("undefined","undefined");if(Ni(e)){let t="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return n.stylize(t,"string")}if(Qu(e))return n.stylize(""+e,"number");if(Yu(e))return n.stylize(""+e,"boolean");if(Mi(e))return n.stylize("null","null")}i(nc,"formatPrimitive");function rc(n,e,t){let r=0;return n.reduce(function(s,a){return r++,a.indexOf(`
33
- `)>=0&&r++,s+a.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?t[0]+(e===""?"":e+`
34
- `)+" "+n.join(`,
35
- `)+" "+t[1]:t[0]+e+" "+n.join(", ")+" "+t[1]}i(rc,"reduceToSingleString")});var Hi=Tt(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.format=void 0;var oc=_i(),ic=Ui(),sc=i((n,...e)=>(0,oc.format)(ic.inspect,n,e),"format");Yt.format=sc});var je=Tt(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.debug=Fe.withoutEnv=Fe.Debugger=void 0;var ac=Ai(),uc=Hi(),Xt=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=(0,ac.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,uc.format)(t,...e);let s=`${this.color(this.ns)} ${t} ${this.color(`+${o}ms`)}`;console.log(s),this.last=Date.now()}};Fe.Debugger=Xt;var Qt=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function Zi(n){return!n||n.length===0?[]:(n=n.replace(/\s/g,"").replace(/\*/g,".+"),n.split(",").map(e=>new RegExp(`^${e}$`)))}i(Zi,"extract");var vt;function cc(n){n||(n=[]),typeof n=="string"&&(n=Zi(n)),vt=new Qt(n)}i(cc,"withoutEnv");Fe.withoutEnv=cc;function lc(n){let e=globalThis.DEBUG;vt||(vt=new Qt(Zi(e)));let t=new Xt(vt,n);return vt.debuggers.set(n,t),Object.assign(t.log.bind(t),{self:t})}i(lc,"debug");Fe.debug=lc});var ji=Ke(je());var Y=class extends Error{static{i(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},_=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 _{static{i(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}},en=class extends _{static{i(this,"FeatureNotEnabledError")}constructor(e,t){super(e,t),this.name="FeatureNotEnabledError"}};var ar="2024-03-14",qi=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 $i(){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:ar,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,COMPATIBILITY_FLAGS:qi[ar]},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($i,"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=$i()),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 Xe=(0,ji.debug)("zuplo:runtime:external-service");function dc(){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(dc,"getServiceAuth");async function Bi(n,e){let t=dc();if(t)if(Xe(`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{Xe("Using sha256 service routing");let d=g.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await pc(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw Xe("Cannot use sha256 service routing, missing build variables"),new _("Failed to generate fully qualified tunnel url.")}let c=new URL(`${u}${r.pathname}${r.search}`);Xe(`Calling external service: ${c.toString()}`);let l=await q.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 _("Could not connect to secure tunnel.");return l}else throw Xe("Cannot call external service with Request object"),new _("Currently, we only support fetch(<some_string>, ...).");else throw Xe("There is no external service auth configured for this zup."),new _("There are no external services configured for this zup.")}i(Bi,"externalServiceHandler");async function pc(n,e,t,r){let o=n.toLowerCase(),s=e.toLowerCase(),a=t.toLowerCase(),u=mc(r);Xe(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await Fi(`${s}-${o}`),l=await Fi(`${s}-${a}-${u}`);return`${c}.${l}`}i(pc,"hashServiceName");async function Fi(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(Fi,"hashSegment");function mc(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(mc,"sanitizeEnvironmentType");var Vi=new Map;Vi.set("service:",Bi);var zi=globalThis.fetch;function ur(n,e){let t=gc(e);if(typeof n=="string"){let r=new URL(n),o=Vi.get(r.protocol);return o?o(n,t):zi(n,t)}else return zi(n,t)}i(ur,"internalFetch");globalThis.fetch=ur;var gc=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 fc={fetch:ur},q=fc;Function.prototype.toString=function(){return"[native code]"};var tn=globalThis,Gi=tn.caches;if(Gi){let n=Gi.open;tn.caches.open=function(e){let t=g.instance.deploymentName??g.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete tn.caches.default,Object.freeze(tn.caches)}var Wi=new Map,cr=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)})}},ct=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=Wi.get(e);r||(r=new cr(t),Wi.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 lr="__zuplo-expiry-header",St=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(lr);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(lr,`${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(lr,`${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 le=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new ct(r),this.#n=new St(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 Ji="zuplo-request-id",Qe="zp-rid",dr="zp-body-removed",et="cf-ray",Ki="x-real-ip",pr="cf-ipcity",mr="cf-ipcontinent",gr="cf-ipcountry",fr="cf-iplongitude",hr="cf-iplatitude",Yi="cf-region",Xi="cf-region-code",Qi="cf-metro-code",es="cf-postal-code",ts="cf-timezone",ns="zp-ipcity",rs="zp-ipcontinent",os="zp-ipcountry",is="zp-iplongitude",ss="zp-iplatitude",as="true-client-ip",yr="zp-asn",br="zp-asorg",wr="zp-colo",Rr="zp-postalcode",Pr="zp-metrocode",Er="zp-region",Ir="zp-regioncode",xr="zp-timezone",us=[pr,mr,gr,fr,hr,yr,br,wr,Rr,Pr,Er,Ir,xr],cs=["zp-","cf-"],ls=[Qe,et,dr];var Ot="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49",nn="zuplo_dynamic_meters_0c8cdc26-2514-4756-8adb-474a6e103d91",rn="system-logger";var Ws=Ke(je());import{trace as Qc}from"@opentelemetry/api";import{SpanStatusCode as hc,trace as yc}from"@opentelemetry/api";import{SpanStatusCode as Or,trace as Cr}from"@opentelemetry/api";var ds=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function ps(n){ds=n}i(ps,"setTelemetryInitFunction");var ms=i(n=>ds(n),"proxyHandler");var Be=class{static{i(this,"RuntimePlugin")}},Ue=class extends Be{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},on=class extends Ue{static{i(this,"MeteringPlugin")}},Ct=class extends Be{static{i(this,"TelemetryPlugin")}};var At=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&&(n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(s){throw new _("Error in custom 'problemResponseFormat'",{cause:s})}})}},tt=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,r){return await At.problemResponseFormat(e,t,r)}};function sn(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&sn(t)}return Object.freeze(n)}i(sn,"deepFreeze");var ne=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 sn(this.#e)}get params(){return sn(this.#t)}user};var _t={},He=[],Tr=[],vr=[],Sr=[];var an={addPlugin(n){He.push(n)},addRequestHook(n){Tr.push(n)},addResponseSendingHook(n){vr.push(n)},addResponseSendingFinalHook(n){Sr.push(n)}},fs=i(async(n,e)=>{if(Tr.length===0)return n;let t=Cr.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let s of Tr){let a=await t.startActiveSpan(s.name,async u=>{let c=await s(o,e);if(c instanceof ne||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:Or.ERROR}),l}});if(a instanceof ne)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),hs=i(async(n,e,t)=>{if(vr.length===0)return n;let r=Cr.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let s=n;for(let a of vr)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:Or.ERROR}),u.end(),l}});return s}finally{o.end()}})},"invokeOnResponseSendingExtensions"),ys=i(async(n,e,t)=>{if(Sr.length===0)return;let r=Cr.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let s of Sr)await r.startActiveSpan(s.name,async a=>{try{await s(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:Or.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),gs=!1;async function bs(n=()=>Promise.resolve()){if(!gs){await n(an),_t.value=an;for(let e of He)if(e instanceof Ct){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 He)e instanceof Ue&&await e.initialize(an);At.setProblemResponseFormat(an.problemResponseFormat),gs=!0}}i(bs,"initializeRuntime");var Ar={Json:"application/json",Form:"application/x-www-form-urlencoded"};function _r(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(Ar.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(Ar.Json)||!e?JSON.stringify(n):n}i(_r,"serialize");function lt(n){return ge.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(ge.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}i(lt,"isSystemRoute");var de=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,t)=>async(r,o)=>yc.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:hc.ERROR}),c}finally{a.end()}});#t=({processors:e,gateway:t,handler:r})=>async(o,s)=>{let a=[...e],u=i(async P=>{let O=a.pop();return O?O(o,s,t,u):await this.#e(async F=>{let Z=await r(F,s);return bc(Z)},t)(P,s)},"nextPipe"),l=await u(o),d=new URL(o.url);if(lt(d)&&g.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new Lt(o,l);s.dispatchEvent(p);let f=fe.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 hs(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 kt(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 ys(l,h,s)}catch(P){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}return A}};function bc(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(_r(n),{headers:{"content-type":"application/json"}})}i(bc,"resultToResponse");var un=(b=>(b[b.CONTINUE=100]="CONTINUE",b[b.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",b[b.PROCESSING=102]="PROCESSING",b[b.EARLY_HINTS=103]="EARLY_HINTS",b[b.OK=200]="OK",b[b.CREATED=201]="CREATED",b[b.ACCEPTED=202]="ACCEPTED",b[b.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",b[b.NO_CONTENT=204]="NO_CONTENT",b[b.RESET_CONTENT=205]="RESET_CONTENT",b[b.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",b[b.MULTI_STATUS=207]="MULTI_STATUS",b[b.ALREADY_REPORTED=208]="ALREADY_REPORTED",b[b.IM_USED=226]="IM_USED",b[b.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",b[b.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",b[b.FOUND=302]="FOUND",b[b.SEE_OTHER=303]="SEE_OTHER",b[b.NOT_MODIFIED=304]="NOT_MODIFIED",b[b.USE_PROXY=305]="USE_PROXY",b[b.SWITCH_PROXY=306]="SWITCH_PROXY",b[b.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",b[b.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",b[b.BAD_REQUEST=400]="BAD_REQUEST",b[b.UNAUTHORIZED=401]="UNAUTHORIZED",b[b.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",b[b.FORBIDDEN=403]="FORBIDDEN",b[b.NOT_FOUND=404]="NOT_FOUND",b[b.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",b[b.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",b[b.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",b[b.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",b[b.CONFLICT=409]="CONFLICT",b[b.GONE=410]="GONE",b[b.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",b[b.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",b[b.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",b[b.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",b[b.URI_TOO_LONG=414]="URI_TOO_LONG",b[b.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",b[b.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",b[b.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",b[b.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",b[b.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",b[b.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",b[b.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",b[b.LOCKED=423]="LOCKED",b[b.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",b[b.TOO_EARLY=425]="TOO_EARLY",b[b.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",b[b.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",b[b.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",b[b.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",b[b.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",b[b.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",b[b.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",b[b.BAD_GATEWAY=502]="BAD_GATEWAY",b[b.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",b[b.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",b[b.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",b[b.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",b[b.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",b[b.LOOP_DETECTED=508]="LOOP_DETECTED",b[b.NOT_EXTENDED=510]="NOT_EXTENDED",b[b.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",b))(un||{}),ws={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 wc={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"},Lr=wc;function Rc(n){return`${new URL(n.url).pathname}`}i(Rc,"instance");function Pc(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:g.instance.build.BUILD_ID},r=n.headers.get(et);return r&&(t.rayId=r),t}i(Pc,"trace");var Ec=i((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:Rc(e),trace:Pc(e,t),...r},additionalHeaders:o,statusText:Lr[n.status]}),"merge"),kr=class{static{i(this,"HttpProblemsBase")}static format=(e,t,r)=>"problem"in e?tt.format(e,t,r):tt.format({problem:e},t,r);static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:ws[e],...t}}},x=class extends kr{static{i(this,"HttpProblems")}static#e(e,t,r,o,s){let a=Ec(this.getProblemFromStatus(e),t,r,o,s);return tt.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 ze=class extends Be{static{i(this,"MetricsPlugin")}};var te=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 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 cn=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,te.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{loggingId:t,remoteLogURL:r,deploymentName:o,systemUserAgent:s}=g.instance,a=`${r}/v1/runtime/metrics`,u=e.map(l=>{let d=Object.assign({},l);return delete d.requestContentLength,delete d.responseContentLength,d.deploymentName=o,d.projectId=t,d}),c=await q.fetch(a,{method:"POST",body:JSON.stringify(u),headers:{"content-type":"application/json","zp-dn":o??"unknown","user-agent":s}});if(!c.ok){let l=await c.text();te.getLogger(this.#e).error(`Metrics POST responded ${c.status}: ${c.statusText}`,l)}}};var ae=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=Nt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Nt={name:"__system-no-version",pathPrefix:""};var he=i(async(n,e,t,r)=>{let o=new Date,s=Date.now(),a=await r(n),u=n.headers.get(et)??void 0,c=n.headers.get(as)??void 0,l=e.incomingRequestProperties,d;e.route instanceof ae&&(d=e.route.systemRouteName);let p=fe.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 cn(e)),He.forEach(A=>{if(A instanceof ze){let P=A.getTransport();h.push(P)}}),h.forEach(A=>{A.pushMetrics(f,e)}),a},"metricsProcessor");var Ze=(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))(Ze||{});var Nr=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"&&te.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new de({processors:[he],handler:t,gateway:e}),o=new ae({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var{toString:Ic}=Object.prototype,{propertyIsEnumerable:xc}=Object.prototype;function Mr(n){return Ic.call(n)}i(Mr,"toString");function Ie(n){return typeof n=="string"}i(Ie,"isString");function dt(n){return Ie(n)&&n!==""}i(dt,"isNonEmptyString");function Rs(n){return Mr(n)==="[object RegExp]"}i(Rs,"isRegexp");function Ps(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>xc.call(n,e))]}i(Ps,"getOwnEnumerableKeys");function nt(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}i(nt,"isObject");function Dr(n){return typeof n=="number"&&!isNaN(n)}i(Dr,"isNumber");function Ur(n){return n===!0||n===!1}i(Ur,"isBoolean");function Es(n){return typeof n>"u"}i(Es,"isUndefined");function Is(n){return Es(n)||n===null}i(Is,"isUndefinedOrNull");function Mt(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(Mt,"isErrorLike");var xs=new Map;function pt(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=xs.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 xs.set(n,r),r}i(pt,"statusCodesStringToNumberArray");function rt(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 _(`Error applying ${t} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i(rt,"getValueFromRequestUser");function Ts(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 _(`Error applying'${e}', reading '${o}'`);if(r&&typeof r=="object")r=Reflect.get(r,o);else throw new _(`Error applying'${e}', reading '${o}'`)}),`${r}`}i(Ts,"selectPropertyUsingJsonPath");function ot(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new m("Received an array that contains non-string values.");return n}if(Ie(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(ot,"parseValueToStringArray");function vs(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(!nt(t))throw new m(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!dt(t.name))throw new m("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!Dr(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&&!Ur(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=Hr(t,"allowedHeaders"),o=Hr(t,"allowedMethods"),s=Hr(t,"exposeHeaders"),a;try{a=ot(t.allowedOrigins)}catch(c){throw new m(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:t.name,allowCredentials:typeof t.allowCredentials=="boolean"?String(t.allowCredentials):void 0,allowedOrigins:a,allowedHeaders: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(vs,"parseCorsPolicies");function Hr(n,e){let t;if(n[e]!==void 0)try{t=ot(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(Hr,"parseOptionalProperty");var ln=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"),dn=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 Zr=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=Tc(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 de({processors:[he],handler:r,gateway:e}),s=new ae({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(s,o.execute)},"registerCorsRoute"),Tc=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=ln(a.allowedOrigins,t);return u?{isValid:!0,headers:dn(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var Ss=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 de({processors:[he],handler:t,gateway:e}),o=new ae({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});n.addRoute(o,r.execute)},"registerNoRoutes");var qr=new ae({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Os=i((n,e)=>{let t=i(async(o,s)=>{let a=_t.value?.notFoundHandler;if(a){let u=fe.getContextExtensions(s);return a(o,s,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return x.notFound(o,s)},"notFoundHandler"),r=new de({processors:[he],handler:t,gateway:e});n.addRoute(qr,r.execute)},"registerNotMatchedHandler");var vc=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Cs=i(n=>{vc.forEach(e=>n.delete(e))},"stripCorsHeaders"),pn=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 Cs(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=Sc(o,t.routeData.corsPolicies),u=Oc(n,a),c=new Headers(s.headers);return Cs(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"),Sc=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"),Oc=i((n,e)=>{let t=ln(e.allowedOrigins,n.headers.get("origin"));return t?dn(e,t):{}},"getCorsHeaders");var $r=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 de({processors:[pn],handler:t,gateway:e}),o=new ae({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");import{SpanStatusCode as As,trace as _s}from"@opentelemetry/api";var ke={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 mn=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!Ie(t))throw new _(`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}},be=class extends mn{static{i(this,"InboundPolicy")}},Ve=class extends mn{static{i(this,"OutboundPolicy")}};var Br=class extends be{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)}},zr=class extends Ve{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)}},Fr=new Map;function Dt(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(s=>!Fr.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 be)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new Br(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}')`);Fr.set(a.name,c)}),t.map(s=>{let a=Fr.get(s);if(a===void 0)throw new _("Internal error. Policy not found in cache.");return a})}i(Dt,"getInboundPolicyInstances");var jr=new Map;function Cc(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!jr.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 Ve)u=new a(s.handler.options??{},s.name);else if(typeof a=="function")u=new zr(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}'`);jr.set(s.name,u)}),t.map(o=>{let s=jr.get(o);if(s===void 0)throw new _("Internal error. Policy not found in cache.");return s})}i(Cc,"getOutboundPolicyInstances");var Vr=i(n=>async(e,t)=>{let r=fe.getContextExtensions(t),o=_s.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 ne||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:As.ERROR}),d.recordException(f),f}});if(l instanceof ne)u=l;else if(l instanceof Request)u=new ne(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),Ac=i(n=>async(e,t,r)=>{let o=_s.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(ke.PolicyName,c.policyName),d.setAttribute(ke.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:As.ERROR}),d.recordException(f),f}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),gn=i(async(n,e,t,r)=>{let o=Dt(e.route,t.routeData.policies),s=Cc(e.route,t.routeData.policies);return ks({request:n,context:e,inboundPolicies:o,outboundPolicies:s,gateway:t,next:r})},"policyProcessor");function Ls({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>ks({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(Ls,"createInternalPolicyProcessor");async function ks({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:s}){let a=Vr(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await s(u),l=Ac(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(ks,"executePolicyProcessor");function Ns(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||_c,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]=Lc(l,o)}s=u+1}return t}i(Ns,"parse");function _c(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}i(_c,"decode");function Lc(n,e){try{return e(n)}catch{return n}}i(Lc,"tryDecode");function Ms(n,e){try{let t=/v\d+(-\d+)?/g,o=Ns(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}i(Ms,"devPortalBaseURL");var Ds="/__zuplo/dev-portal",kc="dev-portal-id",Nc="dev-portal-host",Mc="zp-account",Dc="zp-project",Uc="dev-portal-build",Hc=`
36
- <!DOCTYPE html>
37
- <html lang="en">
38
- <head>
39
- <meta charset="UTF-8">
40
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
41
- <title>Developer Portal Preview</title>
42
- </head>
43
- <body>
44
- <p>Previewing your Developer Portal is not supported (yet) in local development.</p>
45
- <p>For now, create a project on <a href="https://portal.zuplo.com">portal.zuplo.com</a>.</p>
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
- </body>
48
- </html>
49
- `,Us=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(Hc,{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=Ms(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(Mc,g.instance.build.ACCOUNT_NAME),g.instance.build.PROJECT_NAME&&h.set(Dc,g.instance.build.PROJECT_NAME),h.set(kc,r),h.set(Nc,d.host),h.set(Uc,g.instance.build.BUILD_ID),await q.fetch(f.toString(),{headers:h,method:A,body:P,redirect:"manual"})},"devPortalRoute"),a=new de({processors:[he,gn],handler:s,gateway:e}),u=new ae({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"),Hs=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(Ds.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new de({processors:[he],handler:r,gateway:e}),s=new ae({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${Ds}(.*)`,systemRouteName:"developer-portal-legacy"});n.addRoute(s,o.execute)},"registerDevPortalLegacyRedirectRoute");var zs=Ke(je());var Gr=0,Ut=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){Gr>=Number.MAX_SAFE_INTEGER&&(Gr=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:Gr++};this.#t[e](u,a)}};var pe=class extends Be{static{i(this,"LogPlugin")}};var fn=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 Ht=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 Zc=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(n=>[n.name,n]),qc=new Map(Zc);var $c=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],Wr=Symbol(".toJSON was called"),Fc=i(n=>{n[Wr]=!0;let e=n.toJSON();return delete n[Wr],e},"toJSON"),jc=i(n=>qc.get(n)??Error,"getErrorConstructor"),Zs=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&&Mt(n)){let l=jc(n.name);t=new l}else t={};if(e.push(n),s>=o)return t;if(a&&typeof n.toJSON=="function"&&n[Wr]!==!0)return Fc(n);let c=i(l=>Zs({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 $c)typeof n[l]<"u"&&n[l]!==null&&Object.defineProperty(t,l,{value:Mt(n[l])?c(n[l]):n[l],enumerable:r?!0:d,configurable:!0,writable:!0});return t},"destroyCircular");function we(n,e){let t=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof n=="object"&&n!==null?Zs({from:n,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:r,serialize:!0}):typeof n=="function"?`[Function: ${n.name??"anonymous"}]`:n}i(we,"serializeError");var Bc=/file:\/\/\/(.*?)\/dist\//g,zc="at async Event.respondWith";function qs(n){return typeof n!="string"?n:n.split(`
50
- `).filter(e=>!e.trim().startsWith("at async file")).map((e,t)=>{let r=e.replaceAll(Bc,"").replaceAll(zc,"").trim();return t===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
51
- `)}i(qs,"cleanStack");function hn(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
- `,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 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"||Rs(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 O=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+O}).join("")+p.pad+"]";return r.pop(),f(h)}if(nt(a)){let h=Ps(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,O)=>{let H=h.length-1===O?p.newline:","+p.newlineOrSpace,k=typeof P=="symbol",F=!k&&/^[a-z$_][$\w]*$/i.test(P),Z=k||F?P:s(P,u,"",l+1),j=s(a[P],u,c+d,l+1);return u.transform&&(j=u.transform(a,P,j)),p.indent+String(Z)+": "+j+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(hn,"stringifyObject");function Ge(n){return n.map(e=>we(e))}i(Ge,"makeErrorsSerializable");function mt(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:qe(we(e))}i(mt,"extractBestMessage");function $s(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(Mt(t))if(t.stack)e.push(t.stack);else{let r=hn(we(t));e.push(r)}else if(typeof t=="object"){let r=hn(t);e.push(r)}else{let r=Jr(t);e.push(r)}}),e.join(`
56
- `)}i($s,"messagesToMultilineText");function qe(n){return typeof n=="string"?n:JSON.stringify(n)}i(qe,"stringifyNonString");function Jr(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"?Mr(n):"unknown"}i(Jr,"stringifyNonStringToText");import{importPKCS8 as Vc,SignJWT as Gc}from"jose";async function Re(n,e,t){for(let r=0;r<=n.retries;r++){let o=q.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(Re,"fetchRetry");async function Ne({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=n;return await new Gc(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(Ne,"getTokenFromGcpServiceAccount");async function Fs(n,e,t){return js(n,{token:e,returnSecureToken:!0},t)}i(Fs,"exchangeFirebaseJwtForIdToken");async function yn(n,e,t){return js(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(yn,"exchangeGgpJwtForIdToken");async function js(n,e,t){let r=await Re(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 _({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(js,"fetchToken");var xe=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 Vc(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 Kr=class extends pe{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Zt(this.options)}},Wc="https://logging.googleapis.com/v2/entries:write?alt=json",Yr={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Zt=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}#e;#t;#n;#r;#o;#i;async init(){this.#t=await xe.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:Ge(e.messages)},o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:Yr[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=mt(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 xe.init(this.#e));let t=await Ne({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await q.fetch(Wc,{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 bn="gcp";function wn(n){let e={allMessages:Ge(n.messages)},t="zuplo-production",r=mt(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:Yr[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(wn,"gcpLogFormat");var qt=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===bn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[wn(e)])}else this.#e.log(JSON.stringify(e))}};var to=class extends pe{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new $t(this.options)}},Xr="__ddtags",Qr="__ddattr",eo=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),Jc=i(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(eo(r)):t.push(`${eo(r)}:${eo(o.toString())}`)}),t.join(",")},"formatTags"),$t=class{static{i(this,"DataDogTransport")}constructor(e){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[Xr];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(h=>h[Xr]!==void 0);a>-1&&(Object.assign(r,s[a][Xr]),s.splice(a,1));let u={},c=t.custom[Qr];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(h=>h[Qr]!==void 0);l>-1&&(Object.assign(u,s[l][Qr]),s.splice(l,1));let d=Ge(s),f={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:mt(d),service:e.loggingId,ddtags:Jc(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 q.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 Ft=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===bn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[wn(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 Kc=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 q.fetch(`${n}/publish/${t}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:s.map(a=>({...a,messages:Ge(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"),Rn,Pn=class{static{i(this,"RemoteLogTransport")}constructor(e){Rn||(Rn=new X("remote-log-transport",1,Kc(e)))}log(e,t){Rn.enqueue(e),t.waitUntil(Rn.waitUntilFlushed())}};var Yc={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},Bs=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:Yc[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var Xc=i(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let s=Bs(t,r);try{await q.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"),En,In=class{static{i(this,"UnifiedLogTransport")}constructor(e){En||(En=new X("unified-log-transport",1,Xc(e)))}async log(e,t){En.enqueue(e),t.waitUntil(En.waitUntilFlushed())}};var no=(0,zs.debug)("zuplo:logging"),xn=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;no("Gateway.setupSystemCoreLogger");let o=[],s=t.getService(rn);return s?o.push(new Ft(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new qt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new In({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 Ut(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){no("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=t.getService(rn);if(a&&a.captureUserLogs===!0?r.push(new Ft(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new qt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new Pn({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 Zt({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 $t({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return He.forEach(u=>{u instanceof pe&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new Ut(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,t,r,o,s){no("Gateway.createRequestLoggers");let a=new fn(r,o,s),u=new Ht(e,t,this.systemCoreLogger,a);return{userRequestLogger:new Ht(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var it=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 ro=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},jt=class{static{i(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},oo=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}},Bt=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof it||e instanceof ae))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 ro(o,s,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new oo(`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 jt(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 jt(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var io;function Vs(n){io=n}i(Vs,"setGlobalZuploEventContext");function Tn(){if(io===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return io}i(Tn,"getGlobalZuploEventContext");function Gs({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);cs.includes(o.toLowerCase())&&!ls.includes(r.toLowerCase())&&t.delete(r)}t.delete(Ki)}else us.forEach(r=>{t.delete(r)});return t}i(Gs,"normalizeIncomingRequestHeaders");var Me=(0,Ws.debug)("zuplo:runtime"),el=i(n=>{let e=n.findIndex(t=>t.name===Nt.name);return e>-1?[...n.splice(e),Nt]:[...n,Nt]},"setupSystemNoVersion"),ge=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;Me("Gateway.constructor"),ke,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(Me("Gateway.initialize"),!n.#e){let s=await xn.init(r),a=e(),u={...a,corsPolicies:vs(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(){Me("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=[gn,pn,he];#o;setupRoutes=()=>{Me("Gateway.setupRoutes");let e=this.routeData,t=el(e.versions),r=new Bt(t);if(e.routes.length===0)return Nr(r,this),$r(r,this),Zr(r,this),Ss(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(Hs(r,this),Us(r,this)),Nr(r,this),$r(r,this),Zr(r,this);for(let s of He)s instanceof Ue&&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 de({processors:this.#r,handler:a,gateway:this}),c=new it(s);r.addRoute(c,u.execute)}),Os(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 Me("An error occurred in the user's errorHandler",o),this.#i(e,t,o)}}#i(e,t,r){Me("Gateway.internalErrorResponse");let o={};if(g.instance.isWorkingCopy){if(r instanceof _&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let s=we(r.cause);"stack"in s&&(s.stack=qs(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;Vs(r);let a=Gs({headers:e.headers,removeAllVendorHeadersExceptListed:g.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(Qe,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let F=new Headers(u.headers);F.set(dr,"true"),u=new Request(u,{headers:F,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 vn(e.headers),P=new ne(u,{params:h.params}),O=new Sn({logger:l,route:h.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:A}),H=h.routeConfiguration.raw();Qc.getActiveSpan()?.setAttributes({"http.route":O.route.path??O.route.pathPattern,"cloud.region":O.incomingRequestProperties.colo,[ke.RoutePathPattern]:O.route.pathPattern,[ke.RouteOperationId]:H.operationId,[ke.RouteTrace]:H["x-zuplo-trace"],[ke.RouteSystem]:lt(p)?!0:void 0});let k=fe.initialize(O,P);if(h.routeConfiguration===qr&&_t.value?.notFoundHandler!==void 0){let F=this.#n.lookupByPathOnly(f);k.pathOnlyMatches=F.map(Z=>Z.routeConfiguration).filter(Z=>Z instanceof it)}try{if(te.addLogger(O,d),g.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!lt(p):!p.pathname.startsWith("/__zuplo")){let R=await fs(P,O);if(R instanceof Response)return R;{let M=fe.getContextExtensions(O);P=R,M.latestRequest=P}}lt(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:h.routeConfiguration.path});let F=h.executableHandler;tl(F,h,u),Me("Gateway.handleRequest - call user handler");let Z=await F(P,O);if(Me("Gateway.handleRequest - user handler"),!(Z instanceof Response))throw new _(`Invalid Response type from the request handler: ${typeof Z}`);if(Z.bodyUsed)throw new _("The response object has already been used. Return a new response instead.");let j;if(Z.headers.get(Qe)===null&&!Z.webSocket){let R=new Headers(Z.headers);R.set(Qe,o),j=new Response(Z.body,{status:Z.status,statusText:Z.statusText,headers:R,cf:Z.cf})}else j=Z;return j}catch(F){return Me("Gateway - error executing handler",F),F instanceof _?(l.error(F),d.warn(F)):d.error(F),await this.#i(P,O,F)}}};function tl(n,e,t){if(Me("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(tl,"checkHandler");var Js=i(async(n,e,t)=>{let r=ge.instance.routeData.policies,o=Dt([n],r);if(o.length===0)throw new _(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy");var vn=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(yr);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(br)??void 0}get city(){return this.#e.get(pr)??this.#e.get(ns)??void 0}get continent(){return this.#e.get(mr)??this.#e.get(rs)??void 0}get country(){return this.#e.get(gr)??this.#e.get(os)??void 0}get latitude(){return this.#e.get(hr)??this.#e.get(ss)??void 0}get longitude(){return this.#e.get(fr)??this.#e.get(is)??void 0}get colo(){return this.#e.get(wr)??void 0}get postalCode(){return this.#e.get(es)??this.#e.get(Rr)??void 0}get metroCode(){return this.#e.get(Qi)??this.#e.get(Pr)??void 0}get region(){return this.#e.get(Yi)??this.#e.get(Er)??void 0}get regionCode(){return this.#e.get(Xi)??this.#e.get(Ir)??void 0}get timezone(){return this.#e.get(ts)??this.#e.get(xr)??void 0}toJSON(){return{asn:this.asn,asOrganization:this.asOrganization,city:this.city,continent:this.continent,country:this.country,latitude:this.latitude,longitude:this.longitude,colo:this.colo,postalCode:this.postalCode,metroCode:this.metroCode,region:this.region,regionCode:this.regionCode,timezone:this.timezone}}},Lt=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},kt=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},fe=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 _(`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}},Sn=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)=>Js(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{fe.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{fe.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 nl=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function rl(n){return n.startsWith("__ZUPLO")||n.startsWith("ZUPLO_")?!nl.includes(n)&&!n.startsWith("ZUPLO_PUBLIC_"):!1}i(rl,"isRestrictedEnvVariableName");function ol(n){return!!n.startsWith("ZUPLO_")}i(ol,"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(!(rl(t)&&!ol(t)))return g.instance.runtime[t]}});import{AsyncLocalStorage as il}from"node:async_hooks";var Ks={request:new il};var sl="Error initializing gateway. Check your configuration for errors or contact support.",al="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",so=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(Qe)??e.headers.get(Ji)??crypto.randomUUID(),s=e.headers.get(et),a={requestId:o,rayId:s};return Ks.request.run(a,async()=>{g.initialize({build:this.buildEnvironment,runtime:t});try{await bs(this.runtimeInit)}catch(c){this.handleError(c,al,e)}return ms(i(async(c,l)=>{let d;try{d=await ge.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,sl,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 ia=Ke(je());function ul(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(ul,"lexer");function ao(n,e){e===void 0&&(e={});for(var t=ul(n),r=e.prefixes,o=r===void 0?"./":r,s="[^".concat(ll(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=i(function(R){if(c<t.length&&t[c].type===R)return t[c++].value},"tryConsume"),p=i(function(R){var M=d(R);if(M!==void 0)return M;var B=t[c],G=B.type,v=B.index;throw new TypeError("Unexpected ".concat(G," at ").concat(v,", expected ").concat(R))},"mustConsume"),f=i(function(){for(var R="",M;M=d("CHAR")||d("ESCAPED_CHAR");)R+=M;return R},"consumeText");c<t.length;){var h=d("CHAR"),A=d("NAME"),P=d("PATTERN");if(A||P){var O=h||"";o.indexOf(O)===-1&&(l+=O,O=""),l&&(a.push(l),l=""),a.push({name:A||u++,prefix:O,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 k=d("OPEN");if(k){var O=f(),F=d("NAME")||"",Z=d("PATTERN")||"",j=f();p("CLOSE"),a.push({name:F||(Z?u++:""),pattern:F&&!Z?s:Z,prefix:O,suffix:j,modifier:d("MODIFIER")||""});continue}p("END")}return a}i(ao,"parse");function Ys(n,e){return cl(ao(n,e),e)}i(Ys,"compile");function cl(n,e){e===void 0&&(e={});var t=dl(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 O=o(f[P],p);if(a&&!u[d].test(O))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(O,'"'));l+=p.prefix+O+p.suffix}continue}if(typeof f=="string"||typeof f=="number"){var O=o(String(f),p);if(a&&!u[d].test(O))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(O,'"'));l+=p.prefix+O+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(cl,"tokensToFunction");function ll(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(ll,"escapeString");function dl(n){return n&&n.sensitive?"":"i"}i(dl,"flags");var ta=Ke(je());var pl=(0,ta.debug)("zuplo:runtime"),co=new TextEncoder,Xs={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"},ml=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],gt=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 lo(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){pl("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,t),a=q.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")}},lo=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 O,H;(!c||!l)&&([O,H]=gl(this.url,this.headers)),this.service=c||O||"",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 k=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),k.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&k.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(Z=>A||!ml.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"&&!k.has("X-Amz-Expires")&&k.set("X-Amz-Expires","86400"),k.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),k.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),k.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");P||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=ea(this.encodedPath);let F=new Set;this.encodedSearch=[...this.url.searchParams].filter(([Z])=>{if(!Z)return!1;if(this.service==="s3"){if(F.has(Z))return!1;F.add(Z)}return!0}).map(Z=>Z.map(j=>ea(encodeURIComponent(j)))).sort(([Z,j],[R,M])=>Z<R?-1:Z>R?1:j<M?-1:j>M?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 zt("AWS4"+this.secretAccessKey,e),s=await zt(o,this.region),a=await zt(s,this.service);r=await zt(a,"aws4_request"),this.cache.set(t,r)}return uo(await zt(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,uo(await Qs(await this.canonicalString()))].join(`
58
- `)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
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 _("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=uo(await Qs(this.body||""))}return e}};async function zt(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?co.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,co.encode(e))}i(zt,"hmac");async function Qs(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?co.encode(n):n)}i(Qs,"hash");function uo(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}i(uo,"buf2hex");function ea(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(ea,"encodeRfc3986");function gl(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 Xs?[Xs[s],a]:[s,a]}i(gl,"guessServiceRegion");function fl(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(fl,"b64ToUint6");function na(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|=fl(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(na,"base64Decode");function On(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}i(On,"uint6ToB64");function ra(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(On(o>>>18&63),On(o>>>12&63),On(o>>>6&63),On(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}i(ra,"base64Encode");function ft(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}i(ft,"numberToString");function hl(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=ft(Math.floor(t/60)),s=ft(t%60);return`${r}${o}${s}`}i(hl,"getCLFOffset");function po(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=ft(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),s=ft(n.getHours()),a=ft(n.getMinutes()),u=ft(n.getSeconds()),c=hl(n);return`${t}/${r}/${o}:${s}:${a}:${u} ${c}`}i(po,"toCLFDate");var oa=(0,ia.debug)("zuplo:runtime"),yl="X-Amzn-Trace-Id",bl="x-amzn-errortype",sa=[],wl=i(async(n,e,t)=>{let r=t;for await(let o of sa)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),Te=class extends _{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(yl)??void 0,this.errorType=t.get(bl)??void 0}},Rl={addSendingAwsLambdaEventHook:n=>{sa.push(n)}};async function Pl(n,e){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 gt({accessKeyId:t,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(oa(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,f]=await Tl(n,{binaryMediaTypes:c}),{options:h}=e.route.handler,A;h&&typeof h=="object"&&"payloadFormatVersion"in h&&h.payloadFormatVersion==="2.0"?A=xl(n,e):A=await Il(n,e,{useAwsResourcePathStyle:u}),oa("Calling onSendingAwsLambdaEvent hook");let P=await wl(n,e,A);P.body=p,P.isBase64Encoded=f;let O=await l.fetch(d,{body:JSON.stringify(P)});try{return El(O)}catch(H){if(H instanceof Te){let k=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,k)}throw H}}i(Pl,"awsLambdaHandler");async function El(n){let e;try{e=await n.json()}catch{throw new Te("Lambda response did not contain valid JSON",n.headers)}if(n.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new Te(e.message,n.headers):new Te(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new Te(e.errorMessage,n.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:n.status,headers:{"content-type":"application/json"}});let t=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new Te(`Response headers must be an object. Received ${typeof e.headers}`,n.headers);for(let[o,s]of Object.entries(e.headers))t.set(o,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new Te(`Response cookies must be an array. Received ${typeof e.cookies}`,n.headers);t.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new Te(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,n.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new Te("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new Te("Response was set to base64 encoded but body was not a string",n.headers);r=na(e.body)}else"body"in e&&typeof e.body=="string"?r=e.statusCode===204&&e.body===""?null:e.body:"body"in e&&e.body!==null&&e.body!==void 0?r=JSON.stringify(e.body):r=null;if(r!==null&&"bodyEncoding"in e){if(typeof e.bodyEncoding!="string"||!(e.bodyEncoding==="gzip"||e.bodyEncoding==="deflate"))throw new Te(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,n.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:t,status:e.statusCode})}i(El,"getResponse");async function Il(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:po(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Sl(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}i(Il,"buildEventVersion1");function xl(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:po(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}i(xl,"buildEventVersion2");async function Tl(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&&vl(e,o)){let s=await n.arrayBuffer();t=ra(new Uint8Array(s)),r=!0}else t=await n.clone().text();return[t,r]}i(Tl,"getBodyResult");function vl(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}i(vl,"matchesContentType");function Sl(n,e=!1){if(!e)return n;let t=ao(n),r=Ys(n),o={};return t.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),r(o)}i(Sl,"getResourcePath");var Ol=[502,503,504];async function ht(n,e){if(Ol.includes(n.status)){let t=te.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(ht,"logBadGatewayResponses");var mo;function We(n){if(mo===void 0){let t=g.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),mo=t}return n.log[mo]}i(We,"getHandlerUserLogFunction");async function Cl(n,e){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=Al(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 q.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 ht(l,e),l}i(Cl,"openApiSpecHandler");var Al=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 _l(n,e){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(_l,"redirectHandler");function Ll(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(Ll,"join");async function kl(n,e){let t=We(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=Ll(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();t(`URL Forwarding to '${l}'`);let p=await q.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`),ht(p,e),p}i(kl,"urlForwardHandler");var Nl=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 Ml(n,e){let t=We(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?Nl(u,n.url):u,l=Date.now();t(`URL Rewriting to '${c}'`);let d=await q.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`),ht(d,e),d}i(Ml,"urlRewriteHandler");async function Dl(n,e){let t=e.route.handler.options,r=We(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 q.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(Dl,"webSocketHandler");var go=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"),aa=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 ua(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 aa(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(ua,"wireUpListeners");async function Ul(n,e){let t=e.route.handler.options,r=We(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 q.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let O=await c.text(),H=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${O}'`;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?go(t.policies.inbound,"inbound"):[],P=t.policies&&t.policies.outbound?go(t.policies.outbound,"outbound"):[];return ua(p,h,n,e,A),ua(h,p,n,e,P),new Response(null,{status:101,webSocket:d})}i(Ul,"webSocketPipelineHandler");var fo=class extends pe{constructor(t){super();this.options=t}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new ho(this.options)}},ho=class{static{i(this,"DynaTraceTransport")}constructor(e){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:qe(we(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 q.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 yo=class extends pe{constructor(t){super();this.options=t}static{i(this,"LokiLoggingPlugin")}getTransport(){return new wo(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 Hl(n,e){return btoa(`${n}:${e}`)}i(Hl,"createBasicDigest");var wo=class{static{i(this,"LokiTransport")}constructor(e){this.#n=e.url,this.#r=Hl(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:qe(we(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 q.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 Ro=class extends pe{constructor(t){super();this.options=t}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new Po(this.options)}},Po=class{static{i(this,"SumoLogicTransport")}constructor(e){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:qe(we(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 q.fetch(this.#e,{method:"POST",body:t,headers:r})};batcher=new X("sumo-logic-log-transport",10,this.#s)};var Zl="d3a5b78f823648f5b1df4fe269d41172",Eo=class extends pe{constructor(t){super();this.options=t}static{i(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new Io(this.options)}},Io=class{static{i(this,"VMWareLogInsightTransport")}constructor(e){let t;try{t=new URL(e.url),t.pathname==="/"&&(t.pathname=`/api/v1/events/ingest/${e.agentId??Zl}`)}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=$s(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=Jr(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 q.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 X("vmware-log-insights-log-transport",10,this.#a)};var xo=class extends pe{constructor(t){super();this.options=t}static{i(this,"AWSLoggingPlugin")}getTransport(){return new To(this.options)}},To=class{static{i(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new X("aws-log-transport",10,async e=>{if(e.length===0)return;let t=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});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}){this.awsClient=new gt({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:qe(we(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 vo=new WeakMap,ql={tags:[]},So=class extends ze{constructor(t){super();this.options=t}static{i(this,"DataDogMetricsPlugin")}getTransport(){return new Oo(this.options)}static setContext(t,r){let o=vo.get(t);o||(o=ql);let s=Object.assign({...o},r);vo.set(t,s)}},Oo=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 X("data-dog-metrics-transport",10,this.dispatchFunction,te.getLogger(t)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(vo.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 q.fetch(this.#t,{method:"POST",body:t,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new Co(await r.text())}},Co=class n extends Error{static{i(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var Ao=new WeakMap,$l={dimensions:[]},_o=class extends ze{constructor(t){super();this.options=t}static{i(this,"DynatraceMetricsPlugin")}getTransport(){return new Lo(this.options)}static setContext(t,r){let o=Ao.get(t);o||(o=$l);let s=Object.assign({...o},r);Ao.set(t,s)}},Lo=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 X("dynatrace-metrics-transport",10,this.dispatchFunction,te.getLogger(t)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(Ao.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 q.fetch(this.#e,{method:"POST",body:t,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new ko(await r.text())}},ko=class n extends Error{static{i(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var No=class{static{i(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async t=>{await q.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(t)})}))}};var Mo=class extends Ue{static{i(this,"AuditLogPlugin")}constructor(e,t){super(),this.#e=e,this.#t=t}#e;#t;async initialize(e){new Do(e,this.#e,this.#t)}},ca=i(n=>{let e={};return n.forEach((t,r)=>{e[r]=t}),e},"serializableHeaders"),Fl={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},Do=class{static{i(this,"AuditPluginImpl")}constructor(e,t,r){this.#t=t;let o={...Fl};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 X("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?ca(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?ca(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 Uo=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}},De=class extends Uo{static{i(this,"StripeSignatureVerificationError")}header;payload;constructor(e,t,r={}){super(r),this.header=e,this.payload=t}};var jl="v1",Bl=300;async function la(n,e,t,r=Bl,o){return await Vl(n,e,t,r,o),n instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(n)):JSON.parse(n)}i(la,"constructEventAsync");function zl(n,e){return`${e.timestamp}.${n}`}i(zl,"makeHMACContent");async function Vl(n,e,t,r,o){let{decodedHeader:s,decodedPayload:a,details:u,suspectPayloadType:c}=Gl(n,e,jl),l=/\s/.test(t),d=await Yl(zl(a,u),t);return Wl(a,s,u,d,r,c,l,o)}i(Vl,"verifyHeaderAsync");function Gl(n,e,t){if(!n)throw new De(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 De(e,n,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=Jl(a,t);if(!u||u.timestamp===-1)throw new De(a,s,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new De(a,s,{message:"No signatures found with expected scheme"});return{decodedPayload:s,decodedHeader:a,details:u,suspectPayloadType:r}}i(Gl,"parseEventDetails");function Wl(n,e,t,r,o,s,a,u){let c=!!t.signatures.filter(f=>Kl(f,r)).length,l=`
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
-
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 De(e,n,{message:`Webhook payload must be provided as a string or a Buffer (https://nodejs.org/api/buffer.html) instance representing the _raw_ request body.Payload was provided as a parsed JavaScript object instead.
66
- Signature verification is impossible without access to the original signed material.
67
- `+l+`
68
- `+d}):new De(e,n,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
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
- `+l+`
71
- `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new De(e,n,{message:"Timestamp outside the tolerance zone"});return!0}i(Wl,"validateComputedSignature");function Jl(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(Jl,"parseHeader");function Kl(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(Kl,"secureCompare");async function Yl(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]=Ho[s[u]];return a.join("")}i(Yl,"computeHMACSignatureAsync");var Ho=new Array(256);for(let n=0;n<Ho.length;n++)Ho[n]=n.toString(16).padStart(2,"0");function oe(n,e,t="policy",r){let o=`${t} '${e}'`;if(!nt(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 Vt=class extends be{static{i(this,"StripeWebhookVerificationInboundPolicy")}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 da(n){return n!==null&&typeof n=="object"&&"id"in n&&Ie(n.id)&&"type"in n&&Ie(n.type)}i(da,"isStripeWebhookEvent");var Xl={getSubscription:async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await q.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 _(s)}return o},getCustomer:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await q.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 _(s)}return o},getUpcomingInvoice:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await q.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 _(s)}return o}},Cn=Xl;var Zo="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",pa="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`,Zo);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:pa,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await Re({retryDelayMs:5,retries:2,logger:te.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 _(h)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(ma,"createConsumer");async function ga({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=g.instance,u=new URL(`/v1/buckets/${n}/consumers`,Zo);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:pa,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await Re({retryDelayMs:5,retries:2,logger:te.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 _(f)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(ga,"createConsumerInvite");async function fa({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=g.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,Zo);o.searchParams.set("with-api-key","true");let s=await Re({retryDelayMs:5,retries:2,logger:te.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 _(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(fa,"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(!dt(p))throw new Y("No Zuplo JWT token set.");let h=await Re({retryDelayMs:5,retries:2,logger:te.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,O="";try{P=await h.json(),O=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 _(`${A} ${O}`)}n.log.info("Successfully created monetization subscription.",d)}i(ha,"createSubscription");async function yt({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=g.instance;if(!dt(o))throw new Y("No Zuplo JWT token set.");let a=await Re({retryDelayMs:5,retries:2,logger:te.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 _(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}i(yt,"updateSubscription");async function bt({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=g.instance;if(!dt(o))throw new Y("No Zuplo JWT token set.");let a=await Re({retryDelayMs:5,retries:2,logger:te.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 _(`${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 _(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 _(c)}return u.data[0]}i(bt,"getSubscription");var ie="Skipping since we're unable to process the webhook event.",Je="Successfully processed the webhook event",Ee="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function An(n){return n.replaceAll("_","-")}i(An,"stripeStatusToMeteringStatus");function st(n){return new Date(n*1e3).toISOString()}i(st,"unixTimestampToISOString");async function qo(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:ie,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:ie,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:ie,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:ie,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ee});let u=s.product,c,l,d;try{if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_email&&t.data.object.metadata.zuplo_created_by_sub)l=t.data.object.metadata.zuplo_created_by_email,d=t.data.object.metadata.zuplo_created_by_sub,c=await ma({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await Cn.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:ie,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await ga({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:ie,detail:p.message})}if(!c)return x.ok(n,e,{title:ie,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=An(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:st(t.data.object.trial_end),trialStartDate:st(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 fa({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),x.ok(n,e,{title:ie,detail:p.message})}return x.ok(n,e,{title:Je})}i(qo,"onCustomerSubscriptionCreated");async function $o(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:ie,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:ie,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:ie,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ee});try{let a=await bt({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});await yt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return x.ok(n,e,{title:ie,detail:`The event 'customer.subscription.deleted' could not be processed. ${a.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. `+Ee})}return x.ok(n,e,{title:Je})}i($o,"onCustomerSubscriptionDeleted");async function Fo(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:ie,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:ie,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:ie,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ee});if(t.data.previous_attributes){let a=t.data.previous_attributes;if(a.status&&a.status!==t.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${t.id}'.`);let u=await bt({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=An(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=st(t.data.object.trial_end)),await yt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return x.ok(n,e,{title:ie,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ee})}return x.ok(n,e,{title:Je})}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 bt({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await Cn.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 yt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return x.ok(n,e,{title:ie,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ee})}return x.ok(n,e,{title:Je})}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 bt({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?st(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?st(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await yt({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:ie,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ee})}return x.ok(n,e,{title:Je})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),x.ok(n,e,{title:ie,detail:"This 'customer.subscription.updated' event could not be processed. The Stripe monetization plugin only supports update events for subscription plan changes or subscription status changes."+Ee})}i(Fo,"onCustomerSubscriptionUpdated");var ya=class extends on{constructor(t){super();this.options=t}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(!Ql(f))throw new m(`StripeMonetizationPlugin - The value '${f}' on the property 'primaryDataRegion' is invalid.`);let h=await c.json();if(!da(h))return x.ok(c,l,{title:ie,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+Ee});switch(l.log.info(`Received Stripe webhook event of type '${h.type}' with ID '${h.id}'.`),h.type){case"customer.subscription.created":return await qo(c,l,h,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:f,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await Fo(c,l,h,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:f,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await $o(c,l,h,{meteringBucketId:d});default:return x.ok(c,l,{title:ie,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.`+Ee})}},"stripeWebhookHandler"),s=Ls({inboundPolicies:[new Vt({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 de({processors:[he,s],handler:o,gateway:r}),u=new ae({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function Ql(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}i(Ql,"isMetricsRegion");var wa=new WeakMap,ba={},jo=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){wa.set(e,t)}};async function ed(n,e,t,r){if(!t.statusCodes)throw new m(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=pt(t.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=wa.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new _(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=rt(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=ba[t.apiKey];if(!f){let h=t.apiKey,A=n.headers.get("zm-test-id")??"";f=new X("amberflo-ingest-meter",10,async P=>{try{let O=t.url??"https://app.amberflo.io/ingest",H=await q.fetch(O,{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(O){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${O.message}`),O}}),ba[h]=f}f.enqueue(p),e.waitUntil(f.waitUntilFlushed())}}),n}i(ed,"AmberfloMeteringInboundPolicy");async function _n(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(_n,"sha256");var Ra=new Map;async function me(n,e,t){let r,o=`${n}-${e}`,s=Ra.get(o);return s!==void 0?r=s:(r=`zuplo-policy-${await _n(JSON.stringify({policyName:n,options:t}))}`,Ra.set(n,r)),r}i(me,"getPolicyCacheName");var Pa="key-metadata-cache-type";function td(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}i(td,"getKeyValue");async function Bo(n,e,t,r){if(!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(O=>o.allowUnauthenticatedRequests?n:x.unauthorized(n,e,{detail:O}),"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=td(a,o);if(!u||u==="")return s("No key present");let c=await nd(u),l=await me(r,void 0,o),d=new le(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!==Pa&&te.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let f={key:u},h=await Re({retryDelayMs:5,retries:2,logger:te.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 O=await h.text(),H=JSON.parse(O);e.log.error("Unexpected response from key service",H)}catch{e.log.error("Invalid response from key service")}throw new _(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${h.status}`)}let A=await h.json(),P={isValid:!0,typeId:Pa,user:{sub:A.name,data:A.metadata}};return n.user=P.user,d.put(c,P,o.cacheTtlSeconds),n}i(Bo,"ApiKeyInboundPolicy");async function nd(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(nd,"hashValue");var rd=Bo;import{createRemoteJWKSet as id,jwtVerify as Ia}from"jose";import{createLocalJWKSet as od}from"jose";var zo=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 Vo&&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=od(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 q.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new Go("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new wt("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 wt("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function Ea(n,e,t){let r=new zo(n,e,t);return async(o,s)=>r.getKey(o,s)}i(Ea,"createRemoteJWKSet");var wt=class extends _{static{i(this,"JWKSError")}},Vo=class extends wt{static{i(this,"JWKSNoMatchingKey")}},Go=class extends wt{static{i(this,"JWKSTimeout")}};var Ln={},sd=i((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");if(!Ln[r.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(s=r.useExperimentalInMemoryCache),s){let a=await me(n,void 0,r),u=new le(a,e);Ln[r.jwkUrl]=Ea(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else Ln[r.jwkUrl]=id(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await Ia(t,Ln[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),ad=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 Ia(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),ye=i(async(n,e,t,r)=>{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?sd(r,e):ad,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 ud=i(async(n,e,t,r)=>ye(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var kn=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 q.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 cd=[],Wo=class n extends be{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),oe(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new kn(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 cd)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=Ts(o,c.valueSelector)}catch(d){throw d instanceof m?new m(`${this.policyType} '${this.policyName}' - ${d.message}`):new _(`${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 ld=i(async(n,e,t)=>{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 Nn(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}i(Nn,"extractDateElements");function xa(n,e){return new Date(n,e+1,0).getDate()}i(xa,"getDaysInMonth");function Jo(n,e){return n<=e?e-n:6-n+e+1}i(Jo,"getDaysBetweenWeekdays");var Mn=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=xa(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"?Jo(d,p):Jo(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=Nn(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=Nn(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}=Nn(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 dd={min:0,max:59},pd={min:0,max:59},md={min:0,max:23},gd={min:1,max:31},fd={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"}},hd={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},yd={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 1 *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@hourly":"0 * * * *","@minutely":"* * * * *"};function at(n,e){let t=new Set;if(n==="*"){for(let d=e.min;d<=e.max;d=d+1)t.add(d);return t}let r=n.split(",");if(r.length>1)return r.forEach(d=>{at(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(at,"parseElement");function Ko(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=yd[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 Mn({seconds:at(t,dd),minutes:at(r,pd),hours:at(o,md),days:at(s,gd),months:new Set(Array.from(at(a,fd)).map(c=>c-1)),weekdays:new Set(Array.from(at(u,hd)).map(c=>c%7))})}i(Ko,"parseCronExpression");var Yo=class extends be{static{i(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),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=[Ko(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>Ko(r))}async handler(e,t){let r=new Date;if(r.setSeconds(0),r.setMilliseconds(0),this.crons.some(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 bd=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function wd(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(wd,"digestMessage");var Rd=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 wd(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 Pd(n,e,t,r){let o=await me(r,t.cacheId,t),s=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Rd(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);bd.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(Pd,"CachingInboundPolicy");var Ed=i(async(n,e,t,r)=>{if(!t.method)throw new m(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new ne(n,{method:t.method})},"ChangeMethodInboundPolicy");var Id=i(async(n,e,t)=>{let r=[...t.exclude??[]],o=new Headers;return r.forEach(a=>{let u=n.headers.get(a);u&&o.set(a,u)}),new ne(n,{headers:o})},"ClearHeadersInboundPolicy");var xd=i(async(n,e,t,r)=>{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 Td=i(async(n,e,t,r)=>{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 vd=i(async(n,e,t,r)=>{if(!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 Sd=i(async(n,e,t,r)=>{if(!t.policies||t.policies.length===0)throw new m(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=ge.instance,s=Dt(t.policies,o?.routeData.policies);return Vr(s)(n,e)},"CompositeInboundPolicy");var Od=i(async(n,e,t,r)=>{let o=n.headers.get("Authorization");if(!o)return x.unauthorized(n,e,{detail:"No authorization header"});let s=Cd(o);if(!s)return x.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await me(r,void 0,t),u=new le(a,e),c=await u.get(s);if(!c){let l=await q.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 Cd(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(Cd,"getToken");var Ad=i(async(n,e,t,r)=>(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 _d=i(async(n,e,t)=>{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 ne(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var Rt="__unknown__",Ld=i(async(n,e,t,r)=>{let o={allow:{countries:Et(t.allow?.countries,"allow.countries",r),regionCodes:Et(t.allow?.regionCodes,"allow.regionCode",r),asns:Et(t.allow?.asns,"allow.asOrganization",r)},block:{countries:Et(t.block?.countries,"block.countries",r),regionCodes:Et(t.block?.regionCodes,"block.regionCode",r),asns:Et(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??Rt,a=e.incomingRequestProperties.regionCode?.toLowerCase()??Rt,u=e.incomingRequestProperties.asn?.toString()??Rt,c=o.ignoreUnknown&&s===Rt,l=o.ignoreUnknown&&a===Rt,d=o.ignoreUnknown&&u===Rt,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 Pt(n,e,r,s,a,u);let A=o.block.countries,P=o.block.regionCodes,O=o.block.asns;return A.length>0&&A.includes(s)&&!c||P.length>0&&P.includes(a)&&!l||O.length>0&&O.includes(u)&&!d?Pt(n,e,r,s,a,u):n},"GeoFilterInboundPolicy");function Pt(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(Pt,"blockedResponse");function Et(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(Et,"toLowerStringArray");var kd=i(async(n,e,t)=>{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 Nd=i(async(n,e,t,r)=>{let o=e.route.raw().responses;if(!o)return Xo(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 Xo(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 Ta(a[u])}else return a.length>0?Ta(a[0]):Xo(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 Ta(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(Ta,"generateResponse");var Xo=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 Md="Incoming",Dd={logRequestBody:!0,logResponseBody:!0};function va(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}i(va,"headersToObject");function Sa(){return new Date().toISOString()}i(Sa,"timestamp");var Qo=new WeakMap,Ud={};function Hd(n,e){let t=Qo.get(n);t||(t=Ud);let r=Object.assign({...t},e);Qo.set(n,r)}i(Hd,"setMoesifContext");async function Oa(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(Oa,"readBody");var Zd={},ei;function Ca(){if(!ei)throw new _("Invalid State - no _lastLogger");return ei}i(Ca,"getLastLogger");function qd(n){let e=Zd[n];return e||(e=new X("moesif-inbound",100,async t=>{let r=JSON.stringify(t);Ca().debug("posting",r);let o=await q.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||Ca().error({status:o.status,body:await o.text()})})),e}i(qd,"getDispatcher");async function $d(n,e,t,r){ei=e.log;let o=Sa(),s=Object.assign(Dd,t);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await Oa(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=qd(s.applicationId),d=n.headers.get("true-client-ip"),p=Qo.get(e)??{},f={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:va(n.headers)},h=s.logResponseBody?await Oa(u,e):void 0,A={time:Sa(),status:u.status,headers:va(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:Md};l.enqueue(P),e.waitUntil(l.waitUntilFlushed())}),n}i($d,"MoesifInboundPolicy");async function Aa(n,e,t,r){let o=te.getLogger(n),{authApiJWT:s,meteringServiceUrl:a}=g.instance,u;try{let l=await q.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(Aa,"loadSubscription");async function _a(n,e,t,r,o){let{authApiJWT:s,meteringServiceUrl:a}=g.instance,u=te.getLogger(n);try{let c=await q.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(_a,"consumeSubcriptionQuotas");var Fd=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function Dn(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(Dn,"validateMeters");function La(n,e){if(n)try{if(n.length===0)throw new m("Must set valid subscription statuses");let t=ot(n),r=[];for(let o of t)Fd.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(La,"parseAllowedSubscriptionStatuses");function ka(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(ka,"compareMeters");var ti=class extends be{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return Ce.get(e,Ot)}static setMeters(e,t){Dn(t,"setMeters"),Ce.set(e,nn,t)}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=pt(this.options.meterOnStatusCodes),s=Ce.get(t,nn),a={...this.options.meters,...s};Dn(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=La(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(P,O,H)=>{let k=Ce.get(H,Ot);if((this.options.allowRequestsWithoutSubscription??!1)&&!k){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=Ce.get(H,nn),j={...this.options.meters,...Z};if(Dn(j,this.policyName),o.includes(P.status)&&k&&j){H.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${k.id}' with meters '${JSON.stringify(j)} on response status '${P.status}'`);let{metersInSubscription:R,metersNotInSubscription:M}=ka(k.meters,j);if(M&&Object.keys(M).length>0){let B=Object.keys(M);H.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${B}'`)}await _a(H,k.id,this.policyName,this.options.bucketId,R)}});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 Aa(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`),Ce.set(t,Ot,p));let f=Ce.get(t,Ot);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 jd=i(async(n,e,t,r)=>ye(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");import{importSPKI as Bd}from"jose";var ni,zd=i(async(n,e,t,r)=>{if(!ni)try{ni=await Bd(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return ye(n,e,{issuer:t.authUrl,secret:ni,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Ha=Ke(je());var Ma=Ke(je());var Un=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},ri=class extends Un{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},oi=class extends Un{static{i(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function Vd(n,e){if(Is(n))throw new ri(e)}i(Vd,"throwIfUndefinedOrNull");function Gt(n,e){if(Vd(n,e),!Ie(n))throw new oi(e,"string")}i(Gt,"throwIfNotString");var Hn=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 Gt(e,"redisClientUrl"),Gt(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}){Gt(e,"url");let s=await q.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)}`)}},Zn=class{static{i(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:t,method:r}){if(Gt(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 redis client only supports /rate-limit calls")}};var Gd=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"),$n=i(async n=>({key:`ip-${Gd(n)}`}),"getIP"),Fn=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),jn=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),qn;function Bn(n,e){let t;if(qn)return qn;if(g.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),t=new Zn,qn=t,t;let{authApiJWT:r,redisURL:o}=g.instance;if(!Ie(o))throw new Y(`RateLimitInboundPolicy '${n}' - rate limit service URL not configured`);if(!Ie(r))throw new Y(`RateLimitInboundPolicy '${n}' - service authentication not configured`);if(o&&(t=Hn.initialize(o,r,g.instance.deploymentName??"unknown",g.instance.systemUserAgent)),!t||!t.isEnabled())throw new Y(`RateLimitInboundPolicy '${n}' - no redis ('${t}') or redis.isEnabled ('${t?.isEnabled}) is false`);return qn=t,t}i(Bn,"getRedisClient");async function zn(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(zn,"getCountAndUpdateExpiry");function Vn(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 _(c)}return u},"outerFunction")}i(Vn,"wrapUserFunction");var Gn="Retry-After";var Na=(0,Ma.debug)("zuplo:policies:RateLimitInboundPolicy"),Da=i(async(n,e,t,r)=>{let o=te.getLogger(e),s=i((R,M)=>{let B={};return(!R||R==="retry-after")&&(B[Gn]=M.toString()),x.tooManyRequests(n,e,void 0,B)},"rateLimited"),u={function:Vn(t,r),user:Fn,ip:$n,all:jn}[t.rateLimitBy],c=await u(n,e,r),l=c.key,d=c.requestsAllowed??t.requestsAllowed,p=c.timeWindowMinutes??t.timeWindowMinutes,f=t.headerMode??"retry-after",h=Bn(r,o),P=`bucket/${g.instance.build.BUILD_ID}/${r}/${l}`,O=await me(r,void 0,t),H=new le(O,e),k=zn(P,p,h,o,e.requestId),F;i(async()=>{let R=await k;if(R.count>d){let M=Date.now()+R.ttlSeconds*1e3;H.put(P,M,R.ttlSeconds),Na(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${P}' (async mode)`),F=s(f,R.ttlSeconds)}},"asyncCheck")();let j=await H.get(P);if(j!==void 0&&j>Date.now()){Na(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${P}' (async mode)`);let R=Math.round((j-Date.now())/1e3);return s(f,R)}return e.addResponseSendingHook(async R=>F??R),n},"AsyncRateLimitInboundPolicy");var Ua=(0,Ha.debug)("zuplo:policies:RateLimitInboundPolicy"),Wd="strict",Za=i(async(n,e,t,r)=>{if((t.mode??Wd)==="async")return Da(n,e,t,r);let s=Date.now(),a=te.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[Gn]=d.toString()),x.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d={function:Vn(t,r),user:Fn,ip:$n,all:jn}[t.rateLimitBy],p=await d(n,e,r),f=p.key,h=p.requestsAllowed??t.requestsAllowed,A=p.timeWindowMinutes??t.timeWindowMinutes,P=t.headerMode??"retry-after",O=Bn(r,a),k=`bucket/${g.instance.build.BUILD_ID}/${r}/${f}`,F=await zn(k,A,O,a,e.requestId);return F.count>h?(Ua(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${k}' (strict mode)`),c(P,F.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-s;Ua(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var ii;function qa(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}i(qa,"headersToNameValuePairs");function Jd(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}i(Jd,"queryToNameValueParis");function Kd(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}i(Kd,"parseIntOrUndefined");var $a={};async function Yd(n,e,t,r){let o=new Date,s=Date.now();return ii||(ii={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?rt(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?rt(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:ii,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:qa(n.headers),queryString:Jd(n.query)},response:{status:a.status,statusText:a.statusText,headers:qa(a.headers),content:{size:Kd(n.headers.get("content-length"))}}}]}}},d=$a[t.apiKey];if(!d){let p=t.apiKey;d=new X("readme-metering-inbound-policy",10,async f=>{try{let h=t.url??"https://metrics.readme.io/request",A=await q.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}}),$a[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}i(Yd,"ReadmeMetricsInboundPolicy");var Xd=i(async(n,e,t,r)=>{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 ne(n,{headers:s})},"RemoveHeadersInboundPolicy");var Qd=i(async(n,e,t,r,o)=>{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 ep=i(async(n,e,t,r)=>{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 ne(s.toString(),n)},"RemoveQueryParamsInboundPolicy");var tp=i(async(n,e,t,r)=>{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 Fa=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),np=i(async(n,e,t)=>{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?Fa():s&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?Fa():n},"RequestSizeLimitInboundPolicy");function rp(n,e,t){return`_${ut(n+"_"+e+"_"+t)}`}i(rp,"getRawOperationDataIdentifierName");function si(n,e,t,r){return`_${ut(n.toLowerCase())}_`+e.toLowerCase()+"_"+t.toLowerCase()+`_${r.toLowerCase()}`}i(si,"getIdForParameterSchema");function ai(n,e,t){return`_${ut(n.toLowerCase())}_`+e.toLowerCase()+`_rb_${ut(t.toLowerCase())}`}i(ai,"getIdForRequestBodySchema");function op(n,e){return`_${ut(n)}__${ut(e)}`}i(op,"getIdForRefSchema");function ut(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(ut,"sanitizedIdentifierName");var It=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"),xt=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=si(t,r,o,c.name),p=ge.instance.schemaValidator[d],f=p(e[c.name]),h=ui(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"),Ae=i((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),_e=i(n=>n==="log-only"||n==="reject-and-log","shouldLog"),Le=i(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),ui=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 ja(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(_e(t.validateBody)&&Ae(n,t.logLevel??"info",A,[r],h),Le(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 _e(t.validateBody)&&Ae(n,t.logLevel??"info",h,[r],[h]),Le(t.validateBody)?A:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=ai(n.route.path,e.method,o),u=ge.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 _e(t.validateBody)&&Ae(n,t.logLevel??"info",h,[r],[h]),Le(t.validateBody)?A:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=ui(l),f=x.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(_e(t.validateBody)&&Ae(n,t.logLevel??"info",d,[r],p),Le(t.validateBody))return f}i(ja,"handleBodyValidation");function Ba(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=It(n),s=xt(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(_e(t.validateHeaders)&&Ae(n,t.logLevel??"info",a,s.invalidValues,s.errors),Le(t.validateHeaders))return u}}i(Ba,"handleHeadersValidation");function za(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=It(n),o=xt(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(_e(t.validatePathParameters)&&Ae(n,t.logLevel??"info",s,o.invalidValues,o.errors),Le(t.validatePathParameters))return a}}i(za,"handlePathParameterValidation");function Va(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=It(n),o=xt(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(_e(t.validateQueryParameters)&&Ae(n,t.logLevel??"info",s,o.invalidValues,o.errors),Le(t.validateQueryParameters))return a}}i(Va,"handleQueryParameterValidation");var Ga=i(async(n,e,t)=>{let r=Va(e,n,t);if(r!==void 0||(r=za(e,n,t),r!==void 0)||(r=Ba(e,n,t),r!==void 0))return r;let o=await ja(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),ip=Ga;var sp=i(async(n,e,t,r)=>{if(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 ap=i(async(n,e,t)=>new ne(n,{body:t.body}),"SetBodyInboundPolicy");var up=i(async(n,e,t,r)=>{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 ne(n,{headers:s})},"SetHeadersInboundPolicy");var cp=i(async(n,e,t,r,o)=>{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 lp=i(async(n,e,t,r)=>{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 ne(s.toString(),n)},"SetQueryParamsInboundPolicy");var dp=i(async(n,e,t,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(n.body,{headers:n.headers,status:r.status,statusText:r.statusText??n.statusText})},"SetStatusOutboundPolicy");var pp=i(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),mp=i(async(n,e,t,r)=>{if(!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new m(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await pp(t.sleepInMs),n},"SleepInboundPolicy");var gp=i(async(n,e,t,r)=>{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 ne))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 _(`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 fp=i(async(n,e,t,r)=>{oe(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await me(r,void 0,t),s=new le(o,e),a=await s.get(r);if(!a){let u=await hp(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 hp(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await Re({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 _("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 _("Response returned from Azure AD is not in the expected format.")}i(hp,"getAccessToken");var Wa="https://accounts.google.com/o/oauth2/token",ci,yp=i(async(n,e,t,r)=>{oe(t,r).required("serviceAccountJson","string"),ci||(ci=await xe.init(t.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},s=await me(r,void 0,t),a=new le(s,e),u=await a.get(r);if(!u){let c=await Ne({serviceAccount:ci,audience:Wa,payload:o}),l=await yn(Wa,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new _("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 bp="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",wp=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],li,Rp=i(async(n,e,t,r)=>{if(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(wp.indexOf(p)!==-1)throw new m(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}li||(li=await xe.init(t.serviceAccountJson));let s=t.userId;if(!s&&!t.userIdPropertyPath){if(!n.user)throw new _("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 _(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=rt(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new _(`Unable to determine user from for the policy ${r}`);let a=await me(r,void 0,t),u=new le(a,e),c={uid:s,claims:o},l=await _n(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await Ne({serviceAccount:li,audience:bp,payload:c}),f=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,h=await Fs(f,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!h.idToken)throw new _("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 di,Pp=i(async(n,e,t,r)=>{oe(t,r).required("audience","string").required("serviceAccountJson","string"),di||(di=await xe.init(t.serviceAccountJson));let o=await Ne({serviceAccount:di,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var Ja="https://www.googleapis.com/oauth2/v4/token",pi,Ep=i(async(n,e,t,r)=>{oe(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),pi||(pi=await xe.init(t.serviceAccountJson));let o={};if(t.scopes&&t.audience)throw new m("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let c=ot(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 me(r,void 0,t),a;t.useMemoryCacheOnly?a=new ct(s):a=new le(s,e);let u=await a.get(r);if(!u){let c=await Ne({serviceAccount:pi,audience:Ja,payload:o}),l=await yn(Ja,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new _("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new _("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 Ip=i(async(n,e,t)=>{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 Ka=i(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=i((P,O)=>e(P,"name",{value:O,configurable:!0}),"__name"),o=i((P,O)=>i(function(){return O||(0,P[t(P)[0]])((O={exports:{}}).exports,O),O.exports},"__require"),"__commonJS"),s=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(P){var O={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(k,F){return F},attributeValueProcessor:function(k,F){return F},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(k,F,Z){return k}},H=r(function(k){return Object.assign({},O,k)},"buildOptions");P.buildOptions=H,P.defaultOptions=O}}),a=o({"node_modules/fast-xml-parser/src/util.js"(P){"use strict";var O=":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=O+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",k="["+O+"]["+H+"]*",F=new RegExp("^"+k+"$"),Z=r(function(R,M){let B=[],G=M.exec(R);for(;G;){let v=[];v.startIndex=M.lastIndex-G[0].length;let I=G.length;for(let U=0;U<I;U++)v.push(G[U]);B.push(v),G=M.exec(R)}return B},"getAllMatches"),j=r(function(R){let M=F.exec(R);return!(M===null||typeof M>"u")},"isName");P.isExist=function(R){return typeof R<"u"},P.isEmptyObject=function(R){return Object.keys(R).length===0},P.merge=function(R,M,B){if(M){let G=Object.keys(M),v=G.length;for(let I=0;I<v;I++)B==="strict"?R[G[I]]=[M[G[I]]]:R[G[I]]=M[G[I]]}},P.getValue=function(R){return P.isExist(R)?R:""},P.isName=j,P.getAllMatches=Z,P.nameRegexp=k}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(P,O){"use strict";var H=class{static{i(this,"XmlNode")}static{r(this,"XmlNode")}constructor(k){this.tagname=k,this.child=[],this[":@"]={}}add(k,F){k==="__proto__"&&(k="#__proto__"),this.child.push({[k]:F})}addChild(k){k.tagname==="__proto__"&&(k.tagname="#__proto__"),k[":@"]&&Object.keys(k[":@"]).length>0?this.child.push({[k.tagname]:k.child,":@":k[":@"]}):this.child.push({[k.tagname]:k.child})}};O.exports=H}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(P,O){var H=a();function k(v,I){let U={};if(v[I+3]==="O"&&v[I+4]==="C"&&v[I+5]==="T"&&v[I+6]==="Y"&&v[I+7]==="P"&&v[I+8]==="E"){I=I+9;let ue=1,K=!1,Q=!1,ve="";for(;I<v.length;I++)if(v[I]==="<"&&!Q){if(K&&j(v,I))I+=7,[entityName,val,I]=F(v,I+1),val.indexOf("&")===-1&&(U[G(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(K&&R(v,I))I+=8;else if(K&&M(v,I))I+=8;else if(K&&B(v,I))I+=9;else if(Z)Q=!0;else throw new Error("Invalid DOCTYPE");ue++,ve=""}else if(v[I]===">"){if(Q?v[I-1]==="-"&&v[I-2]==="-"&&(Q=!1,ue--):ue--,ue===0)break}else v[I]==="["?K=!0:ve+=v[I];if(ue!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:U,i:I}}i(k,"readDocType"),r(k,"readDocType");function F(v,I){let U="";for(;I<v.length&&v[I]!=="'"&&v[I]!=='"';I++)U+=v[I];if(U=U.trim(),U.indexOf(" ")!==-1)throw new Error("External entites are not supported");let ue=v[I++],K="";for(;I<v.length&&v[I]!==ue;I++)K+=v[I];return[U,K,I]}i(F,"readEntityExp"),r(F,"readEntityExp");function Z(v,I){return v[I+1]==="!"&&v[I+2]==="-"&&v[I+3]==="-"}i(Z,"isComment"),r(Z,"isComment");function j(v,I){return v[I+1]==="!"&&v[I+2]==="E"&&v[I+3]==="N"&&v[I+4]==="T"&&v[I+5]==="I"&&v[I+6]==="T"&&v[I+7]==="Y"}i(j,"isEntity"),r(j,"isEntity");function R(v,I){return v[I+1]==="!"&&v[I+2]==="E"&&v[I+3]==="L"&&v[I+4]==="E"&&v[I+5]==="M"&&v[I+6]==="E"&&v[I+7]==="N"&&v[I+8]==="T"}i(R,"isElement"),r(R,"isElement");function M(v,I){return v[I+1]==="!"&&v[I+2]==="A"&&v[I+3]==="T"&&v[I+4]==="T"&&v[I+5]==="L"&&v[I+6]==="I"&&v[I+7]==="S"&&v[I+8]==="T"}i(M,"isAttlist"),r(M,"isAttlist");function B(v,I){return v[I+1]==="!"&&v[I+2]==="N"&&v[I+3]==="O"&&v[I+4]==="T"&&v[I+5]==="A"&&v[I+6]==="T"&&v[I+7]==="I"&&v[I+8]==="O"&&v[I+9]==="N"}i(B,"isNotation"),r(B,"isNotation");function G(v){if(H.isName(v))return v;throw new Error(`Invalid entity name ${v}`)}i(G,"validateEntityName"),r(G,"validateEntityName"),O.exports=k}}),l=o({"../../node_modules/strnum/strnum.js"(P,O){var H=/^[-+]?0x[a-fA-F0-9]+$/,k=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var F={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function Z(R,M={}){if(M=Object.assign({},F,M),!R||typeof R!="string")return R;let B=R.trim();if(M.skipLike!==void 0&&M.skipLike.test(B))return R;if(M.hex&&H.test(B))return Number.parseInt(B,16);{let G=k.exec(B);if(G){let v=G[1],I=G[2],U=j(G[3]),ue=G[4]||G[6];if(!M.leadingZeros&&I.length>0&&v&&B[2]!==".")return R;if(!M.leadingZeros&&I.length>0&&!v&&B[1]!==".")return R;{let K=Number(B),Q=""+K;return Q.search(/[eE]/)!==-1||ue?M.eNotation?K:R:B.indexOf(".")!==-1?Q==="0"&&U===""||Q===U||v&&Q==="-"+U?K:R:I?U===Q||v+U===Q?K:R:B===Q||B===v+Q?K:R}}else return R}}i(Z,"toNumber"),r(Z,"toNumber");function j(R){return R&&R.indexOf(".")!==-1&&(R=R.replace(/0+$/,""),R==="."?R="0":R[0]==="."?R="0"+R:R[R.length-1]==="."&&(R=R.substr(0,R.length-1))),R}i(j,"trimZeros"),r(j,"trimZeros"),O.exports=Z}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(P,O){"use strict";var H=a(),k=u(),F=c(),Z=l(),j=class{static{i(this,"OrderedObjParser")}static{r(this,"OrderedObjParser")}constructor(w){this.options=w,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,C)=>String.fromCharCode(Number.parseInt(C,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(E,C)=>String.fromCharCode(Number.parseInt(C,16))}},this.addExternalEntities=R,this.parseXml=I,this.parseTextData=M,this.resolveNameSpace=B,this.buildAttributesMap=v,this.isItStopNode=Q,this.replaceEntitiesValue=ue,this.readStopNodeData=V,this.saveTextToParentTag=K,this.addChild=U}};function R(w){let E=Object.keys(w);for(let C=0;C<E.length;C++){let z=E[C];this.lastEntities[z]={regex:new RegExp("&"+z+";","g"),val:w[z]}}}i(R,"addExternalEntities"),r(R,"addExternalEntities");function M(w,E,C,z,L,N,ee){if(w!==void 0&&(this.options.trimValues&&!z&&(w=w.trim()),w.length>0)){ee||(w=this.replaceEntitiesValue(w));let $=this.options.tagValueProcessor(E,w,C,L,N);return $==null?w:typeof $!=typeof w||$!==w?$:this.options.trimValues?ce(w,this.options.parseTagValue,this.options.numberParseOptions):w.trim()===w?ce(w,this.options.parseTagValue,this.options.numberParseOptions):w}}i(M,"parseTextData"),r(M,"parseTextData");function B(w){if(this.options.removeNSPrefix){let E=w.split(":"),C=w.charAt(0)==="/"?"/":"";if(E[0]==="xmlns")return"";E.length===2&&(w=C+E[1])}return w}i(B,"resolveNameSpace"),r(B,"resolveNameSpace");var G=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function v(w,E,C){if(!this.options.ignoreAttributes&&typeof w=="string"){let z=H.getAllMatches(w,G),L=z.length,N={};for(let ee=0;ee<L;ee++){let $=this.resolveNameSpace(z[ee][1]),D=z[ee][4],se=this.options.attributeNamePrefix+$;if($.length)if(this.options.transformAttributeName&&(se=this.options.transformAttributeName(se)),se==="__proto__"&&(se="#__proto__"),D!==void 0){this.options.trimValues&&(D=D.trim()),D=this.replaceEntitiesValue(D);let re=this.options.attributeValueProcessor($,D,E);re==null?N[se]=D:typeof re!=typeof D||re!==D?N[se]=re:N[se]=ce(D,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(N[se]=!0)}if(!Object.keys(N).length)return;if(this.options.attributesGroupName){let ee={};return ee[this.options.attributesGroupName]=N,ee}return N}}i(v,"buildAttributesMap"),r(v,"buildAttributesMap");var I=r(function(w){w=w.replace(/\r\n?/g,`
72
- `);let E=new k("!xml"),C=E,z="",L="";for(let N=0;N<w.length;N++)if(w[N]==="<")if(w[N+1]==="/"){let $=y(w,">",N,"Closing Tag is not closed."),D=w.substring(N+2,$).trim();if(this.options.removeNSPrefix){let Oe=D.indexOf(":");Oe!==-1&&(D=D.substr(Oe+1))}this.options.transformTagName&&(D=this.options.transformTagName(D)),C&&(z=this.saveTextToParentTag(z,C,L));let se=L.substring(L.lastIndexOf(".")+1);if(D&&this.options.unpairedTags.indexOf(D)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${D}>`);let re=0;se&&this.options.unpairedTags.indexOf(se)!==-1?(re=L.lastIndexOf(".",L.lastIndexOf(".")-1),this.tagsNodeStack.pop()):re=L.lastIndexOf("."),L=L.substring(0,re),C=this.tagsNodeStack.pop(),z="",N=$}else if(w[N+1]==="?"){let $=S(w,N,!1,"?>");if(!$)throw new Error("Pi Tag is not closed.");if(z=this.saveTextToParentTag(z,C,L),!(this.options.ignoreDeclaration&&$.tagName==="?xml"||this.options.ignorePiTags)){let D=new k($.tagName);D.add(this.options.textNodeName,""),$.tagName!==$.tagExp&&$.attrExpPresent&&(D[":@"]=this.buildAttributesMap($.tagExp,L,$.tagName)),this.addChild(C,D,L)}N=$.closeIndex+1}else if(w.substr(N+1,3)==="!--"){let $=y(w,"-->",N+4,"Comment is not closed.");if(this.options.commentPropName){let D=w.substring(N+4,$-2);z=this.saveTextToParentTag(z,C,L),C.add(this.options.commentPropName,[{[this.options.textNodeName]:D}])}N=$}else if(w.substr(N+1,2)==="!D"){let $=F(w,N);this.docTypeEntities=$.entities,N=$.i}else if(w.substr(N+1,2)==="!["){let $=y(w,"]]>",N,"CDATA is not closed.")-2,D=w.substring(N+9,$);z=this.saveTextToParentTag(z,C,L);let se=this.parseTextData(D,C.tagname,L,!0,!1,!0,!0);se==null&&(se=""),this.options.cdataPropName?C.add(this.options.cdataPropName,[{[this.options.textNodeName]:D}]):C.add(this.options.textNodeName,se),N=$+2}else{let $=S(w,N,this.options.removeNSPrefix),D=$.tagName,se=$.rawTagName,re=$.tagExp,Oe=$.attrExpPresent,Ri=$.closeIndex;this.options.transformTagName&&(D=this.options.transformTagName(D)),C&&z&&C.tagname!=="!xml"&&(z=this.saveTextToParentTag(z,C,L,!1));let Pi=C;if(Pi&&this.options.unpairedTags.indexOf(Pi.tagname)!==-1&&(C=this.tagsNodeStack.pop(),L=L.substring(0,L.lastIndexOf("."))),D!==E.tagname&&(L+=L?"."+D:D),this.isItStopNode(this.options.stopNodes,L,D)){let Se="";if(re.length>0&&re.lastIndexOf("/")===re.length-1)N=$.closeIndex;else if(this.options.unpairedTags.indexOf(D)!==-1)N=$.closeIndex;else{let Yn=this.readStopNodeData(w,se,Ri+1);if(!Yn)throw new Error(`Unexpected end of ${se}`);N=Yn.i,Se=Yn.tagContent}let Kn=new k(D);D!==re&&Oe&&(Kn[":@"]=this.buildAttributesMap(re,L,D)),Se&&(Se=this.parseTextData(Se,D,L,!0,Oe,!0,!0)),L=L.substr(0,L.lastIndexOf(".")),Kn.add(this.options.textNodeName,Se),this.addChild(C,Kn,L)}else{if(re.length>0&&re.lastIndexOf("/")===re.length-1){D[D.length-1]==="/"?(D=D.substr(0,D.length-1),L=L.substr(0,L.length-1),re=D):re=re.substr(0,re.length-1),this.options.transformTagName&&(D=this.options.transformTagName(D));let Se=new k(D);D!==re&&Oe&&(Se[":@"]=this.buildAttributesMap(re,L,D)),this.addChild(C,Se,L),L=L.substr(0,L.lastIndexOf("."))}else{let Se=new k(D);this.tagsNodeStack.push(C),D!==re&&Oe&&(Se[":@"]=this.buildAttributesMap(re,L,D)),this.addChild(C,Se,L),C=Se}z="",N=Ri}}else z+=w[N];return E.child},"parseXml");function U(w,E,C){let z=this.options.updateTag(E.tagname,C,E[":@"]);z===!1||(typeof z=="string"&&(E.tagname=z),w.addChild(E))}i(U,"addChild"),r(U,"addChild");var ue=r(function(w){if(this.options.processEntities){for(let E in this.docTypeEntities){let C=this.docTypeEntities[E];w=w.replace(C.regx,C.val)}for(let E in this.lastEntities){let C=this.lastEntities[E];w=w.replace(C.regex,C.val)}if(this.options.htmlEntities)for(let E in this.htmlEntities){let C=this.htmlEntities[E];w=w.replace(C.regex,C.val)}w=w.replace(this.ampEntity.regex,this.ampEntity.val)}return w},"replaceEntitiesValue");function K(w,E,C,z){return w&&(z===void 0&&(z=Object.keys(E.child).length===0),w=this.parseTextData(w,E.tagname,C,!1,E[":@"]?Object.keys(E[":@"]).length!==0:!1,z),w!==void 0&&w!==""&&E.add(this.options.textNodeName,w),w=""),w}i(K,"saveTextToParentTag"),r(K,"saveTextToParentTag");function Q(w,E,C){let z="*."+C;for(let L in w){let N=w[L];if(z===N||E===N)return!0}return!1}i(Q,"isItStopNode"),r(Q,"isItStopNode");function ve(w,E,C=">"){let z,L="";for(let N=E;N<w.length;N++){let ee=w[N];if(z)ee===z&&(z="");else if(ee==='"'||ee==="'")z=ee;else if(ee===C[0])if(C[1]){if(w[N+1]===C[1])return{data:L,index:N}}else return{data:L,index:N};else ee===" "&&(ee=" ");L+=ee}}i(ve,"tagExpWithClosingIndex"),r(ve,"tagExpWithClosingIndex");function y(w,E,C,z){let L=w.indexOf(E,C);if(L===-1)throw new Error(z);return L+E.length-1}i(y,"findClosingIndex"),r(y,"findClosingIndex");function S(w,E,C,z=">"){let L=ve(w,E+1,z);if(!L)return;let N=L.data,ee=L.index,$=N.search(/\s/),D=N,se=!0;$!==-1&&(D=N.substring(0,$),N=N.substring($+1).trimStart());let re=D;if(C){let Oe=D.indexOf(":");Oe!==-1&&(D=D.substr(Oe+1),se=D!==L.data.substr(Oe+1))}return{tagName:D,tagExp:N,closeIndex:ee,attrExpPresent:se,rawTagName:re}}i(S,"readTagExp"),r(S,"readTagExp");function V(w,E,C){let z=C,L=1;for(;C<w.length;C++)if(w[C]==="<")if(w[C+1]==="/"){let N=y(w,">",C,`${E} is not closed`);if(w.substring(C+2,N).trim()===E&&(L--,L===0))return{tagContent:w.substring(z,C),i:N};C=N}else if(w[C+1]==="?")C=y(w,"?>",C+1,"StopNode is not closed.");else if(w.substr(C+1,3)==="!--")C=y(w,"-->",C+3,"StopNode is not closed.");else if(w.substr(C+1,2)==="![")C=y(w,"]]>",C,"StopNode is not closed.")-2;else{let N=S(w,C,">");N&&((N&&N.tagName)===E&&N.tagExp[N.tagExp.length-1]!=="/"&&L++,C=N.closeIndex)}}i(V,"readStopNodeData"),r(V,"readStopNodeData");function ce(w,E,C){if(E&&typeof w=="string"){let z=w.trim();return z==="true"?!0:z==="false"?!1:Z(w,C)}else return H.isExist(w)?w:""}i(ce,"parseValue"),r(ce,"parseValue"),O.exports=j}}),p=o({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(P){"use strict";function O(j,R){return H(j,R)}i(O,"prettify"),r(O,"prettify");function H(j,R,M){let B,G={};for(let v=0;v<j.length;v++){let I=j[v],U=k(I),ue="";if(M===void 0?ue=U:ue=M+"."+U,U===R.textNodeName)B===void 0?B=I[U]:B+=""+I[U];else{if(U===void 0)continue;if(I[U]){let K=H(I[U],R,ue),Q=Z(K,R);I[":@"]?F(K,I[":@"],ue,R):Object.keys(K).length===1&&K[R.textNodeName]!==void 0&&!R.alwaysCreateTextNode?K=K[R.textNodeName]:Object.keys(K).length===0&&(R.alwaysCreateTextNode?K[R.textNodeName]="":K=""),G[U]!==void 0&&G.hasOwnProperty(U)?(Array.isArray(G[U])||(G[U]=[G[U]]),G[U].push(K)):R.isArray(U,ue,Q)?G[U]=[K]:G[U]=K}}}return typeof B=="string"?B.length>0&&(G[R.textNodeName]=B):B!==void 0&&(G[R.textNodeName]=B),G}i(H,"compress"),r(H,"compress");function k(j){let R=Object.keys(j);for(let M=0;M<R.length;M++){let B=R[M];if(B!==":@")return B}}i(k,"propName"),r(k,"propName");function F(j,R,M,B){if(R){let G=Object.keys(R),v=G.length;for(let I=0;I<v;I++){let U=G[I];B.isArray(U,M+"."+U,!0,!0)?j[U]=[R[U]]:j[U]=R[U]}}}i(F,"assignAttributes"),r(F,"assignAttributes");function Z(j,R){let{textNodeName:M}=R,B=Object.keys(j).length;return!!(B===0||B===1&&(j[M]||typeof j[M]=="boolean"||j[M]===0))}i(Z,"isLeafTag"),r(Z,"isLeafTag"),P.prettify=O}}),f=o({"node_modules/fast-xml-parser/src/validator.js"(P){"use strict";var O=a(),H={allowBooleanAttributes:!1,unpairedTags:[]};P.validate=function(y,S){S=Object.assign({},H,S);let V=[],ce=!1,w=!1;y[0]==="\uFEFF"&&(y=y.substr(1));for(let E=0;E<y.length;E++)if(y[E]==="<"&&y[E+1]==="?"){if(E+=2,E=F(y,E),E.err)return E}else if(y[E]==="<"){let C=E;if(E++,y[E]==="!"){E=Z(y,E);continue}else{let z=!1;y[E]==="/"&&(z=!0,E++);let L="";for(;E<y.length&&y[E]!==">"&&y[E]!==" "&&y[E]!==" "&&y[E]!==`
73
- `&&y[E]!=="\r";E++)L+=y[E];if(L=L.trim(),L[L.length-1]==="/"&&(L=L.substring(0,L.length-1),E--),!K(L)){let $;return L.trim().length===0?$="Invalid space after '<'.":$="Tag '"+L+"' is an invalid name.",U("InvalidTag",$,Q(y,E))}let N=M(y,E);if(N===!1)return U("InvalidAttr","Attributes for '"+L+"' have open quote.",Q(y,E));let ee=N.value;if(E=N.index,ee[ee.length-1]==="/"){let $=E-ee.length;ee=ee.substring(0,ee.length-1);let D=G(ee,S);if(D===!0)ce=!0;else return U(D.err.code,D.err.msg,Q(y,$+D.err.line))}else if(z)if(N.tagClosed){if(ee.trim().length>0)return U("InvalidTag","Closing tag '"+L+"' can't have attributes or invalid starting.",Q(y,C));{let $=V.pop();if(L!==$.tagName){let D=Q(y,$.tagStartPos);return U("InvalidTag","Expected closing tag '"+$.tagName+"' (opened in line "+D.line+", col "+D.col+") instead of closing tag '"+L+"'.",Q(y,C))}V.length==0&&(w=!0)}}else return U("InvalidTag","Closing tag '"+L+"' doesn't have proper closing.",Q(y,E));else{let $=G(ee,S);if($!==!0)return U($.err.code,$.err.msg,Q(y,E-ee.length+$.err.line));if(w===!0)return U("InvalidXml","Multiple possible root nodes found.",Q(y,E));S.unpairedTags.indexOf(L)!==-1||V.push({tagName:L,tagStartPos:C}),ce=!0}for(E++;E<y.length;E++)if(y[E]==="<")if(y[E+1]==="!"){E++,E=Z(y,E);continue}else if(y[E+1]==="?"){if(E=F(y,++E),E.err)return E}else break;else if(y[E]==="&"){let $=I(y,E);if($==-1)return U("InvalidChar","char '&' is not expected.",Q(y,E));E=$}else if(w===!0&&!k(y[E]))return U("InvalidXml","Extra text at the end",Q(y,E));y[E]==="<"&&E--}}else{if(k(y[E]))continue;return U("InvalidChar","char '"+y[E]+"' is not expected.",Q(y,E))}if(ce){if(V.length==1)return U("InvalidTag","Unclosed tag '"+V[0].tagName+"'.",Q(y,V[0].tagStartPos));if(V.length>0)return U("InvalidXml","Invalid '"+JSON.stringify(V.map(E=>E.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return U("InvalidXml","Start tag expected.",1);return!0};function k(y){return y===" "||y===" "||y===`
74
- `||y==="\r"}i(k,"isWhiteSpace"),r(k,"isWhiteSpace");function F(y,S){let V=S;for(;S<y.length;S++)if(y[S]=="?"||y[S]==" "){let ce=y.substr(V,S-V);if(S>5&&ce==="xml")return U("InvalidXml","XML declaration allowed only at the start of the document.",Q(y,S));if(y[S]=="?"&&y[S+1]==">"){S++;break}else continue}return S}i(F,"readPI"),r(F,"readPI");function Z(y,S){if(y.length>S+5&&y[S+1]==="-"&&y[S+2]==="-"){for(S+=3;S<y.length;S++)if(y[S]==="-"&&y[S+1]==="-"&&y[S+2]===">"){S+=2;break}}else if(y.length>S+8&&y[S+1]==="D"&&y[S+2]==="O"&&y[S+3]==="C"&&y[S+4]==="T"&&y[S+5]==="Y"&&y[S+6]==="P"&&y[S+7]==="E"){let V=1;for(S+=8;S<y.length;S++)if(y[S]==="<")V++;else if(y[S]===">"&&(V--,V===0))break}else if(y.length>S+9&&y[S+1]==="["&&y[S+2]==="C"&&y[S+3]==="D"&&y[S+4]==="A"&&y[S+5]==="T"&&y[S+6]==="A"&&y[S+7]==="["){for(S+=8;S<y.length;S++)if(y[S]==="]"&&y[S+1]==="]"&&y[S+2]===">"){S+=2;break}}return S}i(Z,"readCommentAndCDATA"),r(Z,"readCommentAndCDATA");var j='"',R="'";function M(y,S){let V="",ce="",w=!1;for(;S<y.length;S++){if(y[S]===j||y[S]===R)ce===""?ce=y[S]:ce!==y[S]||(ce="");else if(y[S]===">"&&ce===""){w=!0;break}V+=y[S]}return ce!==""?!1:{value:V,index:S,tagClosed:w}}i(M,"readAttributeStr"),r(M,"readAttributeStr");var B=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function G(y,S){let V=O.getAllMatches(y,B),ce={};for(let w=0;w<V.length;w++){if(V[w][1].length===0)return U("InvalidAttr","Attribute '"+V[w][2]+"' has no space in starting.",ve(V[w]));if(V[w][3]!==void 0&&V[w][4]===void 0)return U("InvalidAttr","Attribute '"+V[w][2]+"' is without value.",ve(V[w]));if(V[w][3]===void 0&&!S.allowBooleanAttributes)return U("InvalidAttr","boolean attribute '"+V[w][2]+"' is not allowed.",ve(V[w]));let E=V[w][2];if(!ue(E))return U("InvalidAttr","Attribute '"+E+"' is an invalid name.",ve(V[w]));if(!ce.hasOwnProperty(E))ce[E]=1;else return U("InvalidAttr","Attribute '"+E+"' is repeated.",ve(V[w]))}return!0}i(G,"validateAttributeString"),r(G,"validateAttributeString");function v(y,S){let V=/\d/;for(y[S]==="x"&&(S++,V=/[\da-fA-F]/);S<y.length;S++){if(y[S]===";")return S;if(!y[S].match(V))break}return-1}i(v,"validateNumberAmpersand"),r(v,"validateNumberAmpersand");function I(y,S){if(S++,y[S]===";")return-1;if(y[S]==="#")return S++,v(y,S);let V=0;for(;S<y.length;S++,V++)if(!(y[S].match(/\w/)&&V<20)){if(y[S]===";")break;return-1}return S}i(I,"validateAmpersand"),r(I,"validateAmpersand");function U(y,S,V){return{err:{code:y,msg:S,line:V.line||V,col:V.col}}}i(U,"getErrorObject"),r(U,"getErrorObject");function ue(y){return O.isName(y)}i(ue,"validateAttrName"),r(ue,"validateAttrName");function K(y){return O.isName(y)}i(K,"validateTagName"),r(K,"validateTagName");function Q(y,S){let V=y.substring(0,S).split(/\r?\n/);return{line:V.length,col:V[V.length-1].length+1}}i(Q,"getLineNumberForPosition"),r(Q,"getLineNumberForPosition");function ve(y){return y.startIndex+y[1].length}i(ve,"getPositionFromMatch"),r(ve,"getPositionFromMatch")}}),h=o({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(P,O){var{buildOptions:H}=s(),k=d(),{prettify:F}=p(),Z=f(),j=class{static{i(this,"XMLParser")}static{r(this,"XMLParser")}constructor(R){this.externalEntities={},this.options=H(R)}parse(R,M){if(typeof R!="string")if(R.toString)R=R.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(M){M===!0&&(M={});let v=Z.validate(R,M);if(v!==!0)throw Error(`${v.err.msg}:${v.err.line}:${v.err.col}`)}let B=new k(this.options);B.addExternalEntities(this.externalEntities);let G=B.parseXml(R);return this.options.preserveOrder||G===void 0?G:F(G,this.options)}addEntity(R,M){if(M.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(R.indexOf("&")!==-1||R.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(M==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[R]=M}};O.exports=j}});let A=h();return new A(n)},"getXmlParser");var mi=class extends Ve{static{i(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),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?pt(e.parseOnStatusCodes):void 0,this.parser=Ka({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 _(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 gi=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 fi=class{static{i(this,"BackgroundDispatcher")}#e;constructor(e,t){if(!t||t.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new X(t.name??"",t.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),Tn().waitUntil(this.#e.waitUntilFlushed())}};var Ya=10,Xa=3e4,hi=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=Xa,this.#r=Ya}else{let r=t;this.#n=r.ttlSeconds*1e3,this.#o=r.loaderTimeoutSeconds?r.loaderTimeoutSeconds*1e3:Xa,this.#r=Ya}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 xp(()=>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);Tn().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 xp(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(xp,"waitUntilTrue");var yi=["sha-1","sha-256","sha-384","sha-512"],Wn=class{static{i(this,"BaseCryptoBeta")}};var bi=class extends Wn{static{i(this,"WorkerCryptoBeta")}async digest(e,t){if(!yi.includes(e.toLowerCase()))throw new _(`Algorithm ${e} is not supported. Try using ${yi.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 Jn=class{constructor(e){this.context=e}static{i(this,"BaseKeyValueStore")}};var wi=class extends Jn{static{i(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let t=g.instance.runtime.ZUPLO_KV;if(!t)throw new en("The Key Value Store feature is not enabled for this project.");this.#e=t}put(e,t,r){if(typeof e!="string")throw new m("value must be of type string");return this.#e.put(e,t,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,t){return this.#e.get(e,{type:"text",cacheTtl:t?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};export{xo as AWSLoggingPlugin,ed as AmberfloMeteringInboundPolicy,jo as AmberfloMeteringPolicy,rd as ApiAuthKeyInboundPolicy,Bo as ApiKeyInboundPolicy,No as AuditLogDataStaxProvider,Mo as AuditLogPlugin,ud as Auth0JwtInboundPolicy,Rl as AwsLambdaHandlerExtensions,Wo as AxiomaticsAuthZInboundPolicy,fi as BackgroundDispatcher,hi as BackgroundLoader,ld as BasicAuthInboundPolicy,Za as BasicRateLimitInboundPolicy,X as BatchDispatch,Yo as BrownoutInboundPolicy,Pd as CachingInboundPolicy,Ed as ChangeMethodInboundPolicy,Id as ClearHeadersInboundPolicy,xd as ClearHeadersOutboundPolicy,Td as ClerkJwtInboundPolicy,vd as CognitoJwtInboundPolicy,Sd as CompositeInboundPolicy,m as ConfigurationError,Ar as ContentTypes,Ce as ContextData,bi as CryptoBeta,Od as CurityPhantomTokenInboundPolicy,to as DataDogLoggingPlugin,So as DataDogMetricsPlugin,fo as DynaTraceLoggingPlugin,_o as DynatraceMetricsPlugin,Ad as FirebaseJwtInboundPolicy,_d as FormDataToJsonInboundPolicy,Ld as GeoFilterInboundPolicy,Kr as GoogleCloudLoggingPlugin,so as Handler,x as HttpProblems,un as HttpStatusCode,be as InboundPolicy,kd as JWTScopeValidationInboundPolicy,wi as KeyValueStore,yo as LokiLoggingPlugin,jt as LookupResult,le as MemoryZoneReadThroughCache,Nd as MockApiInboundPolicy,$d as MoesifInboundPolicy,ti as MonetizationInboundPolicy,jd as OktaJwtInboundPolicy,ye as OpenIdJwtInboundPolicy,Ve as OutboundPolicy,tt as ProblemResponseFormatter,zd as PropelAuthJwtInboundPolicy,Za as RateLimitInboundPolicy,Yd as ReadmeMetricsInboundPolicy,Xd as RemoveHeadersInboundPolicy,Qd as RemoveHeadersOutboundPolicy,ep as RemoveQueryParamsInboundPolicy,tp as ReplaceStringOutboundPolicy,np as RequestSizeLimitInboundPolicy,Ga as RequestValidationInboundPolicy,sp as RequireOriginInboundPolicy,Lt as ResponseSendingEvent,kt as ResponseSentEvent,Bt as Router,_ as RuntimeError,rn as SYSTEM_LOGGER,ip as SchemaBasedRequestValidation,ke as SemanticAttributes,gi as ServiceProviderImpl,ap as SetBodyInboundPolicy,up as SetHeadersInboundPolicy,cp as SetHeadersOutboundPolicy,lp as SetQueryParamsInboundPolicy,dp as SetStatusOutboundPolicy,mp as SleepInboundPolicy,ya as StripeMonetizationPlugin,Vt as StripeWebhookVerificationInboundPolicy,Ro as SumoLogicLoggingPlugin,gp as SupabaseJwtInboundPolicy,Ze as SystemRouteName,Ct as TelemetryPlugin,fp as UpstreamAzureAdServiceAuthInboundPolicy,yp as UpstreamFirebaseAdminAuthInboundPolicy,Rp as UpstreamFirebaseUserAuthInboundPolicy,Pp as UpstreamGcpJwtInboundPolicy,Ep as UpstreamGcpServiceAuthInboundPolicy,Eo as VMWareLogInsightLoggingPlugin,Ip as ValidateJsonSchemaInbound,mi as XmlToJsonOutboundPolicy,St as ZoneCache,ne as ZuploRequest,Pl as awsLambdaHandler,Pe as environment,si as getIdForParameterSchema,op as getIdForRefSchema,ai as getIdForRequestBodySchema,rp as getRawOperationDataIdentifierName,Lr as httpStatuses,Cl as openApiSpecHandler,_l as redirectHandler,ut as sanitizedIdentifierName,_r as serialize,Hd as setMoesifContext,kl as urlForwardHandler,Ml as urlRewriteHandler,Dl as webSocketHandler,Ul as webSocketPipelineHandler};
75
- /*! For license information please see index.min.js.LEGAL.txt */