@zuplo/runtime 6.51.5 → 6.51.7

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 (2) hide show
  1. package/out/esm/index.js +22 -22
  2. package/package.json +1 -1
package/out/esm/index.js CHANGED
@@ -22,17 +22,17 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{a as y,b as Be,e as ye,f as Wu,g as cr,h as lr,i as Ju,j as Ku}from"./chunk-WXV4LG5G.js";import{a as i,b as Gu,c as Vu}from"./chunk-PPV7V43C.js";var oa=Gu(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.parse=Hc;Dn.serialize=$c;var _c=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,Nc=/^[\u0021-\u003A\u003C-\u007E]*$/,Dc=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,Mc=/^[\u0020-\u003A\u003D-\u007E]*$/,qc=Object.prototype.toString,Uc=(()=>{let n=i(function(){},"C");return n.prototype=Object.create(null),n})();function Hc(n,e){let t=new Uc,r=n.length;if(r<2)return t;let o=e?.decode||Zc,s=0;do{let a=n.indexOf("=",s);if(a===-1)break;let u=n.indexOf(";",s),c=u===-1?r:u;if(a>c){s=n.lastIndexOf(";",a-1)+1;continue}let l=na(n,s,a),d=ra(n,a,l),p=n.slice(l,d);if(t[p]===void 0){let m=na(n,a+1,c),h=ra(n,c,m),I=o(n.slice(m,h));t[p]=I}s=c+1}while(s<r);return t}i(Hc,"parse");function na(n,e,t){do{let r=n.charCodeAt(e);if(r!==32&&r!==9)return e}while(++e<t);return t}i(na,"startIndex");function ra(n,e,t){for(;e>t;){let r=n.charCodeAt(--e);if(r!==32&&r!==9)return e+1}return t}i(ra,"endIndex");function $c(n,e,t){let r=t?.encode||encodeURIComponent;if(!_c.test(n))throw new TypeError(`argument name is invalid: ${n}`);let o=r(e);if(!Nc.test(o))throw new TypeError(`argument val is invalid: ${e}`);let s=n+"="+o;if(!t)return s;if(t.maxAge!==void 0){if(!Number.isInteger(t.maxAge))throw new TypeError(`option maxAge is invalid: ${t.maxAge}`);s+="; Max-Age="+t.maxAge}if(t.domain){if(!Dc.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);s+="; Domain="+t.domain}if(t.path){if(!Mc.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);s+="; Path="+t.path}if(t.expires){if(!Fc(t.expires)||!Number.isFinite(t.expires.valueOf()))throw new TypeError(`option expires is invalid: ${t.expires}`);s+="; Expires="+t.expires.toUTCString()}if(t.httpOnly&&(s+="; HttpOnly"),t.secure&&(s+="; Secure"),t.partitioned&&(s+="; Partitioned"),t.priority)switch(typeof t.priority=="string"?t.priority.toLowerCase():void 0){case"low":s+="; Priority=Low";break;case"medium":s+="; Priority=Medium";break;case"high":s+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${t.priority}`)}if(t.sameSite)switch(typeof t.sameSite=="string"?t.sameSite.toLowerCase():t.sameSite){case!0:case"strict":s+="; SameSite=Strict";break;case"lax":s+="; SameSite=Lax";break;case"none":s+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${t.sameSite}`)}return s}i($c,"serialize");function Zc(n){if(n.indexOf("%")===-1)return n;try{return decodeURIComponent(n)}catch{return n}}i(Zc,"decode");function Fc(n){return qc.call(n)==="[object Date]"}i(Fc,"isDate")});var Qu=!1;function dt(n,e){return{open:`\x1B[${n.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}i(dt,"code");function pt(n,e){return Qu?`${e.open}${n.replace(e.regexp,e.open)}${e.close}`:n}i(pt,"run");function Yu(n){return pt(n,dt([31],39))}i(Yu,"red");function Xu(n){return pt(n,dt([32],39))}i(Xu,"green");function ec(n){return pt(n,dt([33],39))}i(ec,"yellow");function tc(n){return pt(n,dt([34],39))}i(tc,"blue");function nc(n){return pt(n,dt([35],39))}i(nc,"magenta");function rc(n){return pt(n,dt([36],39))}i(rc,"cyan");var nm=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");var os=[Yu,Xu,ec,tc,nc,rc];function oc(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(oc,"hashCode");function is(n){let e=Math.abs(oc(n));return os[e%os.length]}i(is,"generateColor");function ss(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(ss,"format");function Ge(n,e,t,r){let o={seen:[],stylize:ic,showHidden:e??!1,depth:t??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=ac),pn(o,n,o.depth)}i(Ge,"inspect");Ge.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]};Ge.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function ic(n,e){return n}i(ic,"stylizeNoColor");function sc(n){return typeof n=="boolean"}i(sc,"isBoolean");function us(n){return n===void 0}i(us,"isUndefined");function ac(n,e){let t=Ge.styles[e];return t?"\x1B["+Ge.colors[t][0]+"m"+n+"\x1B["+Ge.colors[t][1]+"m":n}i(ac,"stylizeWithColor");function dr(n){return typeof n=="function"}i(dr,"isFunction");function cs(n){return typeof n=="string"}i(cs,"isString");function uc(n){return typeof n=="number"}i(uc,"isNumber");function ls(n){return n===null}i(ls,"isNull");function ds(n,e){return Object.prototype.hasOwnProperty.call(n,e)}i(ds,"hasOwn");function pr(n){return hr(n)&&yr(n)==="[object RegExp]"}i(pr,"isRegExp");function hr(n){return typeof n=="object"&&n!==null}i(hr,"isObject");function mr(n){return hr(n)&&(yr(n)==="[object Error]"||n instanceof Error)}i(mr,"isError");function as(n){return hr(n)&&yr(n)==="[object Date]"}i(as,"isDate");function yr(n){return Object.prototype.toString.call(n)}i(yr,"objectToString");function cc(n){let e={};return n.forEach(function(t,r){e[t]=!0}),e}i(cc,"arrayToHash");function lc(n,e,t,r,o){let s=[];for(let a=0,u=e.length;a<u;++a)ds(e,String(a))?s.push(fr(n,e,t,r,String(a),!0)):s.push("");return o.forEach(function(a){a.match(/^\d+$/)||s.push(fr(n,e,t,r,a,!0))}),s}i(lc,"formatArray");function gr(n){return"["+Error.prototype.toString.call(n)+"]"}i(gr,"formatError");function pn(n,e,t){if(n.customInspect&&e&&dr(e.inspect)&&e.inspect!==Ge&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(t,n);return cs(d)||(d=pn(n,d,t)),d}let r=dc(n,e);if(r)return r;let o=Object.keys(e),s=cc(o);try{n.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(mr(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return gr(e);if(o.length===0){if(dr(e)){let d=e.name?": "+e.name:"";return n.stylize("[Function"+d+"]","special")}if(pr(e))return n.stylize(RegExp.prototype.toString.call(e),"regexp");if(as(e))return n.stylize(Date.prototype.toString.call(e),"date");if(mr(e))return gr(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),dr(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),pr(e)&&(a=" "+RegExp.prototype.toString.call(e)),as(e)&&(a=" "+Date.prototype.toUTCString.call(e)),mr(e)&&(a=" "+gr(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(t<0)return pr(e)?n.stylize(RegExp.prototype.toString.call(e),"regexp"):n.stylize("[Object]","special");n.seen.push(e);let l;return u?l=lc(n,e,t,s,o):l=o.map(function(d){return fr(n,e,t,s,d,u)}),n.seen.pop(),pc(l,a,c)}i(pn,"formatValue");function fr(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")),ds(r,o)||(a="["+o+"]"),u||(n.seen.indexOf(c.value)<0?(ls(t)?u=pn(n,c.value,null):u=pn(n,c.value,t-1),u.indexOf(`
25
+ import{a as y,b as Be,e as ye,f as Ku,g as cr,h as lr,i as Qu,j as Yu}from"./chunk-WXV4LG5G.js";import{a as i,b as Wu,c as Ju}from"./chunk-PPV7V43C.js";var sa=Wu(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.parse=Zc;Dn.serialize=Fc;var Dc=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,Mc=/^[\u0021-\u003A\u003C-\u007E]*$/,qc=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,Uc=/^[\u0020-\u003A\u003D-\u007E]*$/,Hc=Object.prototype.toString,$c=(()=>{let n=i(function(){},"C");return n.prototype=Object.create(null),n})();function Zc(n,e){let t=new $c,r=n.length;if(r<2)return t;let o=e?.decode||jc,s=0;do{let a=n.indexOf("=",s);if(a===-1)break;let u=n.indexOf(";",s),c=u===-1?r:u;if(a>c){s=n.lastIndexOf(";",a-1)+1;continue}let l=oa(n,s,a),d=ia(n,a,l),p=n.slice(l,d);if(t[p]===void 0){let m=oa(n,a+1,c),h=ia(n,c,m),I=o(n.slice(m,h));t[p]=I}s=c+1}while(s<r);return t}i(Zc,"parse");function oa(n,e,t){do{let r=n.charCodeAt(e);if(r!==32&&r!==9)return e}while(++e<t);return t}i(oa,"startIndex");function ia(n,e,t){for(;e>t;){let r=n.charCodeAt(--e);if(r!==32&&r!==9)return e+1}return t}i(ia,"endIndex");function Fc(n,e,t){let r=t?.encode||encodeURIComponent;if(!Dc.test(n))throw new TypeError(`argument name is invalid: ${n}`);let o=r(e);if(!Mc.test(o))throw new TypeError(`argument val is invalid: ${e}`);let s=n+"="+o;if(!t)return s;if(t.maxAge!==void 0){if(!Number.isInteger(t.maxAge))throw new TypeError(`option maxAge is invalid: ${t.maxAge}`);s+="; Max-Age="+t.maxAge}if(t.domain){if(!qc.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);s+="; Domain="+t.domain}if(t.path){if(!Uc.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);s+="; Path="+t.path}if(t.expires){if(!zc(t.expires)||!Number.isFinite(t.expires.valueOf()))throw new TypeError(`option expires is invalid: ${t.expires}`);s+="; Expires="+t.expires.toUTCString()}if(t.httpOnly&&(s+="; HttpOnly"),t.secure&&(s+="; Secure"),t.partitioned&&(s+="; Partitioned"),t.priority)switch(typeof t.priority=="string"?t.priority.toLowerCase():void 0){case"low":s+="; Priority=Low";break;case"medium":s+="; Priority=Medium";break;case"high":s+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${t.priority}`)}if(t.sameSite)switch(typeof t.sameSite=="string"?t.sameSite.toLowerCase():t.sameSite){case!0:case"strict":s+="; SameSite=Strict";break;case"lax":s+="; SameSite=Lax";break;case"none":s+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${t.sameSite}`)}return s}i(Fc,"serialize");function jc(n){if(n.indexOf("%")===-1)return n;try{return decodeURIComponent(n)}catch{return n}}i(jc,"decode");function zc(n){return Hc.call(n)==="[object Date]"}i(zc,"isDate")});var Xu=!1;function dt(n,e){return{open:`\x1B[${n.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}i(dt,"code");function pt(n,e){return Xu?`${e.open}${n.replace(e.regexp,e.open)}${e.close}`:n}i(pt,"run");function ec(n){return pt(n,dt([31],39))}i(ec,"red");function tc(n){return pt(n,dt([32],39))}i(tc,"green");function nc(n){return pt(n,dt([33],39))}i(nc,"yellow");function rc(n){return pt(n,dt([34],39))}i(rc,"blue");function oc(n){return pt(n,dt([35],39))}i(oc,"magenta");function ic(n){return pt(n,dt([36],39))}i(ic,"cyan");var om=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");var os=[ec,tc,nc,rc,oc,ic];function sc(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(sc,"hashCode");function is(n){let e=Math.abs(sc(n));return os[e%os.length]}i(is,"generateColor");function ss(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(ss,"format");function Ge(n,e,t,r){let o={seen:[],stylize:ac,showHidden:e??!1,depth:t??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=cc),pn(o,n,o.depth)}i(Ge,"inspect");Ge.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]};Ge.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function ac(n,e){return n}i(ac,"stylizeNoColor");function uc(n){return typeof n=="boolean"}i(uc,"isBoolean");function us(n){return n===void 0}i(us,"isUndefined");function cc(n,e){let t=Ge.styles[e];return t?"\x1B["+Ge.colors[t][0]+"m"+n+"\x1B["+Ge.colors[t][1]+"m":n}i(cc,"stylizeWithColor");function dr(n){return typeof n=="function"}i(dr,"isFunction");function cs(n){return typeof n=="string"}i(cs,"isString");function lc(n){return typeof n=="number"}i(lc,"isNumber");function ls(n){return n===null}i(ls,"isNull");function ds(n,e){return Object.prototype.hasOwnProperty.call(n,e)}i(ds,"hasOwn");function pr(n){return hr(n)&&yr(n)==="[object RegExp]"}i(pr,"isRegExp");function hr(n){return typeof n=="object"&&n!==null}i(hr,"isObject");function mr(n){return hr(n)&&(yr(n)==="[object Error]"||n instanceof Error)}i(mr,"isError");function as(n){return hr(n)&&yr(n)==="[object Date]"}i(as,"isDate");function yr(n){return Object.prototype.toString.call(n)}i(yr,"objectToString");function dc(n){let e={};return n.forEach(function(t,r){e[t]=!0}),e}i(dc,"arrayToHash");function pc(n,e,t,r,o){let s=[];for(let a=0,u=e.length;a<u;++a)ds(e,String(a))?s.push(fr(n,e,t,r,String(a),!0)):s.push("");return o.forEach(function(a){a.match(/^\d+$/)||s.push(fr(n,e,t,r,a,!0))}),s}i(pc,"formatArray");function gr(n){return"["+Error.prototype.toString.call(n)+"]"}i(gr,"formatError");function pn(n,e,t){if(n.customInspect&&e&&dr(e.inspect)&&e.inspect!==Ge&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(t,n);return cs(d)||(d=pn(n,d,t)),d}let r=mc(n,e);if(r)return r;let o=Object.keys(e),s=dc(o);try{n.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(mr(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return gr(e);if(o.length===0){if(dr(e)){let d=e.name?": "+e.name:"";return n.stylize("[Function"+d+"]","special")}if(pr(e))return n.stylize(RegExp.prototype.toString.call(e),"regexp");if(as(e))return n.stylize(Date.prototype.toString.call(e),"date");if(mr(e))return gr(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),dr(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),pr(e)&&(a=" "+RegExp.prototype.toString.call(e)),as(e)&&(a=" "+Date.prototype.toUTCString.call(e)),mr(e)&&(a=" "+gr(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(t<0)return pr(e)?n.stylize(RegExp.prototype.toString.call(e),"regexp"):n.stylize("[Object]","special");n.seen.push(e);let l;return u?l=pc(n,e,t,s,o):l=o.map(function(d){return fr(n,e,t,s,d,u)}),n.seen.pop(),gc(l,a,c)}i(pn,"formatValue");function fr(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")),ds(r,o)||(a="["+o+"]"),u||(n.seen.indexOf(c.value)<0?(ls(t)?u=pn(n,c.value,null):u=pn(n,c.value,t-1),u.indexOf(`
27
27
  `)>-1&&(s?u=u.split(`
28
28
  `).map(function(l){return" "+l}).join(`
29
29
  `).substr(2):u=`
30
30
  `+u.split(`
31
31
  `).map(function(l){return" "+l}).join(`
32
- `))):u=n.stylize("[Circular]","special")),us(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(fr,"formatProperty");function dc(n,e){if(us(e))return n.stylize("undefined","undefined");if(cs(e)){let t="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return n.stylize(t,"string")}if(uc(e))return n.stylize(""+e,"number");if(sc(e))return n.stylize(""+e,"boolean");if(ls(e))return n.stylize("null","null")}i(dc,"formatPrimitive");function pc(n,e,t){let r=0;return n.reduce(function(s,a){return r++,a.indexOf(`
32
+ `))):u=n.stylize("[Circular]","special")),us(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(fr,"formatProperty");function mc(n,e){if(us(e))return n.stylize("undefined","undefined");if(cs(e)){let t="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return n.stylize(t,"string")}if(lc(e))return n.stylize(""+e,"number");if(uc(e))return n.stylize(""+e,"boolean");if(ls(e))return n.stylize("null","null")}i(mc,"formatPrimitive");function gc(n,e,t){let r=0;return n.reduce(function(s,a){return r++,a.indexOf(`
33
33
  `)>=0&&r++,s+a.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?t[0]+(e===""?"":e+`
34
34
  `)+" "+n.join(`,
35
- `)+" "+t[1]:t[0]+e+" "+n.join(", ")+" "+t[1]}i(pc,"reduceToSingleString");var ps=i((n,...e)=>ss(Ge,n,e),"format");var br=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=is(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=ps(t,...e);let s=`${this.color(this.ns)} ${t} ${this.color(`+${o}ms`)}`;console.log(s),this.last=Date.now()}},wr=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function mc(n){return!n||n.length===0?[]:(n=n.replace(/\s/g,"").replace(/\*/g,".+"),n.split(",").map(e=>new RegExp(`^${e}$`)))}i(mc,"extract");var mn;function be(n){let e=globalThis.DEBUG;mn||(mn=new wr(mc(e)));let t=new br(mn,n);return mn.debuggers.set(n,t),Object.assign(t.log.bind(t),{self:t})}i(be,"debug");var Y=class extends Error{static{i(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},k=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"}},g=class extends k{static{i(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}};var rt=be("zuplo:runtime:external-service");function gc(){let n,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=y.instance.runtime;if(e&&e!=="undefined")try{let t=atob(e);n=JSON.parse(t)}catch{}return n}i(gc,"getServiceAuth");async function ms(n,e){let t=gc();if(t)if(rt(`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(y.instance.useLegacyServiceRouting)u=`https://${o}.zuptunnel.com`;else{rt("Using sha256 service routing");let d=y.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE){let p=await fc(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE),m=gs(d.ENVIRONMENT_TYPE),h=await Rr(`${d.ACCOUNT_NAME}-${d.PROJECT_NAME}-${m}`);h==="40d7ad502f5d743997999594c177184a00161a77865423511f3a1ea21eb5a5e"||h==="d05bffe8fa91a300187d2cf43e8aa4a56bd809c442ae10d1ee49af7d29a5a11"?u=`https://${p}.zuptunnel.com`:u=`https://${p}.t.zuplo.app`}else throw rt("Cannot use sha256 service routing, missing build variables"),new k("Failed to generate fully qualified tunnel url.")}let c=new URL(`${u}${r.pathname}${r.search}`);rt(`Calling external service: ${c.toString()}`);let l=await gn(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 k("Could not connect to secure tunnel.");return l}else throw rt("Cannot call external service with Request object"),new k("Currently, we only support fetch(<some_string>, ...).");else throw rt("There is no external service auth configured for this zup."),new k("There are no external services configured for this zup.")}i(ms,"externalServiceHandler");async function fc(n,e,t,r){let o=n.toLowerCase(),s=e.toLowerCase(),a=t.toLowerCase(),u=gs(r);rt(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await Rr(`${s}-${o}`),l=await Rr(`${s}-${a}-${u}`);return`${c}.${l}`}i(fc,"hashServiceName");async function Rr(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(Rr,"hashSegment");function gs(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(gs,"sanitizeEnvironmentType");var fs=new Map;fs.set("service:",ms);var gn=globalThis.fetch;function Pr(n,e){let t=hc(e);if(typeof n=="string"){let r=new URL(n),o=fs.get(r.protocol);return o?o(n,t):gn(n,t)}else return gn(n,t)}i(Pr,"internalFetch");globalThis.fetch=Pr;var hc=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 yc={fetch:Pr},$=yc;Function.prototype.toString=function(){return"[native code]"};var fn=globalThis,hs=fn.caches;if(hs){let n=hs.open;fn.caches.open=function(e){let t=y.instance.deploymentName??y.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete fn.caches.default,Object.freeze(fn.caches)}var hn=new Set,ys=new Set;function f(n){ys.has(n)||(ys.add(n),hn.add(n))}i(f,"trackFeature");function bs(){let n=[...hn];return hn.clear(),n}i(bs,"getUnsentFeatures");function ws(n){for(let e of n)hn.add(e)}i(ws,"restoreFeatures");function De(n,e){n.has("Authorization")||n.set("Authorization",`Bearer ${y.instance.authApiJWT}`),n.set("zp-rid",e??`global-${crypto.randomUUID()}`),n.set("zp-dn",y.instance.deploymentName??"unknown"),n.set("User-Agent",y.instance.systemUserAgent),n.set("zp-compat-date",y.instance.build.COMPATIBILITY_DATE??"none")}i(De,"setZuploHeaders");async function bc(n,e={}){f("utility.zuplo-api-services");let{method:t="GET",data:r}=e,o=new URL(n,y.instance.zuploEdgeApiUrl),s=new Headers(e.headers);De(s),s.set("Content-Type","application/json");let a={method:t,headers:s};r&&(a.body=JSON.stringify(r));let u=await $.fetch(o,a),c;try{if(!u.ok)throw c=await u.clone().json(),new Error(`Error ${u.status}: ${JSON.stringify(c)||"Request failed"}`);if(u.status===204)return;c=await u.clone().json()}catch(l){throw new Error(l.message)}return c}i(bc,"apiServices");var Rs=new Map,Ir=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)})}},Me=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=Rs.get(e);r||(r=new Ir(t),Rs.set(e,r)),this.#e=r}name;#e;get(e){return this.#e.get(e)}put(e,t,r){return this.#e.put(e,t,r)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var Er="__zuplo-expiry-header",Dt=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(Er);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(Er,`${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(Er,`${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 re=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Me(r),this.#n=new Dt(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)}async delete(e){this.#t.delete(e),await this.#n.delete(e)}};var xr="__zuplo-expiry-header",Tr=class{static{i(this,"StreamingZoneCache")}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://streaming-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(xr);if(!s){await t.delete(r).catch(u=>{this.logDebug(`StreamingZoneCache: error deleting missing expiry entry ${e}`,u)});return}let a=parseInt(s,10);if(Date.now()>=a){await t.delete(r).catch(u=>{this.logDebug(`StreamingZoneCache: error deleting expired entry ${e}`,u)});return}return o.body??void 0}catch(t){this.logDebug(`get(${e}) failed`,t);return}}async put(e,t,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`});o.set(xr,`${Date.now()+r*1e3}`);let s=new Response(t,{headers:o}),a=await this.#r(),u=this.#o(e);await a.put(u,s)}async delete(e){try{await(await this.#r()).delete(this.#o(e))}catch(t){this.logDebug(`delete(${e}) fallback needed`,t),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate",[xr]:`${Date.now()}`}),r=new Response("",{headers:t}),o=await this.#r(),s=this.#o(e);await o.put(s,r)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`StreamingZoneCache(${this.#t}):`,...e):"log"in this.#e&&this.#e.log.debug(`StreamingZoneCache(${this.#t}):`,...e)}};var Ps="zuplo-request-id",mt="zp-rid",vr="zp-body-removed",ot="cf-ray",Is="x-real-ip",Cr="cf-ipcity",Sr="cf-ipcontinent",Or="cf-ipcountry",Ar="cf-iplongitude",kr="cf-iplatitude",Es="cf-region",xs="cf-region-code",Ts="cf-metro-code",vs="cf-postal-code",Cs="cf-timezone",yn="zp-ipcity",bn="zp-ipcontinent",wn="zp-ipcountry",Rn="zp-iplongitude",Pn="zp-iplatitude",Ss="true-client-ip",Mt="zp-asn",Lr="zp-asorg",_r="zp-colo",qt="zp-postalcode",Ut="zp-metrocode",Nr="zp-region",Ht="zp-regioncode",$t="zp-timezone",Os="zp-http-protocol",Dr="x-akamai-edgescape",As=[Cr,Sr,Or,Ar,kr,Mt,Lr,_r,qt,Ut,Nr,Ht,$t,Dr],ks=["zp-","cf-"],Ls=[mt,ot,vr];var Zt=Symbol("zuplo_meters"),Ft=Symbol("zuplo_dynamic_meters"),In="system-logger";var oe=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)}};import{trace as cl}from"@opentelemetry/api";import{SpanStatusCode as wc,trace as Rc}from"@opentelemetry/api";import{SpanStatusCode as vn,trace as Cn}from"@opentelemetry/api";var _s=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function Ns(n){_s=n}i(Ns,"setTelemetryInitFunction");var Ds=i(n=>_s(n),"proxyHandler");var Ve=class{static{i(this,"RuntimePlugin")}},fe=class extends Ve{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},En=class extends fe{static{i(this,"MeteringPlugin")}},jt=class extends Ve{static{i(this,"TelemetryPlugin")}};var zt=class n{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=i(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"}})},"problemResponseFormat");static setProblemResponseFormat(e){e&&(f("runtime.problem-response-formatter"),n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(s){throw new k("Error in custom 'problemResponseFormat'",{cause:s})}})}},it=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,r){return await zt.problemResponseFormat(e,t,r)}};function xn(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&xn(t)}return Object.freeze(n)}i(xn,"deepFreeze");var ee=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 xn(this.#e)}get params(){return xn(this.#t)}user};var $r={},Ze=[],Mr=[],qr=[],Ur=[],Hr=[];var Tn={addPlugin(n){Ze.push(n)},addRequestHook(n){Mr.push(n)},addResponseSendingHook(n){qr.push(n)},addResponseSendingFinalHook(n){Ur.push(n)},addPreRoutingHook(n){Hr.push(n)}},qs=i(async(n,e)=>{if(Mr.length===0)return n;let t=Cn.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let s of Mr){let a=await t.startActiveSpan(s.name,async u=>{let c=await s(o,e);if(c instanceof ee||c instanceof Response)return u.end(),c;{let l=new g(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw u.end(),u.recordException(l),u.setStatus({code:vn.ERROR}),l}});if(a instanceof ee)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),Us=i(async(n,e,t)=>{if(qr.length===0)return n;let r=Cn.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let s=n;for(let a of qr)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 g(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof s}.`);throw u.recordException(l),u.setStatus({code:vn.ERROR}),u.end(),l}});return s}finally{o.end()}})},"invokeOnResponseSendingExtensions"),Hs=i(async(n,e,t)=>{if(Ur.length===0)return;let r=Cn.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let s of Ur)await r.startActiveSpan(s.name,async a=>{try{await s(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:vn.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),$s=i(async n=>{if(Hr.length===0)return n;let e=Cn.getTracer("extension");return e.startActiveSpan("hook:preRouting",async t=>{try{let r=n;for(let o of Hr)r=await e.startActiveSpan(o.name,async a=>{try{let u=await o(r);if(u instanceof Request)return u;{let c=new k(`Invalid state - the PreRouting hook must return a Request. Received ${typeof u}.`);throw a.recordException(c),a.setStatus({code:vn.ERROR}),c}}finally{a.end()}});return r}finally{t.end()}})},"invokePreRoutingHooks"),Ms=!1;async function Zs(n){if(!Ms){n&&(f("runtime.extensions"),await n(Tn)),$r.value=Tn;for(let e of Ze)if(e instanceof jt){let{requestHandlerProxy:t}=e.instrument({accountName:y.instance.build.ACCOUNT_NAME,projectName:y.instance.build.PROJECT_NAME,buildId:y.instance.build.BUILD_ID,zuploVersion:y.instance.build.ZUPLO_VERSION,compatibilityDate:y.instance.build.COMPATIBILITY_DATE,instanceId:y.instance.instanceId,environmentType:y.instance.loggingEnvironmentType,environmentStage:y.instance.loggingEnvironmentStage,deploymentName:y.instance.deploymentName});Ns(t)}await Promise.all(Ze.map(async e=>{e instanceof fe&&await e.initialize(Tn)})),zt.setProblemResponseFormat(Tn.problemResponseFormat),Ms=!0}}i(Zs,"initializeRuntime");var Zr={Json:"application/json",Form:"application/x-www-form-urlencoded"};function Fr(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(Zr.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(Zr.Json)||!e?JSON.stringify(n):n}i(Fr,"serialize");function gt(n){return ge.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(ge.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}i(gt,"isSystemRoute");var he=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=i((e,t)=>async(r,o)=>Rc.getTracer("pipeline").startActiveSpan(`handler:${o.route.handler.export}`,async a=>{try{return await e(r,o)}catch(u){let c=t.errorHandler(r,o,"Error executing request handler.",u);return a.setStatus({code:wc.ERROR}),c}finally{a.end()}}),"#errorWrappedHandler");#t=i(({processors:e,gateway:t,handler:r})=>async(o,s)=>{let a=Re.getContextExtensions(s),u=[...e],c=i(async b=>{let E=u.pop();if(!E){let O=await this.#e(async Z=>{let M=await r(Z,s);return Pc(M)},t)(b,s);try{await a.onHandlerResponse(O,b,s)}catch(Z){return t.errorHandler(o,s,"Error invoking 'context.onHandlerResponse' hook",Z)}return O}return E(o,s,t,c)},"nextPipe"),d=await c(o),p=new URL(o.url);if(gt(p)&&y.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return d;let m=new Bt(o,d);s.dispatchEvent(m);let h=a.latestRequest,I;try{I=await m.mutableResponse}catch(b){return t.errorHandler(o,s,"Error retrieving mutableResponse",b)}try{I=await a.onResponseSending(I,h,s)}catch(b){return t.errorHandler(o,s,"Error invoking 'context.onResponseSending' hook",b)}try{I=await Us(I,h,s)}catch(b){return t.errorHandler(o,s,"Error invoking 'context.onResponseSending' hook",b)}s.dispatchEvent(new Gt(o,I));try{await a.onResponseSendingFinal(d,h,s)}catch(b){throw s.log.error("Error invoking 'runtime.onResponseSending' hook",b),b}try{await Hs(d,h,s)}catch(b){throw s.log.error("Error invoking 'runtime.onResponseSending' hook",b),b}return I},"#toZuploPipeline")};function Pc(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(Fr(n),{headers:{"content-type":"application/json"}})}i(Pc,"resultToResponse");var qe=class extends Ve{static{i(this,"MetricsPlugin")}};var J=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 K=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=i(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)}))},"enqueue");waitUntilFlushed=i(async()=>{if(this.#e)return this.#e},"waitUntilFlushed")};var Sn=class{static{i(this,"ZuploMetricsTransport")}#e;#t;constructor(e){this.#e=e,this.#t=new K("zuplo-metrics-transport",10,this.dispatchFunction,J.getLogger(e))}pushMetrics(e,t){this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let{remoteLogURL:t,deploymentName:r}=y.instance,{ACCOUNT_NAME:o,PROJECT_NAME:s}=y.instance.build,a=e.map(p=>{let m=Object.assign({},p);return delete m.requestContentLength,delete m.responseContentLength,m}),u=bs(),c={metadata:{timestamp:new Date,accountName:o,projectName:s,deploymentName:r},metrics:a,features:u},l=new Headers({"content-type":"application/json"});De(l);let d=await $.fetch(`${t}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(c),headers:l});if(!d.ok){let p=await d.text();J.getLogger(this.#e).error(`Metrics POST responded ${d.status}: ${d.statusText}`,p),ws(u)}}catch(t){J.getLogger(this.#e).error("Failed to send Zuplo metrics.",t)}},"dispatchFunction")};var pe=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.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;policies;systemRouteName;raw(){return{}}};var Pe=i(async(n,e,t,r)=>{let o=new Date,s=Date.now(),a=await r(n),u=n.headers.get(ot)??void 0,c=n.headers.get(Ss)??void 0,l=e.incomingRequestProperties,d;e.route instanceof pe&&(d=e.route.systemRouteName);let p=Re.getContextExtensions(e).latestRequest,m={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,contextId:e.contextId,parentContextId:e.parentContext?.contextId,requestId:e.requestId,parentRequestId:e.parentContext?.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:y.instance.instanceId,userSub:p.user?.sub,clientIp:c},h=[];return!y.instance.isLocalDevelopment&&y.instance.remoteLogURL&&y.instance.remoteLogToken&&y.instance.loggingId&&h.push(new Sn(e)),Ze.forEach(I=>{if(I instanceof qe){let b=I.getTransport();h.push(b)}}),h.forEach(I=>{I.pushMetrics(m,e)}),a},"metricsProcessor");var jr=i((n,e)=>{let t=i(async(s,a)=>{let u=new URL(s.url),c=y.instance.build,l={buildId:c.BUILD_ID,zuploVersion:c.ZUPLO_VERSION,compatibilityDate:c.COMPATIBILITY_DATE,apiVersion:c.API_VERSION,gitSha:c.GIT_SHA,timestamp:c.TIMESTAMP,isProduction:c.ENVIRONMENT_TYPE==="PRODUCTION"};if(u.searchParams.get("system_log")==="true"&&J.getLogger(a).error("Test System Log",l),u.searchParams.get("error")==="true")throw new Error("this is an unhandled error");return new Response(JSON.stringify(l,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new he({processors:[Pe],handler:t,gateway:e}),o=new pe({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var On=(R=>(R[R.CONTINUE=100]="CONTINUE",R[R.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",R[R.PROCESSING=102]="PROCESSING",R[R.EARLY_HINTS=103]="EARLY_HINTS",R[R.OK=200]="OK",R[R.CREATED=201]="CREATED",R[R.ACCEPTED=202]="ACCEPTED",R[R.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",R[R.NO_CONTENT=204]="NO_CONTENT",R[R.RESET_CONTENT=205]="RESET_CONTENT",R[R.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",R[R.MULTI_STATUS=207]="MULTI_STATUS",R[R.ALREADY_REPORTED=208]="ALREADY_REPORTED",R[R.IM_USED=226]="IM_USED",R[R.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",R[R.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",R[R.FOUND=302]="FOUND",R[R.SEE_OTHER=303]="SEE_OTHER",R[R.NOT_MODIFIED=304]="NOT_MODIFIED",R[R.USE_PROXY=305]="USE_PROXY",R[R.SWITCH_PROXY=306]="SWITCH_PROXY",R[R.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",R[R.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",R[R.BAD_REQUEST=400]="BAD_REQUEST",R[R.UNAUTHORIZED=401]="UNAUTHORIZED",R[R.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",R[R.FORBIDDEN=403]="FORBIDDEN",R[R.NOT_FOUND=404]="NOT_FOUND",R[R.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",R[R.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",R[R.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",R[R.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",R[R.CONFLICT=409]="CONFLICT",R[R.GONE=410]="GONE",R[R.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",R[R.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",R[R.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",R[R.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",R[R.URI_TOO_LONG=414]="URI_TOO_LONG",R[R.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",R[R.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",R[R.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",R[R.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",R[R.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",R[R.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",R[R.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",R[R.LOCKED=423]="LOCKED",R[R.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",R[R.TOO_EARLY=425]="TOO_EARLY",R[R.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",R[R.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",R[R.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",R[R.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",R[R.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",R[R.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",R[R.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",R[R.BAD_GATEWAY=502]="BAD_GATEWAY",R[R.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",R[R.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",R[R.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",R[R.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",R[R.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",R[R.LOOP_DETECTED=508]="LOOP_DETECTED",R[R.NOT_EXTENDED=510]="NOT_EXTENDED",R[R.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",R))(On||{}),Fs={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 Ic={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"},zr=Ic;function Ec(n){return`${new URL(n.url).pathname}`}i(Ec,"instance");function xc(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:y.instance.build.BUILD_ID},r=n.headers.get(ot);return r&&(t.rayId=r),t}i(xc,"trace");var Tc=i((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:Ec(e),trace:xc(e,t),...r},additionalHeaders:o,statusText:zr[n.status]}),"merge"),Br=class{static{i(this,"HttpProblemsBase")}static format=i((e,t,r)=>"problem"in e?it.format(e,t,r):it.format({problem:e},t,r),"format");static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:Fs[e],...t}}},T=class extends Br{static{i(this,"HttpProblems")}static#e(e,t,r,o,s){let a=Tc(this.getProblemFromStatus(e),t,r,o,s);return it.format(a,t,r)}static continue=i((e,t,r,o)=>this.#e(200,e,t,r,o),"continue");static switchingProtocols=i((e,t,r,o)=>this.#e(101,e,t,r,o),"switchingProtocols");static processing=i((e,t,r,o)=>this.#e(102,e,t,r,o),"processing");static earlyHints=i((e,t,r,o)=>this.#e(103,e,t,r,o),"earlyHints");static ok=i((e,t,r,o)=>this.#e(200,e,t,r,o),"ok");static created=i((e,t,r,o)=>this.#e(201,e,t,r,o),"created");static accepted=i((e,t,r,o)=>this.#e(202,e,t,r,o),"accepted");static nonAuthoritativeInformation=i((e,t,r,o)=>this.#e(203,e,t,r,o),"nonAuthoritativeInformation");static noContent=i((e,t,r,o)=>this.#e(204,e,t,r,o),"noContent");static resetContent=i((e,t,r,o)=>this.#e(205,e,t,r,o),"resetContent");static partialContent=i((e,t,r,o)=>this.#e(206,e,t,r,o),"partialContent");static multiStatus=i((e,t,r,o)=>this.#e(207,e,t,r,o),"multiStatus");static alreadyReported=i((e,t,r,o)=>this.#e(208,e,t,r,o),"alreadyReported");static imUsed=i((e,t,r,o)=>this.#e(226,e,t,r,o),"imUsed");static multipleChoices=i((e,t,r,o)=>this.#e(300,e,t,r,o),"multipleChoices");static movedPermanently=i((e,t,r,o)=>this.#e(301,e,t,r,o),"movedPermanently");static found=i((e,t,r,o)=>this.#e(302,e,t,r,o),"found");static seeOther=i((e,t,r,o)=>this.#e(303,e,t,r,o),"seeOther");static notModified=i((e,t,r,o)=>this.#e(304,e,t,r,o),"notModified");static useProxy=i((e,t,r,o)=>this.#e(305,e,t,r,o),"useProxy");static switchProxy=i((e,t,r,o)=>this.#e(306,e,t,r,o),"switchProxy");static temporaryRedirect=i((e,t,r,o)=>this.#e(307,e,t,r,o),"temporaryRedirect");static permanentRedirect=i((e,t,r,o)=>this.#e(308,e,t,r,o),"permanentRedirect");static badRequest=i((e,t,r,o)=>this.#e(400,e,t,r,o),"badRequest");static unauthorized=i((e,t,r,o)=>this.#e(401,e,t,r,o),"unauthorized");static paymentRequired=i((e,t,r,o)=>this.#e(402,e,t,r,o),"paymentRequired");static forbidden=i((e,t,r,o)=>this.#e(403,e,t,r,o),"forbidden");static notFound=i((e,t,r,o)=>this.#e(404,e,t,r,o),"notFound");static methodNotAllowed=i((e,t,r,o)=>this.#e(405,e,t,r,o),"methodNotAllowed");static notAcceptable=i((e,t,r,o)=>this.#e(406,e,t,r,o),"notAcceptable");static proxyAuthenticationRequired=i((e,t,r,o)=>this.#e(407,e,t,r,o),"proxyAuthenticationRequired");static requestTimeout=i((e,t,r,o)=>this.#e(408,e,t,r,o),"requestTimeout");static conflict=i((e,t,r,o)=>this.#e(409,e,t,r,o),"conflict");static gone=i((e,t,r,o)=>this.#e(410,e,t,r,o),"gone");static lengthRequired=i((e,t,r,o)=>this.#e(411,e,t,r,o),"lengthRequired");static preconditionFailed=i((e,t,r,o)=>this.#e(412,e,t,r,o),"preconditionFailed");static contentTooLarge=i((e,t,r,o)=>this.#e(413,e,t,r,o),"contentTooLarge");static uriTooLong=i((e,t,r,o)=>this.#e(414,e,t,r,o),"uriTooLong");static unsupportedMediaType=i((e,t,r,o)=>this.#e(415,e,t,r,o),"unsupportedMediaType");static rangeNotSatisfiable=i((e,t,r,o)=>this.#e(416,e,t,r,o),"rangeNotSatisfiable");static expectationFailed=i((e,t,r,o)=>this.#e(417,e,t,r,o),"expectationFailed");static imATeapot=i((e,t,r,o)=>this.#e(418,e,t,r,o),"imATeapot");static misdirectedRequest=i((e,t,r,o)=>this.#e(421,e,t,r,o),"misdirectedRequest");static unprocessableContent=i((e,t,r,o)=>this.#e(422,e,t,r,o),"unprocessableContent");static locked=i((e,t,r,o)=>this.#e(423,e,t,r,o),"locked");static failedDependency=i((e,t,r,o)=>this.#e(424,e,t,r,o),"failedDependency");static tooEarly=i((e,t,r,o)=>this.#e(425,e,t,r,o),"tooEarly");static upgradeRequired=i((e,t,r,o)=>this.#e(426,e,t,r,o),"upgradeRequired");static preconditionRequired=i((e,t,r,o)=>this.#e(428,e,t,r,o),"preconditionRequired");static tooManyRequests=i((e,t,r,o)=>this.#e(429,e,t,r,o),"tooManyRequests");static requestHeaderFieldsTooLarge=i((e,t,r,o)=>this.#e(431,e,t,r,o),"requestHeaderFieldsTooLarge");static unavailableForLegalReasons=i((e,t,r,o)=>this.#e(451,e,t,r,o),"unavailableForLegalReasons");static internalServerError=i((e,t,r,o)=>this.#e(500,e,t,r,o),"internalServerError");static notImplemented=i((e,t,r,o)=>this.#e(501,e,t,r,o),"notImplemented");static badGateway=i((e,t,r,o)=>this.#e(502,e,t,r,o),"badGateway");static serviceUnavailable=i((e,t,r,o)=>this.#e(503,e,t,r,o),"serviceUnavailable");static gatewayTimeout=i((e,t,r,o)=>this.#e(504,e,t,r,o),"gatewayTimeout");static httpVersionNotSupported=i((e,t,r,o)=>this.#e(505,e,t,r,o),"httpVersionNotSupported");static variantAlsoNegotiates=i((e,t,r,o)=>this.#e(506,e,t,r,o),"variantAlsoNegotiates");static insufficientStorage=i((e,t,r,o)=>this.#e(507,e,t,r,o),"insufficientStorage");static loopDetected=i((e,t,r,o)=>this.#e(508,e,t,r,o),"loopDetected");static notExtended=i((e,t,r,o)=>this.#e(510,e,t,r,o),"notExtended");static networkAuthenticationRequired=i((e,t,r,o)=>this.#e(511,e,t,r,o),"networkAuthenticationRequired")};var{toString:vc}=Object.prototype,{propertyIsEnumerable:Cc}=Object.prototype;function Gr(n){return vc.call(n)}i(Gr,"toString");function Te(n){return typeof n=="string"}i(Te,"isString");function ft(n){return Te(n)&&n!==""}i(ft,"isNonEmptyString");function js(n){return Gr(n)==="[object RegExp]"}i(js,"isRegexp");function zs(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>Cc.call(n,e))]}i(zs,"getOwnEnumerableKeys");function st(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}i(st,"isObject");function Vr(n){return typeof n=="number"&&!isNaN(n)}i(Vr,"isNumber");function Wr(n){return n===!0||n===!1}i(Wr,"isBoolean");function Bs(n){return typeof n>"u"}i(Bs,"isUndefined");function Gs(n){return Bs(n)||n===null}i(Gs,"isUndefinedOrNull");function Vt(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(Vt,"isErrorLike");var Vs=new Map;function We(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 g("Malformed input string");let e=Vs.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 Vs.set(n,r),r}i(We,"statusCodesStringToNumberArray");function Fe(n,e,t){if(!e.startsWith("."))throw new g(`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 k(`Error applying ${t} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i(Fe,"getValueFromRequestUser");function je(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new g("Received an array that contains non-string values.");return n}if(Te(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new g(`Expected type of string, received type '${typeof n}'`)}i(je,"parseValueToStringArray");function Ws(n){if(n==null)return[];if(!Array.isArray(n))throw new g(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!st(t))throw new g(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!ft(t.name))throw new g("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!Vr(t.maxAge))throw new g(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!Wr(t.allowCredentials))throw new g("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=Jr(t,"allowedHeaders"),o=Jr(t,"allowedMethods"),s=Jr(t,"exposeHeaders"),a;try{a=je(t.allowedOrigins)}catch(c){throw new g(`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(Ws,"parseCorsPolicies");function Jr(n,e){let t;if(n[e]!==void 0)try{t=je(n[e])}catch(r){throw new g(`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(Jr,"parseOptionalProperty");var An=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"),kn=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 Kr=i((n,e)=>{let t=e.routeData.corsPolicies,r=i(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return T.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let m=n.lookup(c,l);if(!m)return T.notFound(a,u);let h=m.routeConfiguration,I=Sc(l,d,p,h,t);return I.isValid?new Response(void 0,{status:200,statusText:"OK",headers:I.headers}):(I.error&&u.log.warn(I.error),T.notFound(a,u))},"optionsHandler"),o=new he({processors:[Pe],handler:r,gateway:e}),s=new pe({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(s,o.execute)},"registerCorsRoute"),Sc=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 g(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=An(a.allowedOrigins,t);return u?{isValid:!0,headers:kn(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var Js=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 he({processors:[Pe],handler:t,gateway:e}),o=new pe({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 Je=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.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,this.raw=e.raw}raw;get summary(){return this.raw()?.summary}get operationId(){return this.raw()?.operationId}get tags(){return this.raw()?.tags}get parameters(){return this.raw()?.parameters}get responses(){return this.raw()?.responses}label;key;path;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;policies};var Oc=new pe({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Ks=i((n,e)=>{let t=i(async(o,s)=>{let a=$r.value?.notFoundHandler;if(a){let u=new URL(o.url);return a(o,s,{get routesMatchedByPathOnly(){return n.lookupByPathOnly(u.pathname).map(l=>l.routeConfiguration).filter(l=>l instanceof Je)}})}return T.notFound(o,s)},"notFoundHandler"),r=new he({processors:[Pe],handler:t,gateway:e});n.addRoute(Oc,r.execute)},"registerNotMatchedHandler");var Ac=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Qs=i(n=>{Ac.forEach(e=>n.delete(e))},"stripCorsHeaders"),Ln=i(async(n,e,t,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await r(n),p=new Headers(d.headers);return Qs(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await r(n);if(!(s instanceof Response))throw new Y(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=kc(o,t.routeData.corsPolicies),u=Lc(n,a),c=new Headers(s.headers);return Qs(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(s.body,{status:s.status,statusText:s.statusText,headers:c,webSocket:s.webSocket})},"corsProcessor"),kc=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 g(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),Lc=i((n,e)=>{let t=An(e.allowedOrigins,n.headers.get("origin"));return t?kn(e,t):{}},"getCorsHeaders");var Qr=i((n,e)=>{let t=i(async()=>new Response(JSON.stringify({buildId:y.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new he({processors:[Ln],handler:t,gateway:e}),o=new pe({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");import{SpanStatusCode as Ys,trace as Xs}from"@opentelemetry/api";var ze={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 _n=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!Te(t))throw new k(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},ae=class extends _n{static{i(this,"InboundPolicy")}},Ke=class extends _n{static{i(this,"OutboundPolicy")}};var eo=class extends ae{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)}},to=class extends Ke{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)}},Yr=new Map;function Wt(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(s=>!Yr.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new g(`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 g(`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 g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof ae)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new eo(u,a.handler.options,a.name);else throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new g(`Invalid state - invalid handler on policy '${s}' on route '${r}' (typeof handler '${typeof c.handler}')`);Yr.set(a.name,c)}),t.map(s=>{let a=Yr.get(s);if(a===void 0)throw new k("Internal error. Policy not found in cache.");return a})}i(Wt,"getInboundPolicyInstances");var Xr=new Map;function Jt(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.outbound??[],r=n.path),t.filter(s=>!Xr.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new g(`Invalid state - no Policy with the name '${s}' on route '${r}' was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export],c;if(typeof u!="function")throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof Ke)c=new u(a.handler.options??{},a.name);else if(typeof u=="function")c=new to(u,a.handler.options??{},a.name);else throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new g(`Invalid state - invalid handler on policy '${s}' on route '${r}'`);Xr.set(a.name,c)}),t.map(s=>{let a=Xr.get(s);if(a===void 0)throw new k("Internal error. Policy not found in cache.");return a})}i(Jt,"getOutboundPolicyInstances");var no=i(n=>async(e,t)=>{let r=Re.getContextExtensions(t),o=Xs.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 ee||p instanceof Response)return d.end(),p instanceof Response||p instanceof ee?p:new ee(p);{let m=new g(`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:Ys.ERROR}),d.recordException(m),m}});if(l instanceof ee)u=l;else if(l instanceof Request)u=new ee(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),ro=i(n=>async(e,t,r)=>{let o=Xs.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(ze.PolicyName,c.policyName),d.setAttribute(ze.PolicyType,c.policyType);let p=await c.handler(u,t,r);if(p instanceof Response)return p;{let m=new g(`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:Ys.ERROR}),d.recordException(m),m}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),Nn=i(async(n,e,t,r)=>{let o=Wt(e.route,t.routeData.policies),s=Jt(e.route,t.routeData.policies);return ta({request:n,context:e,inboundPolicies:o,outboundPolicies:s,gateway:t,next:r})},"policyProcessor");function ea({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>ta({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(ea,"createInternalPolicyProcessor");async function ta({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:s}){let a=no(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await s(u),l=ro(r),d;return y.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,n,e):d=c.ok?l(c,n,e):c,d}catch(u){return o.errorHandler(n,e,"Error executing policies",u)}}i(ta,"executePolicyProcessor");var ia=Vu(oa(),1);function sa(n,e){try{let t=/v\d+(-\d+)?/g,o=(0,ia.parse)(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}i(sa,"devPortalBaseURL");var aa="/__zuplo/dev-portal",jc="dev-portal-id",zc="dev-portal-host",Bc="zp-account",Gc="zp-project",Vc="dev-portal-build",Wc=`
35
+ `)+" "+t[1]:t[0]+e+" "+n.join(", ")+" "+t[1]}i(gc,"reduceToSingleString");var ps=i((n,...e)=>ss(Ge,n,e),"format");var br=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=is(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=ps(t,...e);let s=`${this.color(this.ns)} ${t} ${this.color(`+${o}ms`)}`;console.log(s),this.last=Date.now()}},wr=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function fc(n){return!n||n.length===0?[]:(n=n.replace(/\s/g,"").replace(/\*/g,".+"),n.split(",").map(e=>new RegExp(`^${e}$`)))}i(fc,"extract");var mn;function be(n){let e=globalThis.DEBUG;mn||(mn=new wr(fc(e)));let t=new br(mn,n);return mn.debuggers.set(n,t),Object.assign(t.log.bind(t),{self:t})}i(be,"debug");var Y=class extends Error{static{i(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},k=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"}},g=class extends k{static{i(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}};var rt=be("zuplo:runtime:external-service");function hc(){let n,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=y.instance.runtime;if(e&&e!=="undefined")try{let t=atob(e);n=JSON.parse(t)}catch{}return n}i(hc,"getServiceAuth");async function ms(n,e){let t=hc();if(t)if(rt(`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(y.instance.useLegacyServiceRouting)u=`https://${o}.zuptunnel.com`;else{rt("Using sha256 service routing");let d=y.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE){let p=await yc(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE),m=gs(d.ENVIRONMENT_TYPE),h=await Rr(`${d.ACCOUNT_NAME}-${d.PROJECT_NAME}-${m}`);h==="40d7ad502f5d743997999594c177184a00161a77865423511f3a1ea21eb5a5e"||h==="d05bffe8fa91a300187d2cf43e8aa4a56bd809c442ae10d1ee49af7d29a5a11"?u=`https://${p}.zuptunnel.com`:u=`https://${p}.t.zuplo.app`}else throw rt("Cannot use sha256 service routing, missing build variables"),new k("Failed to generate fully qualified tunnel url.")}let c=new URL(`${u}${r.pathname}${r.search}`);rt(`Calling external service: ${c.toString()}`);let l=await gn(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 k("Could not connect to secure tunnel.");return l}else throw rt("Cannot call external service with Request object"),new k("Currently, we only support fetch(<some_string>, ...).");else throw rt("There is no external service auth configured for this zup."),new k("There are no external services configured for this zup.")}i(ms,"externalServiceHandler");async function yc(n,e,t,r){let o=n.toLowerCase(),s=e.toLowerCase(),a=t.toLowerCase(),u=gs(r);rt(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await Rr(`${s}-${o}`),l=await Rr(`${s}-${a}-${u}`);return`${c}.${l}`}i(yc,"hashServiceName");async function Rr(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(Rr,"hashSegment");function gs(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(gs,"sanitizeEnvironmentType");var fs=new Map;fs.set("service:",ms);var gn=globalThis.fetch;function Pr(n,e){let t=bc(e);if(typeof n=="string"){let r=new URL(n),o=fs.get(r.protocol);return o?o(n,t):gn(n,t)}else return gn(n,t)}i(Pr,"internalFetch");globalThis.fetch=Pr;var bc=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 wc={fetch:Pr},$=wc;Function.prototype.toString=function(){return"[native code]"};var fn=globalThis,hs=fn.caches;if(hs){let n=hs.open;fn.caches.open=function(e){let t=y.instance.deploymentName??y.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete fn.caches.default,Object.freeze(fn.caches)}var hn=new Set,ys=new Set;function f(n){ys.has(n)||(ys.add(n),hn.add(n))}i(f,"trackFeature");function bs(){let n=[...hn];return hn.clear(),n}i(bs,"getUnsentFeatures");function ws(n){for(let e of n)hn.add(e)}i(ws,"restoreFeatures");function De(n,e){n.has("Authorization")||n.set("Authorization",`Bearer ${y.instance.authApiJWT}`),n.set("zp-rid",e??`global-${crypto.randomUUID()}`),n.set("zp-dn",y.instance.deploymentName??"unknown"),n.set("User-Agent",y.instance.systemUserAgent),n.set("zp-compat-date",y.instance.build.COMPATIBILITY_DATE??"none")}i(De,"setZuploHeaders");async function Rc(n,e={}){f("utility.zuplo-api-services");let{method:t="GET",data:r}=e,o=new URL(n,y.instance.zuploEdgeApiUrl),s=new Headers(e.headers);De(s),s.set("Content-Type","application/json");let a={method:t,headers:s};r&&(a.body=JSON.stringify(r));let u=await $.fetch(o,a),c;try{if(!u.ok)throw c=await u.clone().json(),new Error(`Error ${u.status}: ${JSON.stringify(c)||"Request failed"}`);if(u.status===204)return;c=await u.clone().json()}catch(l){throw new Error(l.message)}return c}i(Rc,"apiServices");var Rs=new Map,Ir=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)})}},Me=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=Rs.get(e);r||(r=new Ir(t),Rs.set(e,r)),this.#e=r}name;#e;get(e){return this.#e.get(e)}put(e,t,r){return this.#e.put(e,t,r)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var Er="__zuplo-expiry-header",Dt=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(Er);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(Er,`${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(Er,`${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 re=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Me(r),this.#n=new Dt(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)}async delete(e){this.#t.delete(e),await this.#n.delete(e)}};var xr="__zuplo-expiry-header",Tr=class{static{i(this,"StreamingZoneCache")}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://streaming-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(xr);if(!s){await t.delete(r).catch(u=>{this.logDebug(`StreamingZoneCache: error deleting missing expiry entry ${e}`,u)});return}let a=parseInt(s,10);if(Date.now()>=a){await t.delete(r).catch(u=>{this.logDebug(`StreamingZoneCache: error deleting expired entry ${e}`,u)});return}return o.body??void 0}catch(t){this.logDebug(`get(${e}) failed`,t);return}}async put(e,t,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`});o.set(xr,`${Date.now()+r*1e3}`);let s=new Response(t,{headers:o}),a=await this.#r(),u=this.#o(e);await a.put(u,s)}async delete(e){try{await(await this.#r()).delete(this.#o(e))}catch(t){this.logDebug(`delete(${e}) fallback needed`,t),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate",[xr]:`${Date.now()}`}),r=new Response("",{headers:t}),o=await this.#r(),s=this.#o(e);await o.put(s,r)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`StreamingZoneCache(${this.#t}):`,...e):"log"in this.#e&&this.#e.log.debug(`StreamingZoneCache(${this.#t}):`,...e)}};var Ps="zuplo-request-id",mt="zp-rid",vr="zp-body-removed",ot="cf-ray",Is="x-real-ip",Cr="cf-ipcity",Sr="cf-ipcontinent",Or="cf-ipcountry",Ar="cf-iplongitude",kr="cf-iplatitude",Es="cf-region",xs="cf-region-code",Ts="cf-metro-code",vs="cf-postal-code",Cs="cf-timezone",yn="zp-ipcity",bn="zp-ipcontinent",wn="zp-ipcountry",Rn="zp-iplongitude",Pn="zp-iplatitude",Ss="true-client-ip",Os="x-forwarded-for",Mt="zp-asn",Lr="zp-asorg",_r="zp-colo",qt="zp-postalcode",Ut="zp-metrocode",Nr="zp-region",Ht="zp-regioncode",$t="zp-timezone",As="zp-http-protocol",Dr="x-akamai-edgescape",ks=[Cr,Sr,Or,Ar,kr,Mt,Lr,_r,qt,Ut,Nr,Ht,$t,Dr],Ls=["zp-","cf-"],_s=[mt,ot,vr];var Zt=Symbol("zuplo_meters"),Ft=Symbol("zuplo_dynamic_meters"),In="system-logger";var oe=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)}};import{trace as dl}from"@opentelemetry/api";import{SpanStatusCode as Pc,trace as Ic}from"@opentelemetry/api";import{SpanStatusCode as vn,trace as Cn}from"@opentelemetry/api";var Ns=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function Ds(n){Ns=n}i(Ds,"setTelemetryInitFunction");var Ms=i(n=>Ns(n),"proxyHandler");var Ve=class{static{i(this,"RuntimePlugin")}},fe=class extends Ve{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},En=class extends fe{static{i(this,"MeteringPlugin")}},jt=class extends Ve{static{i(this,"TelemetryPlugin")}};var zt=class n{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=i(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"}})},"problemResponseFormat");static setProblemResponseFormat(e){e&&(f("runtime.problem-response-formatter"),n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(s){throw new k("Error in custom 'problemResponseFormat'",{cause:s})}})}},it=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,r){return await zt.problemResponseFormat(e,t,r)}};function xn(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&xn(t)}return Object.freeze(n)}i(xn,"deepFreeze");var ee=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 xn(this.#e)}get params(){return xn(this.#t)}user};var $r={},Ze=[],Mr=[],qr=[],Ur=[],Hr=[];var Tn={addPlugin(n){Ze.push(n)},addRequestHook(n){Mr.push(n)},addResponseSendingHook(n){qr.push(n)},addResponseSendingFinalHook(n){Ur.push(n)},addPreRoutingHook(n){Hr.push(n)}},Us=i(async(n,e)=>{if(Mr.length===0)return n;let t=Cn.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let s of Mr){let a=await t.startActiveSpan(s.name,async u=>{let c=await s(o,e);if(c instanceof ee||c instanceof Response)return u.end(),c;{let l=new g(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw u.end(),u.recordException(l),u.setStatus({code:vn.ERROR}),l}});if(a instanceof ee)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),Hs=i(async(n,e,t)=>{if(qr.length===0)return n;let r=Cn.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let s=n;for(let a of qr)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 g(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof s}.`);throw u.recordException(l),u.setStatus({code:vn.ERROR}),u.end(),l}});return s}finally{o.end()}})},"invokeOnResponseSendingExtensions"),$s=i(async(n,e,t)=>{if(Ur.length===0)return;let r=Cn.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let s of Ur)await r.startActiveSpan(s.name,async a=>{try{await s(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:vn.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),Zs=i(async n=>{if(Hr.length===0)return n;let e=Cn.getTracer("extension");return e.startActiveSpan("hook:preRouting",async t=>{try{let r=n;for(let o of Hr)r=await e.startActiveSpan(o.name,async a=>{try{let u=await o(r);if(u instanceof Request)return u;{let c=new k(`Invalid state - the PreRouting hook must return a Request. Received ${typeof u}.`);throw a.recordException(c),a.setStatus({code:vn.ERROR}),c}}finally{a.end()}});return r}finally{t.end()}})},"invokePreRoutingHooks"),qs=!1;async function Fs(n){if(!qs){n&&(f("runtime.extensions"),await n(Tn)),$r.value=Tn;for(let e of Ze)if(e instanceof jt){let{requestHandlerProxy:t}=e.instrument({accountName:y.instance.build.ACCOUNT_NAME,projectName:y.instance.build.PROJECT_NAME,buildId:y.instance.build.BUILD_ID,zuploVersion:y.instance.build.ZUPLO_VERSION,compatibilityDate:y.instance.build.COMPATIBILITY_DATE,instanceId:y.instance.instanceId,environmentType:y.instance.loggingEnvironmentType,environmentStage:y.instance.loggingEnvironmentStage,deploymentName:y.instance.deploymentName});Ds(t)}await Promise.all(Ze.map(async e=>{e instanceof fe&&await e.initialize(Tn)})),zt.setProblemResponseFormat(Tn.problemResponseFormat),qs=!0}}i(Fs,"initializeRuntime");var Zr={Json:"application/json",Form:"application/x-www-form-urlencoded"};function Fr(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(Zr.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(Zr.Json)||!e?JSON.stringify(n):n}i(Fr,"serialize");function gt(n){return ge.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(ge.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}i(gt,"isSystemRoute");var he=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=i((e,t)=>async(r,o)=>Ic.getTracer("pipeline").startActiveSpan(`handler:${o.route.handler.export}`,async a=>{try{return await e(r,o)}catch(u){let c=t.errorHandler(r,o,"Error executing request handler.",u);return a.setStatus({code:Pc.ERROR}),c}finally{a.end()}}),"#errorWrappedHandler");#t=i(({processors:e,gateway:t,handler:r})=>async(o,s)=>{let a=Re.getContextExtensions(s),u=[...e],c=i(async b=>{let E=u.pop();if(!E){let O=await this.#e(async Z=>{let M=await r(Z,s);return Ec(M)},t)(b,s);try{await a.onHandlerResponse(O,b,s)}catch(Z){return t.errorHandler(o,s,"Error invoking 'context.onHandlerResponse' hook",Z)}return O}return E(o,s,t,c)},"nextPipe"),d=await c(o),p=new URL(o.url);if(gt(p)&&y.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return d;let m=new Bt(o,d);s.dispatchEvent(m);let h=a.latestRequest,I;try{I=await m.mutableResponse}catch(b){return t.errorHandler(o,s,"Error retrieving mutableResponse",b)}try{I=await a.onResponseSending(I,h,s)}catch(b){return t.errorHandler(o,s,"Error invoking 'context.onResponseSending' hook",b)}try{I=await Hs(I,h,s)}catch(b){return t.errorHandler(o,s,"Error invoking 'context.onResponseSending' hook",b)}s.dispatchEvent(new Gt(o,I));try{await a.onResponseSendingFinal(d,h,s)}catch(b){throw s.log.error("Error invoking 'runtime.onResponseSending' hook",b),b}try{await $s(d,h,s)}catch(b){throw s.log.error("Error invoking 'runtime.onResponseSending' hook",b),b}return I},"#toZuploPipeline")};function Ec(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(Fr(n),{headers:{"content-type":"application/json"}})}i(Ec,"resultToResponse");var qe=class extends Ve{static{i(this,"MetricsPlugin")}};var J=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 K=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=i(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)}))},"enqueue");waitUntilFlushed=i(async()=>{if(this.#e)return this.#e},"waitUntilFlushed")};var Sn=class{static{i(this,"ZuploMetricsTransport")}#e;#t;constructor(e){this.#e=e,this.#t=new K("zuplo-metrics-transport",10,this.dispatchFunction,J.getLogger(e))}pushMetrics(e,t){this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let{remoteLogURL:t,deploymentName:r}=y.instance,{ACCOUNT_NAME:o,PROJECT_NAME:s}=y.instance.build,a=e.map(p=>{let m=Object.assign({},p);return delete m.requestContentLength,delete m.responseContentLength,m}),u=bs(),c={metadata:{timestamp:new Date,accountName:o,projectName:s,deploymentName:r},metrics:a,features:u},l=new Headers({"content-type":"application/json"});De(l);let d=await $.fetch(`${t}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(c),headers:l});if(!d.ok){let p=await d.text();J.getLogger(this.#e).error(`Metrics POST responded ${d.status}: ${d.statusText}`,p),ws(u)}}catch(t){J.getLogger(this.#e).error("Failed to send Zuplo metrics.",t)}},"dispatchFunction")};var pe=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.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;policies;systemRouteName;raw(){return{}}};function js(n){let e=n.headers,t=e.get(Ss);if(t)return t;let r=e.get(Os);if(r)return r.split(",")[0].trim()}i(js,"getClientIp");var Pe=i(async(n,e,t,r)=>{let o=new Date,s=Date.now(),a=await r(n),u=n.headers.get(ot)??void 0,c=js(n),l=e.incomingRequestProperties,d;e.route instanceof pe&&(d=e.route.systemRouteName);let p=Re.getContextExtensions(e).latestRequest,m={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,contextId:e.contextId,parentContextId:e.parentContext?.contextId,requestId:e.requestId,parentRequestId:e.parentContext?.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:y.instance.instanceId,userSub:p.user?.sub,clientIp:c},h=[];return!y.instance.isLocalDevelopment&&y.instance.remoteLogURL&&y.instance.remoteLogToken&&y.instance.loggingId&&h.push(new Sn(e)),Ze.forEach(I=>{if(I instanceof qe){let b=I.getTransport();h.push(b)}}),h.forEach(I=>{I.pushMetrics(m,e)}),a},"metricsProcessor");var jr=i((n,e)=>{let t=i(async(s,a)=>{let u=new URL(s.url),c=y.instance.build,l={buildId:c.BUILD_ID,zuploVersion:c.ZUPLO_VERSION,compatibilityDate:c.COMPATIBILITY_DATE,apiVersion:c.API_VERSION,gitSha:c.GIT_SHA,timestamp:c.TIMESTAMP,isProduction:c.ENVIRONMENT_TYPE==="PRODUCTION"};if(u.searchParams.get("system_log")==="true"&&J.getLogger(a).error("Test System Log",l),u.searchParams.get("error")==="true")throw new Error("this is an unhandled error");return new Response(JSON.stringify(l,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new he({processors:[Pe],handler:t,gateway:e}),o=new pe({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var On=(R=>(R[R.CONTINUE=100]="CONTINUE",R[R.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",R[R.PROCESSING=102]="PROCESSING",R[R.EARLY_HINTS=103]="EARLY_HINTS",R[R.OK=200]="OK",R[R.CREATED=201]="CREATED",R[R.ACCEPTED=202]="ACCEPTED",R[R.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",R[R.NO_CONTENT=204]="NO_CONTENT",R[R.RESET_CONTENT=205]="RESET_CONTENT",R[R.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",R[R.MULTI_STATUS=207]="MULTI_STATUS",R[R.ALREADY_REPORTED=208]="ALREADY_REPORTED",R[R.IM_USED=226]="IM_USED",R[R.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",R[R.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",R[R.FOUND=302]="FOUND",R[R.SEE_OTHER=303]="SEE_OTHER",R[R.NOT_MODIFIED=304]="NOT_MODIFIED",R[R.USE_PROXY=305]="USE_PROXY",R[R.SWITCH_PROXY=306]="SWITCH_PROXY",R[R.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",R[R.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",R[R.BAD_REQUEST=400]="BAD_REQUEST",R[R.UNAUTHORIZED=401]="UNAUTHORIZED",R[R.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",R[R.FORBIDDEN=403]="FORBIDDEN",R[R.NOT_FOUND=404]="NOT_FOUND",R[R.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",R[R.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",R[R.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",R[R.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",R[R.CONFLICT=409]="CONFLICT",R[R.GONE=410]="GONE",R[R.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",R[R.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",R[R.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",R[R.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",R[R.URI_TOO_LONG=414]="URI_TOO_LONG",R[R.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",R[R.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",R[R.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",R[R.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",R[R.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",R[R.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",R[R.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",R[R.LOCKED=423]="LOCKED",R[R.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",R[R.TOO_EARLY=425]="TOO_EARLY",R[R.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",R[R.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",R[R.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",R[R.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",R[R.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",R[R.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",R[R.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",R[R.BAD_GATEWAY=502]="BAD_GATEWAY",R[R.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",R[R.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",R[R.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",R[R.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",R[R.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",R[R.LOOP_DETECTED=508]="LOOP_DETECTED",R[R.NOT_EXTENDED=510]="NOT_EXTENDED",R[R.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",R))(On||{}),zs={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 xc={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"},zr=xc;function Tc(n){return`${new URL(n.url).pathname}`}i(Tc,"instance");function vc(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:y.instance.build.BUILD_ID},r=n.headers.get(ot);return r&&(t.rayId=r),t}i(vc,"trace");var Cc=i((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:Tc(e),trace:vc(e,t),...r},additionalHeaders:o,statusText:zr[n.status]}),"merge"),Br=class{static{i(this,"HttpProblemsBase")}static format=i((e,t,r)=>"problem"in e?it.format(e,t,r):it.format({problem:e},t,r),"format");static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:zs[e],...t}}},T=class extends Br{static{i(this,"HttpProblems")}static#e(e,t,r,o,s){let a=Cc(this.getProblemFromStatus(e),t,r,o,s);return it.format(a,t,r)}static continue=i((e,t,r,o)=>this.#e(200,e,t,r,o),"continue");static switchingProtocols=i((e,t,r,o)=>this.#e(101,e,t,r,o),"switchingProtocols");static processing=i((e,t,r,o)=>this.#e(102,e,t,r,o),"processing");static earlyHints=i((e,t,r,o)=>this.#e(103,e,t,r,o),"earlyHints");static ok=i((e,t,r,o)=>this.#e(200,e,t,r,o),"ok");static created=i((e,t,r,o)=>this.#e(201,e,t,r,o),"created");static accepted=i((e,t,r,o)=>this.#e(202,e,t,r,o),"accepted");static nonAuthoritativeInformation=i((e,t,r,o)=>this.#e(203,e,t,r,o),"nonAuthoritativeInformation");static noContent=i((e,t,r,o)=>this.#e(204,e,t,r,o),"noContent");static resetContent=i((e,t,r,o)=>this.#e(205,e,t,r,o),"resetContent");static partialContent=i((e,t,r,o)=>this.#e(206,e,t,r,o),"partialContent");static multiStatus=i((e,t,r,o)=>this.#e(207,e,t,r,o),"multiStatus");static alreadyReported=i((e,t,r,o)=>this.#e(208,e,t,r,o),"alreadyReported");static imUsed=i((e,t,r,o)=>this.#e(226,e,t,r,o),"imUsed");static multipleChoices=i((e,t,r,o)=>this.#e(300,e,t,r,o),"multipleChoices");static movedPermanently=i((e,t,r,o)=>this.#e(301,e,t,r,o),"movedPermanently");static found=i((e,t,r,o)=>this.#e(302,e,t,r,o),"found");static seeOther=i((e,t,r,o)=>this.#e(303,e,t,r,o),"seeOther");static notModified=i((e,t,r,o)=>this.#e(304,e,t,r,o),"notModified");static useProxy=i((e,t,r,o)=>this.#e(305,e,t,r,o),"useProxy");static switchProxy=i((e,t,r,o)=>this.#e(306,e,t,r,o),"switchProxy");static temporaryRedirect=i((e,t,r,o)=>this.#e(307,e,t,r,o),"temporaryRedirect");static permanentRedirect=i((e,t,r,o)=>this.#e(308,e,t,r,o),"permanentRedirect");static badRequest=i((e,t,r,o)=>this.#e(400,e,t,r,o),"badRequest");static unauthorized=i((e,t,r,o)=>this.#e(401,e,t,r,o),"unauthorized");static paymentRequired=i((e,t,r,o)=>this.#e(402,e,t,r,o),"paymentRequired");static forbidden=i((e,t,r,o)=>this.#e(403,e,t,r,o),"forbidden");static notFound=i((e,t,r,o)=>this.#e(404,e,t,r,o),"notFound");static methodNotAllowed=i((e,t,r,o)=>this.#e(405,e,t,r,o),"methodNotAllowed");static notAcceptable=i((e,t,r,o)=>this.#e(406,e,t,r,o),"notAcceptable");static proxyAuthenticationRequired=i((e,t,r,o)=>this.#e(407,e,t,r,o),"proxyAuthenticationRequired");static requestTimeout=i((e,t,r,o)=>this.#e(408,e,t,r,o),"requestTimeout");static conflict=i((e,t,r,o)=>this.#e(409,e,t,r,o),"conflict");static gone=i((e,t,r,o)=>this.#e(410,e,t,r,o),"gone");static lengthRequired=i((e,t,r,o)=>this.#e(411,e,t,r,o),"lengthRequired");static preconditionFailed=i((e,t,r,o)=>this.#e(412,e,t,r,o),"preconditionFailed");static contentTooLarge=i((e,t,r,o)=>this.#e(413,e,t,r,o),"contentTooLarge");static uriTooLong=i((e,t,r,o)=>this.#e(414,e,t,r,o),"uriTooLong");static unsupportedMediaType=i((e,t,r,o)=>this.#e(415,e,t,r,o),"unsupportedMediaType");static rangeNotSatisfiable=i((e,t,r,o)=>this.#e(416,e,t,r,o),"rangeNotSatisfiable");static expectationFailed=i((e,t,r,o)=>this.#e(417,e,t,r,o),"expectationFailed");static imATeapot=i((e,t,r,o)=>this.#e(418,e,t,r,o),"imATeapot");static misdirectedRequest=i((e,t,r,o)=>this.#e(421,e,t,r,o),"misdirectedRequest");static unprocessableContent=i((e,t,r,o)=>this.#e(422,e,t,r,o),"unprocessableContent");static locked=i((e,t,r,o)=>this.#e(423,e,t,r,o),"locked");static failedDependency=i((e,t,r,o)=>this.#e(424,e,t,r,o),"failedDependency");static tooEarly=i((e,t,r,o)=>this.#e(425,e,t,r,o),"tooEarly");static upgradeRequired=i((e,t,r,o)=>this.#e(426,e,t,r,o),"upgradeRequired");static preconditionRequired=i((e,t,r,o)=>this.#e(428,e,t,r,o),"preconditionRequired");static tooManyRequests=i((e,t,r,o)=>this.#e(429,e,t,r,o),"tooManyRequests");static requestHeaderFieldsTooLarge=i((e,t,r,o)=>this.#e(431,e,t,r,o),"requestHeaderFieldsTooLarge");static unavailableForLegalReasons=i((e,t,r,o)=>this.#e(451,e,t,r,o),"unavailableForLegalReasons");static internalServerError=i((e,t,r,o)=>this.#e(500,e,t,r,o),"internalServerError");static notImplemented=i((e,t,r,o)=>this.#e(501,e,t,r,o),"notImplemented");static badGateway=i((e,t,r,o)=>this.#e(502,e,t,r,o),"badGateway");static serviceUnavailable=i((e,t,r,o)=>this.#e(503,e,t,r,o),"serviceUnavailable");static gatewayTimeout=i((e,t,r,o)=>this.#e(504,e,t,r,o),"gatewayTimeout");static httpVersionNotSupported=i((e,t,r,o)=>this.#e(505,e,t,r,o),"httpVersionNotSupported");static variantAlsoNegotiates=i((e,t,r,o)=>this.#e(506,e,t,r,o),"variantAlsoNegotiates");static insufficientStorage=i((e,t,r,o)=>this.#e(507,e,t,r,o),"insufficientStorage");static loopDetected=i((e,t,r,o)=>this.#e(508,e,t,r,o),"loopDetected");static notExtended=i((e,t,r,o)=>this.#e(510,e,t,r,o),"notExtended");static networkAuthenticationRequired=i((e,t,r,o)=>this.#e(511,e,t,r,o),"networkAuthenticationRequired")};var{toString:Sc}=Object.prototype,{propertyIsEnumerable:Oc}=Object.prototype;function Gr(n){return Sc.call(n)}i(Gr,"toString");function Te(n){return typeof n=="string"}i(Te,"isString");function ft(n){return Te(n)&&n!==""}i(ft,"isNonEmptyString");function Bs(n){return Gr(n)==="[object RegExp]"}i(Bs,"isRegexp");function Gs(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>Oc.call(n,e))]}i(Gs,"getOwnEnumerableKeys");function st(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}i(st,"isObject");function Vr(n){return typeof n=="number"&&!isNaN(n)}i(Vr,"isNumber");function Wr(n){return n===!0||n===!1}i(Wr,"isBoolean");function Vs(n){return typeof n>"u"}i(Vs,"isUndefined");function Ws(n){return Vs(n)||n===null}i(Ws,"isUndefinedOrNull");function Vt(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(Vt,"isErrorLike");var Js=new Map;function We(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 g("Malformed input string");let e=Js.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 Js.set(n,r),r}i(We,"statusCodesStringToNumberArray");function Fe(n,e,t){if(!e.startsWith("."))throw new g(`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 k(`Error applying ${t} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i(Fe,"getValueFromRequestUser");function je(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new g("Received an array that contains non-string values.");return n}if(Te(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new g(`Expected type of string, received type '${typeof n}'`)}i(je,"parseValueToStringArray");function Ks(n){if(n==null)return[];if(!Array.isArray(n))throw new g(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!st(t))throw new g(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!ft(t.name))throw new g("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!Vr(t.maxAge))throw new g(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!Wr(t.allowCredentials))throw new g("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=Jr(t,"allowedHeaders"),o=Jr(t,"allowedMethods"),s=Jr(t,"exposeHeaders"),a;try{a=je(t.allowedOrigins)}catch(c){throw new g(`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(Ks,"parseCorsPolicies");function Jr(n,e){let t;if(n[e]!==void 0)try{t=je(n[e])}catch(r){throw new g(`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(Jr,"parseOptionalProperty");var An=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"),kn=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 Kr=i((n,e)=>{let t=e.routeData.corsPolicies,r=i(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return T.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let m=n.lookup(c,l);if(!m)return T.notFound(a,u);let h=m.routeConfiguration,I=Ac(l,d,p,h,t);return I.isValid?new Response(void 0,{status:200,statusText:"OK",headers:I.headers}):(I.error&&u.log.warn(I.error),T.notFound(a,u))},"optionsHandler"),o=new he({processors:[Pe],handler:r,gateway:e}),s=new pe({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(s,o.execute)},"registerCorsRoute"),Ac=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 g(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=An(a.allowedOrigins,t);return u?{isValid:!0,headers:kn(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var Qs=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 he({processors:[Pe],handler:t,gateway:e}),o=new pe({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 Je=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.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,this.raw=e.raw}raw;get summary(){return this.raw()?.summary}get operationId(){return this.raw()?.operationId}get tags(){return this.raw()?.tags}get parameters(){return this.raw()?.parameters}get responses(){return this.raw()?.responses}label;key;path;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;policies};var kc=new pe({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Ys=i((n,e)=>{let t=i(async(o,s)=>{let a=$r.value?.notFoundHandler;if(a){let u=new URL(o.url);return a(o,s,{get routesMatchedByPathOnly(){return n.lookupByPathOnly(u.pathname).map(l=>l.routeConfiguration).filter(l=>l instanceof Je)}})}return T.notFound(o,s)},"notFoundHandler"),r=new he({processors:[Pe],handler:t,gateway:e});n.addRoute(kc,r.execute)},"registerNotMatchedHandler");var Lc=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Xs=i(n=>{Lc.forEach(e=>n.delete(e))},"stripCorsHeaders"),Ln=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 Xs(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=_c(o,t.routeData.corsPolicies),u=Nc(n,a),c=new Headers(s.headers);return Xs(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"),_c=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 g(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),Nc=i((n,e)=>{let t=An(e.allowedOrigins,n.headers.get("origin"));return t?kn(e,t):{}},"getCorsHeaders");var Qr=i((n,e)=>{let t=i(async()=>new Response(JSON.stringify({buildId:y.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new he({processors:[Ln],handler:t,gateway:e}),o=new pe({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");import{SpanStatusCode as ea,trace as ta}from"@opentelemetry/api";var ze={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 _n=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!Te(t))throw new k(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},ae=class extends _n{static{i(this,"InboundPolicy")}},Ke=class extends _n{static{i(this,"OutboundPolicy")}};var eo=class extends ae{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)}},to=class extends Ke{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)}},Yr=new Map;function Wt(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(s=>!Yr.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new g(`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 g(`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 g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof ae)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new eo(u,a.handler.options,a.name);else throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new g(`Invalid state - invalid handler on policy '${s}' on route '${r}' (typeof handler '${typeof c.handler}')`);Yr.set(a.name,c)}),t.map(s=>{let a=Yr.get(s);if(a===void 0)throw new k("Internal error. Policy not found in cache.");return a})}i(Wt,"getInboundPolicyInstances");var Xr=new Map;function Jt(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.outbound??[],r=n.path),t.filter(s=>!Xr.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new g(`Invalid state - no Policy with the name '${s}' on route '${r}' was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export],c;if(typeof u!="function")throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof Ke)c=new u(a.handler.options??{},a.name);else if(typeof u=="function")c=new to(u,a.handler.options??{},a.name);else throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new g(`Invalid state - invalid handler on policy '${s}' on route '${r}'`);Xr.set(a.name,c)}),t.map(s=>{let a=Xr.get(s);if(a===void 0)throw new k("Internal error. Policy not found in cache.");return a})}i(Jt,"getOutboundPolicyInstances");var no=i(n=>async(e,t)=>{let r=Re.getContextExtensions(t),o=ta.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 ee||p instanceof Response)return d.end(),p instanceof Response||p instanceof ee?p:new ee(p);{let m=new g(`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:ea.ERROR}),d.recordException(m),m}});if(l instanceof ee)u=l;else if(l instanceof Request)u=new ee(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),ro=i(n=>async(e,t,r)=>{let o=ta.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(ze.PolicyName,c.policyName),d.setAttribute(ze.PolicyType,c.policyType);let p=await c.handler(u,t,r);if(p instanceof Response)return p;{let m=new g(`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:ea.ERROR}),d.recordException(m),m}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),Nn=i(async(n,e,t,r)=>{let o=Wt(e.route,t.routeData.policies),s=Jt(e.route,t.routeData.policies);return ra({request:n,context:e,inboundPolicies:o,outboundPolicies:s,gateway:t,next:r})},"policyProcessor");function na({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>ra({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(na,"createInternalPolicyProcessor");async function ra({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:s}){let a=no(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await s(u),l=ro(r),d;return y.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,n,e):d=c.ok?l(c,n,e):c,d}catch(u){return o.errorHandler(n,e,"Error executing policies",u)}}i(ra,"executePolicyProcessor");var aa=Ju(sa(),1);function ua(n,e){try{let t=/v\d+(-\d+)?/g,o=(0,aa.parse)(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}i(ua,"devPortalBaseURL");var ca="/__zuplo/dev-portal",Bc="dev-portal-id",Gc="dev-portal-host",Vc="zp-account",Wc="zp-project",Jc="dev-portal-build",Kc=`
36
36
  <!DOCTYPE html>
37
37
  <html lang="en">
38
38
  <head>
@@ -55,27 +55,27 @@ import{a as y,b as Be,e as ye,f as Wu,g as cr,h as lr,i as Ju,j as Ku}from"./chu
55
55
  </div>
56
56
  </body>
57
57
  </html>
58
- `,ua=i((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=y.instance.deploymentName,o=y.instance.devPortalBaseUrl,s=i(async(c,l)=>{if(y.instance.isLocalDevelopment)return new Response(Wc,{headers:{"content-type":"text/html"}});if(!r)return T.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=sa(o,c.headers),m=new URL(`${d.pathname}${d.search}`,p),{headers:h,method:I,body:b}=c;return y.instance.build.ACCOUNT_NAME&&h.set(Bc,y.instance.build.ACCOUNT_NAME),y.instance.build.PROJECT_NAME&&h.set(Gc,y.instance.build.PROJECT_NAME),h.set(jc,r),h.set(zc,d.host),h.set(Vc,y.instance.build.BUILD_ID),await $.fetch(m.toString(),{headers:h,method:I,body:b,redirect:"manual"})},"devPortalRoute"),a=new he({processors:[Pe,Nn],handler:s,gateway:e}),u=new pe({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"),ca=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(aa.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new he({processors:[Pe],handler:r,gateway:e}),s=new pe({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${aa}(.*)`,systemRouteName:"developer-portal-legacy"});n.addRoute(s,o.execute)},"registerDevPortalLegacyRedirectRoute");var oo=0,Kt=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=i(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)})},"#setupMethods");#t={};#n;#r;#o;#i;log(e,t,r,o,s,a){oo>=Number.MAX_SAFE_INTEGER&&(oo=0);let u={logId:crypto.randomUUID(),requestId:r,rayId:o,level:e,logSource:t,messages:s,timestamp:new Date,logOwner:this.#n,loggingId:this.#r,buildId:this.#o,vectorClock:oo++};this.#t[e](u,a)}};var le=class extends Ve{static{i(this,"LogPlugin")}};var Mn=class{static{i(this,"LoggingContext")}constructor(e,t,r,o){this.#e=e,this.custom=t,this.originalRequest=r,this.route=o}#e;custom;originalRequest;route;waitUntil=i(e=>{this.#e.waitUntil(e)},"waitUntil")};var Qt=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=i((...e)=>{this.#r.log("debug",this.#e,this.#t,this.#n,e,this.#o)},"debug");info=i((...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)},"info");log=i((...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)},"log");warn=i((...e)=>{this.#r.log("warn",this.#e,this.#t,this.#n,e,this.#o)},"warn");error=i((...e)=>{this.#r.log("error",this.#e,this.#t,this.#n,e,this.#o)},"error")};var Jc=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(n=>[n.name,n]),Kc=new Map(Jc);var Qc=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],io=Symbol(".toJSON was called"),Yc=i(n=>{n[io]=!0;let e=n.toJSON();return delete n[io],e},"toJSON"),Xc=i(n=>Kc.get(n)??Error,"getErrorConstructor"),la=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&&Vt(n)){let l=Xc(n.name);t=new l}else t={};if(e.push(n),s>=o)return t;if(a&&typeof n.toJSON=="function"&&n[io]!==!0)return Yc(n);let c=i(l=>la({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 Qc)typeof n[l]<"u"&&n[l]!==null&&Object.defineProperty(t,l,{value:Vt(n[l])?c(n[l]):n[l],enumerable:r?!0:d,configurable:!0,writable:!0});return t},"destroyCircular");function at(n,e){let t=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof n=="object"&&n!==null?la({from:n,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:r,serialize:!0}):typeof n=="function"?`[Function: ${n.name??"anonymous"}]`:n}i(at,"serializeError");var el=/file:\/\/\/(.*?)\/dist\//g,tl="at async Event.respondWith";function so(n){return typeof n!="string"?n:n.split(`
59
- `).filter(e=>!e.trim().startsWith("at async file")).map((e,t)=>{let r=e.replaceAll(el,"").replaceAll(tl,"").trim();return t===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
58
+ `,la=i((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=y.instance.deploymentName,o=y.instance.devPortalBaseUrl,s=i(async(c,l)=>{if(y.instance.isLocalDevelopment)return new Response(Kc,{headers:{"content-type":"text/html"}});if(!r)return T.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=ua(o,c.headers),m=new URL(`${d.pathname}${d.search}`,p),{headers:h,method:I,body:b}=c;return y.instance.build.ACCOUNT_NAME&&h.set(Vc,y.instance.build.ACCOUNT_NAME),y.instance.build.PROJECT_NAME&&h.set(Wc,y.instance.build.PROJECT_NAME),h.set(Bc,r),h.set(Gc,d.host),h.set(Jc,y.instance.build.BUILD_ID),await $.fetch(m.toString(),{headers:h,method:I,body:b,redirect:"manual"})},"devPortalRoute"),a=new he({processors:[Pe,Nn],handler:s,gateway:e}),u=new pe({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"),da=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(ca.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new he({processors:[Pe],handler:r,gateway:e}),s=new pe({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${ca}(.*)`,systemRouteName:"developer-portal-legacy"});n.addRoute(s,o.execute)},"registerDevPortalLegacyRedirectRoute");var oo=0,Kt=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=i(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)})},"#setupMethods");#t={};#n;#r;#o;#i;log(e,t,r,o,s,a){oo>=Number.MAX_SAFE_INTEGER&&(oo=0);let u={logId:crypto.randomUUID(),requestId:r,rayId:o,level:e,logSource:t,messages:s,timestamp:new Date,logOwner:this.#n,loggingId:this.#r,buildId:this.#o,vectorClock:oo++};this.#t[e](u,a)}};var le=class extends Ve{static{i(this,"LogPlugin")}};var Mn=class{static{i(this,"LoggingContext")}constructor(e,t,r,o){this.#e=e,this.custom=t,this.originalRequest=r,this.route=o}#e;custom;originalRequest;route;waitUntil=i(e=>{this.#e.waitUntil(e)},"waitUntil")};var Qt=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=i((...e)=>{this.#r.log("debug",this.#e,this.#t,this.#n,e,this.#o)},"debug");info=i((...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)},"info");log=i((...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)},"log");warn=i((...e)=>{this.#r.log("warn",this.#e,this.#t,this.#n,e,this.#o)},"warn");error=i((...e)=>{this.#r.log("error",this.#e,this.#t,this.#n,e,this.#o)},"error")};var Qc=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(n=>[n.name,n]),Yc=new Map(Qc);var Xc=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],io=Symbol(".toJSON was called"),el=i(n=>{n[io]=!0;let e=n.toJSON();return delete n[io],e},"toJSON"),tl=i(n=>Yc.get(n)??Error,"getErrorConstructor"),pa=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&&Vt(n)){let l=tl(n.name);t=new l}else t={};if(e.push(n),s>=o)return t;if(a&&typeof n.toJSON=="function"&&n[io]!==!0)return el(n);let c=i(l=>pa({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 Xc)typeof n[l]<"u"&&n[l]!==null&&Object.defineProperty(t,l,{value:Vt(n[l])?c(n[l]):n[l],enumerable:r?!0:d,configurable:!0,writable:!0});return t},"destroyCircular");function at(n,e){let t=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof n=="object"&&n!==null?pa({from:n,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:r,serialize:!0}):typeof n=="function"?`[Function: ${n.name??"anonymous"}]`:n}i(at,"serializeError");var nl=/file:\/\/\/(.*?)\/dist\//g,rl="at async Event.respondWith";function so(n){return typeof n!="string"?n:n.split(`
59
+ `).filter(e=>!e.trim().startsWith("at async file")).map((e,t)=>{let r=e.replaceAll(nl,"").replaceAll(rl,"").trim();return t===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
60
60
  `)}i(so,"cleanStack");function qn(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:`
61
61
  `,newlineOrSpace:`
62
62
  `,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 m=i(h=>{if(u.inlineCharacterLimit===void 0)return h;let I=h.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return I.length<=u.inlineCharacterLimit?I:h.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
63
- `).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"||js(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((I,b)=>{let E=a.length-1===b?p.newline:","+p.newlineOrSpace,L=s(I,u,c+d,l+1);return u.transform&&(L=u.transform(a,b,L)),p.indent+L+E}).join("")+p.pad+"]";return r.pop(),m(h)}if(st(a)){let h=zs(a);if(u.filter&&(h=h.filter(b=>u.filter?.(a,b))),h.length===0)return"{}";r.push(a);let I="{"+p.newline+h.map((b,E)=>{let L=h.length-1===E?p.newline:","+p.newlineOrSpace,O=typeof b=="symbol",Z=!O&&/^[a-z$_][$\w]*$/i.test(b),M=O||Z?b:s(b,u,"",l+1),F=s(a[b],u,c+d,l+1);return u.transform&&(F=u.transform(a,b,F)),p.indent+String(M)+": "+F+L}).join("")+p.pad+"}";return r.pop(),m(I)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,h=>h===`
64
- `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}i(qn,"stringifyObject");function ve(n){return pa(at(n))}i(ve,"serializeMessage");function Ue(n){return n.map(e=>ve(e))}i(Ue,"serializeMessages");function ht(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:pa(at(e))}i(ht,"extractBestMessage");function da(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(Vt(t))if(t.stack)e.push(t.stack);else{let r=qn(at(t));e.push(r)}else if(typeof t=="object"){let r=qn(t);e.push(r)}else{let r=ao(t);e.push(r)}}),e.join(`
65
- `)}i(da,"messagesToMultilineText");function pa(n){return typeof n=="string"?n:JSON.stringify(n)}i(pa,"stringifyNonString");function ao(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"?Gr(n):"unknown"}i(ao,"stringifyNonStringToText");import{SignJWT as nl,importPKCS8 as rl}from"jose";async function we(n,e,t){for(let r=0;r<=n.retries;r++){let o=$.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 g("An unknown error occurred, ensure retries is not negative")}i(we,"fetchRetry");async function Ae({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=n;return await new nl(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(Ae,"getTokenFromGcpServiceAccount");async function ma(n,e,t){if(!n.startsWith("projects/"))throw new g(`The provided audience is invalid: ${n}. It must start with 'projects/'.`);return uo("https://sts.googleapis.com/v1/token",{audience:`//iam.googleapis.com/${n}`,grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token_type:"urn:ietf:params:oauth:token-type:jwt",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,scope:"https://www.googleapis.com/auth/cloud-platform"},t)}i(ma,"exchangeIDTokenForGcpWorkloadToken");async function ga({serviceAccountEmailOrIdentifier:n,audience:e,accessToken:t},r){let o={audience:e,includeEmail:!0};return ha(`https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${encodeURIComponent(n)}:generateIdToken`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},redirect:"follow",body:JSON.stringify(o)},r)}i(ga,"generateServiceAccountIDToken");async function fa(n,e,t){return uo(n,{token:e,returnSecureToken:!0},t)}i(fa,"exchangeFirebaseJwtForIdToken");async function yt(n,e,t){return uo(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(yt,"exchangeGgpJwtForIdToken");async function uo(n,e,t){let r={method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)};return ha(n,r,t)}i(uo,"fetchTokenFromBody");async function ha(n,e,t){let r=await we(t,n,e);if(r.status!==200){let s;try{let a=await r.text(),u=JSON.parse(a);s={cause:u.error_description??u.error??u}}catch{}throw new k({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(ha,"fetchToken");var Ie=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 rl(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 ol={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},ya=i(n=>e=>{let t={};return t.accountName=n.build.ACCOUNT_NAME,t.projectName=n.build.PROJECT_NAME,t.deploymentName=n.deploymentName,t.environmentType=n.loggingEnvironmentStage,t.labels={requestId:e.requestId,source:e.logSource,logOwner:e.logOwner},t.rayId=e.rayId??"",t.runtime={buildId:n.build.BUILD_ID,buildTimestamp:n.build.TIMESTAMP,gitSHA:n.build.GIT_SHA,version:n.build.ZUPLO_VERSION},t.atomicCounter=e.vectorClock,{logId:e.logId,timestamp:e.timestamp,observerdTimestamp:e.timestamp,traceId:e.requestId,severityText:e.level,severityNumber:ol[e.level],body:Ue(e.messages),attributes:t}},"unifiedFormatter");async function Q(n,e){if(n.level==="error"&&console.error(n.messages),!y.instance.remoteLogURL||!y.instance.loggingId||!y.instance.remoteLogToken)return;let t;try{t=await e?.text()}catch{}try{let r={...n,messages:[...n.messages,...t?[t]:[]],logId:crypto.randomUUID(),logOwner:"user",logSource:"runtime",rayId:null,requestId:`global-${crypto.randomUUID()}`,timestamp:new Date,buildId:y.instance.build.BUILD_ID,loggingId:y.instance.loggingId,vectorClock:0};await ba(y.instance,[r])}catch(r){console.error(r)}}i(Q,"sendRemoteGlobalLog");async function ba(n,e){let t=ya(n);try{let r=new Headers({"content-type":"application/json",authentication:`Bearer ${n.remoteLogToken}`});De(r),await $.fetch(`${n.remoteLogURL}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:e.map(t)}),headers:{"content-type":"application/json","user-agent":y.instance.systemUserAgent,"zp-dn":y.instance.deploymentName??"unknown"}})}catch(r){console.error(r)}}i(ba,"sendLogs");var il=i(n=>async e=>{e.length!==0&&await ba(n,e)},"dispatchFunction"),Un,Yt=class{static{i(this,"UnifiedLogTransport")}constructor(e){Un||(Un=new K("unified-log-transport",1,il(e)))}log(e,t){Un.enqueue(e),t.waitUntil(Un.waitUntilFlushed())}};var co=class extends le{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Xt(this.options)}},sl="https://logging.googleapis.com/v2/entries:write?alt=json",lo={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Xt=class{static{i(this,"GoogleLogTransport")}constructor(e){f("logging.google-cloud"),this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=y.instance.loggingEnvironmentType,this.#i=y.instance.loggingEnvironmentStage,this.#r=y.instance.deploymentName,this.#s=e.fields??{}}#e;#t;#n;#r;#o;#i;#s;async init(){this.#t=await Ie.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=Object.assign({allMessages:Ue(e.messages)},this.#s),o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:lo[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=ht(r.allMessages);s.jsonPayload={...r,message:a},this.batcher.enqueue(s),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length===0)return;this.#t||(this.#t=await Ie.init(this.#e));let t=await Ae({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"});try{let r=await $.fetch(sl,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});r.ok||await Q({level:"error",messages:[`Failed to send logs to Google: ${r.status} - ${r.statusText}`]},r)}catch{await Q({level:"error",messages:["Failed to connect to Google logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new K("google-log-transport",1,this.dispatchFunction)};var Hn="gcp";function $n(n){let e={allMessages:Ue(n.messages)},t="zuplo-production",r=ht(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:lo[n.level],timestamp:n.timestamp,"logging.googleapis.com/labels":{buildId:n.buildId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${n.requestId}`,allMessages:e.allMessages};return n.rayId&&(o["logging.googleapis.com/labels"].rayId=n.rayId),o}i($n,"gcpLogFormat");var en=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e,t){if(this.#t===Hn){if(e.messages.length===0)return;this.#e[e.level]($n(e))}else{let r={...e,url:t.originalRequest.url,method:t.originalRequest.method,route:t.route.pathPattern??t.route.path,messages:Ue(e.messages)};this.#e[e.level](JSON.stringify(r))}}};var fo=class extends le{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new tn(this.options)}},po="__ddtags",mo="__ddattr",go=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),al=i(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(go(r)):t.push(`${go(r)}:${go(o.toString())}`)}),t.join(",")},"formatTags"),tn=class{static{i(this,"DataDogTransport")}constructor(e){f("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName,this.#i=e.fields??{},this.#s=e.tags??{},this.#a=e.source??"Zuplo"}#e;#t;#n;#r;#o;#i;#s;#a;log(e,t){let r=Object.assign({},this.#s),o={},s=[...e.messages];if(!y.instance.build.COMPATIBILITY_FLAGS.removeLegacyLogInitialization){let l=t.custom[po];l&&typeof l=="object"&&(f("logging.datadog.legacy-tags"),Object.assign(r,l));let d=e.messages.findIndex(h=>h[po]!==void 0);d>-1&&(Object.assign(r,s[d][po]),s.splice(d,1));let p=t.custom[mo];p&&typeof p=="object"&&(f("logging.datadog.legacy-attributes"),Object.assign(o,p));let m=e.messages.findIndex(h=>h[mo]!==void 0);m>-1&&(Object.assign(o,s[m][mo]),s.splice(m,1))}let a=Ue(s),u={...e,activityId:e.requestId,trace:e.requestId},c=Object.assign({message:{...u,messages:a},ddsource:this.#a,hostname:new URL(t.originalRequest.url).hostname,msg:ht(a),atomic_counter:e.vectorClock,service:e.loggingId,ddtags:al(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o,ray_id:e.rayId,request_id:e.requestId},this.#i,o);this.batcher.enqueue(c),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let t=await $.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}});t.ok||await Q({level:"error",messages:[`Failed to send logs to DataDog: ${t.status} - ${t.statusText}`]},t)}catch{await Q({level:"error",messages:["Failed to connect to DataDog logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new K("data-dog-transport",10,this.dispatchFunction)};var nn=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===Hn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[$n(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId,vectorClock:e.vectorClock}])}};var ho=be("zuplo:logging"),Zn=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(y.instance,e),r=await n.setupUserCoreLogger(y.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;ho("Gateway.setupSystemCoreLogger");let o=[],s=t.getService(In);return s?o.push(new nn(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new en(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Yt(e)),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new Kt(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){ho("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=t.getService(In);if(a&&a.captureUserLogs===!0?r.push(new nn(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new en(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new Yt(e)),!y.instance.build.COMPATIBILITY_FLAGS.removeLegacyLogInitialization&&(o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&(f("logging.google.legacy-initialization"),r.push(new Xt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME}))),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY)){f("logging.datadog.legacy-initialization");let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new tn({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return Ze.forEach(u=>{u instanceof le&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new Kt(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,t,r,o,s,a){ho("Gateway.createRequestLoggers");let u=new Mn(r,o,s,a),c=new Qt(e,t,this.systemCoreLogger,u);return{userRequestLogger:new Qt(e,t,this.userCoreLogger,u),systemRequestLogger:c}}};var bt=class{static{i(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},Fn=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}};var yo=class{static{i(this,"UrlPatternRouterEntry")}constructor(e,t,r){this.fullPath=e,this.config=t,this.executableHandler=r;try{this.urlPattern=new URLPattern({pathname:this.fullPath})}catch(o){throw new Y(`Invalid path '${e}'. ${o.message}`)}}urlPattern;fullPath;config;executableHandler},jn=class{static{i(this,"UrlPatternRouter")}routeEntries=[];addRoute(e,t){if(!(e instanceof Je||e instanceof pe))throw new Y("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r;"pathPattern"in e&&e.pathPattern?r=e.pathPattern:r=e.path;try{let o=new yo(r,e,t);Object.freeze(o.config),this.routeEntries.push(o)}catch(o){throw new Fn(`addRoute-error: Invalid path '${r}'. '${o.message}'`,{cause:o})}}lookup(e,t){if(typeof t>"u")throw new g(`Invalid request - Method was undefined. Path: '${e}'`);for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r];if(o.config.methods.includes(t)){let s=o.urlPattern.exec({pathname:e});if(s!==null)return new bt(o.config,o.executableHandler,s.pathname.groups)}}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],s=o.urlPattern.exec({pathname:e});if(s!==null){let a=new bt(o.config,o.executableHandler,s.pathname.groups);t.push(a)}}return t}};import{AsyncLocalStorage as ul}from"node:async_hooks";var zn={context:new ul};var bo;function wa(n){bo=n}i(wa,"setGlobalZuploEventContext");function Qe(){if(bo===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return bo}i(Qe,"getGlobalZuploEventContext");function Ra({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);ks.includes(o.toLowerCase())&&!Ls.includes(r.toLowerCase())&&t.delete(r)}t.delete(Is)}else As.forEach(r=>{t.delete(r)});return t}i(Ra,"normalizeIncomingRequestHeaders");var Ye=be("zuplo:runtime"),ge=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;Ye("Gateway.constructor"),this.#n=this.setupRoutes(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(Ye("Gateway.initialize"),!n.#e){let s=await Zn.init(r),a=await e(),u={...a,corsPolicies:Ws(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(){Ye("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=[Nn,Ln,Pe];setupRoutes=i(()=>{Ye("Gateway.setupRoutes");let e=this.routeData,t=new jn;if(e.routes.length===0)return jr(t,this),Qr(t,this),Kr(t,this),Js(t,this),t;let{enabled:r,version:o}=this.runtimeSettings.developerPortal;r&&o==="legacy"&&(ca(t,this),ua(t,this)),jr(t,this),Qr(t,this),Kr(t,this);for(let s of Ze)s instanceof fe&&s.registerRoutes(t,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 g(`Invalid state - No handler on route for path '${s.path}'`);let u=new he({processors:this.#r,handler:a,gateway:this}),c=new Je(s);t.addRoute(c,u.execute)}),Ks(t,this),t},"setupRoutes");errorHandler(e,t,r,o){Ye("Gateway.internalErrorResponse"),t.log.error(r,o);let s={};if(y.instance.isLocalDevelopment||y.instance.isWorkingCopy)if(o instanceof k&&o.extensionMembers)s=o.extensionMembers;else if(o.cause){let a=at(o.cause);"stack"in a&&(a.stack=so(a.stack)),s={cause:a}}else{let a=at(o);"stack"in a&&(a.stack=so(a.stack)),s={cause:a}}return T.internalServerError(e,t,{detail:o.message,...s})}async handleRequest(e,t,r){let o=e.headers.get(mt)??e.headers.get(Ps)??r?.parentContext?.requestId??crypto.randomUUID(),s=e.headers.get(ot);wa(t);let a=Ra({headers:e.headers,removeAllVendorHeadersExceptListed:y.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(mt,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let Z=new Headers(u.headers);Z.set(vr,"true"),u=new Request(u,{headers:Z,body:null})}u=await $s(u);let c=new URL(u.url),l=c.pathname,d=this.#n.lookup(l,u.method);if(!d)throw new Y(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let p={},{userRequestLogger:m,systemRequestLogger:h}=this.#t.createRequestLoggers(o,s,t,p,u,d.routeConfiguration);gt(c)||m.debug(`Request received '${c.pathname}'`,{method:u.method,url:c.pathname,hostname:c.hostname,route:d.routeConfiguration.path});let I=new Bn(e.headers),b=new ee(u,{params:d.params}),E=new Gn({logger:m,route:d.routeConfiguration,requestId:o,event:t,custom:p,incomingRequestProperties:I,parentContext:r?.parentContext}),L=zn.context.getStore();L&&(L.context=E);let O=d.routeConfiguration.raw();cl.getActiveSpan()?.setAttributes({"http.route":E.route.path??E.route.pathPattern,"cloud.region":E.incomingRequestProperties.colo,[ze.RoutePathPattern]:E.route.pathPattern,[ze.RouteOperationId]:O.operationId,[ze.RouteTrace]:O["x-zuplo-trace"],[ze.RouteSystem]:gt(c)?!0:void 0}),Re.initialize(E,b);try{if(J.addLogger(E,h),y.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!gt(c):!c.pathname.startsWith("/__zuplo")){let S=await qs(b,E);if(S instanceof Response)return S;{let H=Re.getContextExtensions(E);b=S,H.latestRequest=b}}let Z=d.executableHandler;ll(Z,d,u),Ye("Gateway.handleRequest - call user handler");let M=await Z(b,E);if(Ye("Gateway.handleRequest - user handler"),!(M instanceof Response))throw new k(`Invalid Response type from the request handler: ${typeof M}`);if(M.bodyUsed)throw new k("The response object has already been used. Return a new response instead.");let F;if(M.headers.get(mt)===null&&!M.webSocket){let S=new Headers(M.headers);S.set(mt,o),F=new Response(M.body,{status:M.status,statusText:M.statusText,headers:S,cf:M.cf})}else F=M;return F}catch(Z){return Z instanceof k?(m.error(Z),h.warn(Z)):h.error(Z),await this.errorHandler(b,E,"Error executing handler",Z)}}};function ll(n,e,t){if(Ye("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new g(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new g(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}i(ll,"checkHandler");import{SpanStatusCode as Pa,trace as Ia}from"@opentelemetry/api";var Ea=i(async(n,e,t)=>{let r=ge.instance.routeData.policies,o=Wt([n],r);if(o.length===0)throw new k(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);let s=o[0];return await Ia.getTracer("pipeline").startActiveSpan(`policy:${s.policyName}`,async c=>{try{let l=await s.handler(e,t);if(l instanceof Request||l instanceof ee||l instanceof Response)return l instanceof Response||l instanceof ee?l:new ee(l);{let d=new g(`Invalid state - invalid handler on policy '${s.policyName}' invoked via 'invokeInboundPolicy' on route '${t.route.path}'. The result of an inbound policy must be a Response or Request.`);throw c.setStatus({code:Pa.ERROR}),c.recordException(d),d}}finally{c.end()}})},"invokeInboundPolicy"),xa=i(async(n,e,t,r)=>{let o=ge.instance.routeData.policies,s=Jt([n],o);if(s.length===0)throw new k(`Invalid 'invokeOutboundPolicy call' - no policy '${n}' found.`);let a=s[0];return await Ia.getTracer("pipeline").startActiveSpan(`policy:${a.policyName}`,async l=>{try{let d=await a.handler(e,t,r);if(d instanceof Response)return d;{let p=new g(`Invalid state - invalid handler on policy '${a.policyName}' invoked via 'invokeOutboundPolicy' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw l.setStatus({code:Pa.ERROR}),l.recordException(p),p}}finally{l.end()}})},"invokeOutboundPolicy");function dl(n){let e={};if(!n)return e;try{let t=n.split(","),r={};return t.forEach(o=>{let[s,a]=o.split("=");s&&a&&(r[s.trim()]=a.trim())}),r.asnum&&(e[Mt]=r.asnum),r.zip&&(e[qt]=r.zip.split("+")[0]),r.dma&&(e[Ut]=r.dma),r.region_code&&(e[Ht]=r.region_code),r.timezone&&(e[$t]=r.timezone),r.city&&(e[yn]=r.city),r.continent&&(e[bn]=r.continent),r.country_code&&(e[wn]=r.country_code),r.long&&(e[Rn]=r.long),r.lat&&(e[Pn]=r.lat),e}catch{return{}}}i(dl,"parseEdgeScapeHeader");function Ta(n,e){let t=dl(e);for(let[r,o]of Object.entries(t))n.has(r)||n.set(r,o)}i(Ta,"setZpHeadersFromAkamaiEdgeScapeHeader");var Bn=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e;let t=e.get(Dr);if(t){let r=new Headers(e);Ta(r,t),this.#e=r}}get asn(){try{let e=this.#e.get(Mt);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Lr)??void 0}get city(){return this.#e.get(Cr)??this.#e.get(yn)??void 0}get continent(){return this.#e.get(Sr)??this.#e.get(bn)??void 0}get country(){return this.#e.get(Or)??this.#e.get(wn)??void 0}get latitude(){return this.#e.get(kr)??this.#e.get(Pn)??void 0}get longitude(){return this.#e.get(Ar)??this.#e.get(Rn)??void 0}get colo(){return this.#e.get(_r)??void 0}get postalCode(){return this.#e.get(vs)??this.#e.get(qt)??void 0}get metroCode(){return this.#e.get(Ts)??this.#e.get(Ut)??void 0}get region(){return this.#e.get(Es)??this.#e.get(Nr)??void 0}get regionCode(){return this.#e.get(xs)??this.#e.get(Ht)??void 0}get timezone(){return this.#e.get(Cs)??this.#e.get($t)??void 0}get httpProtocol(){return this.#e.get(Os)??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,httpProtocol:this.httpProtocol}}};function Xe(n){return{contextId:n.contextId,incomingRequestProperties:n.incomingRequestProperties,requestId:n.requestId,route:n.route,custom:n.custom,parentContext:n.parentContext}}i(Xe,"createRewriteContext");var Bt=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},Gt=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},Re=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 k(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;#t;#n;#r;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[],this.#r=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}addHandlerResponseHook(e){this.#r.push(e)}onResponseSendingFinal=i(async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)},"onResponseSendingFinal");onResponseSending=i(async(e,t,r)=>{let o=e;for(let s of this.#n)o=await s(e,t,r);return o},"onResponseSending");onHandlerResponse=i(async(e,t,r)=>{for(let o of this.#r)await o(e,t,r)},"onHandlerResponse")},Gn=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:s,incomingRequestProperties:a,parentContext:u}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=s,this.incomingRequestProperties=a,this.parentContext=u,this.#e=o,this.invokeInboundPolicy=(c,l)=>Ea(c,l,this),this.contextId=crypto.randomUUID(),this.invokeOutboundPolicy=(c,l,d)=>xa(c,l,d,this),this.invokeRoute=async(c,l)=>{let d=new ee(c,l);return ge.instance.handleRequest(d,this,{parentContext:this})},this.waitUntil=c=>{this.#e.waitUntil(c)},this.addResponseSendingHook=c=>{Re.getContextExtensions(this).addResponseSendingHook(c)},this.addResponseSendingFinalHook=c=>{Re.getContextExtensions(this).addResponseSendingFinalHook(c)},Object.freeze(this)}#e;contextId;requestId;log;route;custom;incomingRequestProperties;parentContext;invokeInboundPolicy;invokeOutboundPolicy;invokeRoute;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 pl="Error initializing gateway. Check your configuration for errors or contact support.",ml="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",wo=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=i(async(e,t,r)=>{y.initialize({build:this.buildEnvironment,runtime:t});try{await Zs(this.runtimeInit)}catch(s){this.handleError(s,ml,e)}return Ds(i(async(s,a)=>{let u;try{u=await ge.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(l){return this.handleError(l,pl,s)}let c={context:void 0};return zn.context.run(c,async()=>u.handleRequest(s,a))},"innerHandler"))(e,r)},"requestHandler");handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof g&&(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:y.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};function gl(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(gl,"lexer");function Po(n,e){e===void 0&&(e={});for(var t=gl(n),r=e.prefixes,o=r===void 0?"./":r,s=e.delimiter,a=s===void 0?"/#?":s,u=[],c=0,l=0,d="",p=i(function(j){if(l<t.length&&t[l].type===j)return t[l++].value},"tryConsume"),m=i(function(j){var v=p(j);if(v!==void 0)return v;var x=t[l],q=x.type,ce=x.index;throw new TypeError("Unexpected ".concat(q," at ").concat(ce,", expected ").concat(j))},"mustConsume"),h=i(function(){for(var j="",v;v=p("CHAR")||p("ESCAPED_CHAR");)j+=v;return j},"consumeText"),I=i(function(j){for(var v=0,x=a;v<x.length;v++){var q=x[v];if(j.indexOf(q)>-1)return!0}return!1},"isSafe"),b=i(function(j){var v=u[u.length-1],x=j||(v&&typeof v=="string"?v:"");if(v&&!x)throw new TypeError('Must have text between two parameters, missing text after "'.concat(v.name,'"'));return!x||I(x)?"[^".concat(Ro(a),"]+?"):"(?:(?!".concat(Ro(x),")[^").concat(Ro(a),"])+?")},"safePattern");l<t.length;){var E=p("CHAR"),L=p("NAME"),O=p("PATTERN");if(L||O){var Z=E||"";o.indexOf(Z)===-1&&(d+=Z,Z=""),d&&(u.push(d),d=""),u.push({name:L||c++,prefix:Z,suffix:"",pattern:O||b(Z),modifier:p("MODIFIER")||""});continue}var M=E||p("ESCAPED_CHAR");if(M){d+=M;continue}d&&(u.push(d),d="");var F=p("OPEN");if(F){var Z=h(),S=p("NAME")||"",H=p("PATTERN")||"",V=h();m("CLOSE"),u.push({name:S||(H?c++:""),pattern:S&&!H?b(Z):H,prefix:Z,suffix:V,modifier:p("MODIFIER")||""});continue}m("END")}return u}i(Po,"parse");function va(n,e){return fl(Po(n,e),e)}i(va,"compile");function fl(n,e){e===void 0&&(e={});var t=hl(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 m=c?c[p.name]:void 0,h=p.modifier==="?"||p.modifier==="*",I=p.modifier==="*"||p.modifier==="+";if(Array.isArray(m)){if(!I)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(m.length===0){if(h)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var b=0;b<m.length;b++){var E=o(m[b],p);if(a&&!u[d].test(E))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(E,'"'));l+=p.prefix+E+p.suffix}continue}if(typeof m=="string"||typeof m=="number"){var E=o(String(m),p);if(a&&!u[d].test(E))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(E,'"'));l+=p.prefix+E+p.suffix;continue}if(!h){var L=I?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(L))}}return l}}i(fl,"tokensToFunction");function Ro(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(Ro,"escapeString");function hl(n){return n&&n.sensitive?"":"i"}i(hl,"flags");var yl=be("zuplo:runtime"),Eo=new TextEncoder,Ca={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},bl=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],wt=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 xo(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){yl("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,t),a=$.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 g("An unknown error occurred, ensure retries is not negative")}},xo=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:m,appendSessionToken:h,allHeaders:I,singleEncode:b}){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 E,L;(!c||!l)&&([E,L]=wl(this.url,this.headers)),this.service=c||E||"",this.region=l||L||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=h||this.service==="iotdevicegateway",this.headers.delete("Host");let O=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"),O.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&O.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(M=>I||!bl.includes(M)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(M=>M+":"+(M==="host"?this.url.host:(this.headers.get(M)||"").replace(/\s+/g," "))).join(`
66
- `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!O.has("X-Amz-Expires")&&O.set("X-Amz-Expires","86400"),O.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),O.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),O.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,"/");b||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=Oa(this.encodedPath);let Z=new Set;this.encodedSearch=[...this.url.searchParams].filter(([M])=>{if(!M)return!1;if(this.service==="s3"){if(Z.has(M))return!1;Z.add(M)}return!0}).map(M=>M.map(F=>Oa(encodeURIComponent(F)))).sort(([M,F],[S,H])=>M<S?-1:M>S?1:F<H?-1:F>H?1:0).map(M=>M.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 rn("AWS4"+this.secretAccessKey,e),s=await rn(o,this.region),a=await rn(s,this.service);r=await rn(a,"aws4_request"),this.cache.set(t,r)}return Io(await rn(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Io(await Sa(await this.canonicalString()))].join(`
63
+ `).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"||Bs(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((I,b)=>{let E=a.length-1===b?p.newline:","+p.newlineOrSpace,L=s(I,u,c+d,l+1);return u.transform&&(L=u.transform(a,b,L)),p.indent+L+E}).join("")+p.pad+"]";return r.pop(),m(h)}if(st(a)){let h=Gs(a);if(u.filter&&(h=h.filter(b=>u.filter?.(a,b))),h.length===0)return"{}";r.push(a);let I="{"+p.newline+h.map((b,E)=>{let L=h.length-1===E?p.newline:","+p.newlineOrSpace,O=typeof b=="symbol",Z=!O&&/^[a-z$_][$\w]*$/i.test(b),M=O||Z?b:s(b,u,"",l+1),F=s(a[b],u,c+d,l+1);return u.transform&&(F=u.transform(a,b,F)),p.indent+String(M)+": "+F+L}).join("")+p.pad+"}";return r.pop(),m(I)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,h=>h===`
64
+ `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}i(qn,"stringifyObject");function ve(n){return ga(at(n))}i(ve,"serializeMessage");function Ue(n){return n.map(e=>ve(e))}i(Ue,"serializeMessages");function ht(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:ga(at(e))}i(ht,"extractBestMessage");function ma(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(Vt(t))if(t.stack)e.push(t.stack);else{let r=qn(at(t));e.push(r)}else if(typeof t=="object"){let r=qn(t);e.push(r)}else{let r=ao(t);e.push(r)}}),e.join(`
65
+ `)}i(ma,"messagesToMultilineText");function ga(n){return typeof n=="string"?n:JSON.stringify(n)}i(ga,"stringifyNonString");function ao(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"?Gr(n):"unknown"}i(ao,"stringifyNonStringToText");import{SignJWT as ol,importPKCS8 as il}from"jose";async function we(n,e,t){for(let r=0;r<=n.retries;r++){let o=$.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 g("An unknown error occurred, ensure retries is not negative")}i(we,"fetchRetry");async function Ae({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=n;return await new ol(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(Ae,"getTokenFromGcpServiceAccount");async function fa(n,e,t){if(!n.startsWith("projects/"))throw new g(`The provided audience is invalid: ${n}. It must start with 'projects/'.`);return uo("https://sts.googleapis.com/v1/token",{audience:`//iam.googleapis.com/${n}`,grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token_type:"urn:ietf:params:oauth:token-type:jwt",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,scope:"https://www.googleapis.com/auth/cloud-platform"},t)}i(fa,"exchangeIDTokenForGcpWorkloadToken");async function ha({serviceAccountEmailOrIdentifier:n,audience:e,accessToken:t},r){let o={audience:e,includeEmail:!0};return ba(`https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${encodeURIComponent(n)}:generateIdToken`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},redirect:"follow",body:JSON.stringify(o)},r)}i(ha,"generateServiceAccountIDToken");async function ya(n,e,t){return uo(n,{token:e,returnSecureToken:!0},t)}i(ya,"exchangeFirebaseJwtForIdToken");async function yt(n,e,t){return uo(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(yt,"exchangeGgpJwtForIdToken");async function uo(n,e,t){let r={method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)};return ba(n,r,t)}i(uo,"fetchTokenFromBody");async function ba(n,e,t){let r=await we(t,n,e);if(r.status!==200){let s;try{let a=await r.text(),u=JSON.parse(a);s={cause:u.error_description??u.error??u}}catch{}throw new k({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(ba,"fetchToken");var Ie=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 il(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 sl={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},wa=i(n=>e=>{let t={};return t.accountName=n.build.ACCOUNT_NAME,t.projectName=n.build.PROJECT_NAME,t.deploymentName=n.deploymentName,t.environmentType=n.loggingEnvironmentStage,t.labels={requestId:e.requestId,source:e.logSource,logOwner:e.logOwner},t.rayId=e.rayId??"",t.runtime={buildId:n.build.BUILD_ID,buildTimestamp:n.build.TIMESTAMP,gitSHA:n.build.GIT_SHA,version:n.build.ZUPLO_VERSION},t.atomicCounter=e.vectorClock,{logId:e.logId,timestamp:e.timestamp,observerdTimestamp:e.timestamp,traceId:e.requestId,severityText:e.level,severityNumber:sl[e.level],body:Ue(e.messages),attributes:t}},"unifiedFormatter");async function Q(n,e){if(n.level==="error"&&console.error(n.messages),!y.instance.remoteLogURL||!y.instance.loggingId||!y.instance.remoteLogToken)return;let t;try{t=await e?.text()}catch{}try{let r={...n,messages:[...n.messages,...t?[t]:[]],logId:crypto.randomUUID(),logOwner:"user",logSource:"runtime",rayId:null,requestId:`global-${crypto.randomUUID()}`,timestamp:new Date,buildId:y.instance.build.BUILD_ID,loggingId:y.instance.loggingId,vectorClock:0};await Ra(y.instance,[r])}catch(r){console.error(r)}}i(Q,"sendRemoteGlobalLog");async function Ra(n,e){let t=wa(n);try{let r=new Headers({"content-type":"application/json",authentication:`Bearer ${n.remoteLogToken}`});De(r),await $.fetch(`${n.remoteLogURL}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:e.map(t)}),headers:{"content-type":"application/json","user-agent":y.instance.systemUserAgent,"zp-dn":y.instance.deploymentName??"unknown"}})}catch(r){console.error(r)}}i(Ra,"sendLogs");var al=i(n=>async e=>{e.length!==0&&await Ra(n,e)},"dispatchFunction"),Un,Yt=class{static{i(this,"UnifiedLogTransport")}constructor(e){Un||(Un=new K("unified-log-transport",1,al(e)))}log(e,t){Un.enqueue(e),t.waitUntil(Un.waitUntilFlushed())}};var co=class extends le{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Xt(this.options)}},ul="https://logging.googleapis.com/v2/entries:write?alt=json",lo={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Xt=class{static{i(this,"GoogleLogTransport")}constructor(e){f("logging.google-cloud"),this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=y.instance.loggingEnvironmentType,this.#i=y.instance.loggingEnvironmentStage,this.#r=y.instance.deploymentName,this.#s=e.fields??{}}#e;#t;#n;#r;#o;#i;#s;async init(){this.#t=await Ie.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=Object.assign({allMessages:Ue(e.messages)},this.#s),o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:lo[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=ht(r.allMessages);s.jsonPayload={...r,message:a},this.batcher.enqueue(s),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length===0)return;this.#t||(this.#t=await Ie.init(this.#e));let t=await Ae({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"});try{let r=await $.fetch(ul,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});r.ok||await Q({level:"error",messages:[`Failed to send logs to Google: ${r.status} - ${r.statusText}`]},r)}catch{await Q({level:"error",messages:["Failed to connect to Google logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new K("google-log-transport",1,this.dispatchFunction)};var Hn="gcp";function $n(n){let e={allMessages:Ue(n.messages)},t="zuplo-production",r=ht(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:lo[n.level],timestamp:n.timestamp,"logging.googleapis.com/labels":{buildId:n.buildId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${n.requestId}`,allMessages:e.allMessages};return n.rayId&&(o["logging.googleapis.com/labels"].rayId=n.rayId),o}i($n,"gcpLogFormat");var en=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e,t){if(this.#t===Hn){if(e.messages.length===0)return;this.#e[e.level]($n(e))}else{let r={...e,url:t.originalRequest.url,method:t.originalRequest.method,route:t.route.pathPattern??t.route.path,messages:Ue(e.messages)};this.#e[e.level](JSON.stringify(r))}}};var fo=class extends le{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new tn(this.options)}},po="__ddtags",mo="__ddattr",go=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),cl=i(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(go(r)):t.push(`${go(r)}:${go(o.toString())}`)}),t.join(",")},"formatTags"),tn=class{static{i(this,"DataDogTransport")}constructor(e){f("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName,this.#i=e.fields??{},this.#s=e.tags??{},this.#a=e.source??"Zuplo"}#e;#t;#n;#r;#o;#i;#s;#a;log(e,t){let r=Object.assign({},this.#s),o={},s=[...e.messages];if(!y.instance.build.COMPATIBILITY_FLAGS.removeLegacyLogInitialization){let l=t.custom[po];l&&typeof l=="object"&&(f("logging.datadog.legacy-tags"),Object.assign(r,l));let d=e.messages.findIndex(h=>h[po]!==void 0);d>-1&&(Object.assign(r,s[d][po]),s.splice(d,1));let p=t.custom[mo];p&&typeof p=="object"&&(f("logging.datadog.legacy-attributes"),Object.assign(o,p));let m=e.messages.findIndex(h=>h[mo]!==void 0);m>-1&&(Object.assign(o,s[m][mo]),s.splice(m,1))}let a=Ue(s),u={...e,activityId:e.requestId,trace:e.requestId},c=Object.assign({message:{...u,messages:a},ddsource:this.#a,hostname:new URL(t.originalRequest.url).hostname,msg:ht(a),atomic_counter:e.vectorClock,service:e.loggingId,ddtags:cl(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o,ray_id:e.rayId,request_id:e.requestId},this.#i,o);this.batcher.enqueue(c),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let t=await $.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}});t.ok||await Q({level:"error",messages:[`Failed to send logs to DataDog: ${t.status} - ${t.statusText}`]},t)}catch{await Q({level:"error",messages:["Failed to connect to DataDog logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new K("data-dog-transport",10,this.dispatchFunction)};var nn=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===Hn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[$n(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId,vectorClock:e.vectorClock}])}};var ho=be("zuplo:logging"),Zn=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(y.instance,e),r=await n.setupUserCoreLogger(y.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;ho("Gateway.setupSystemCoreLogger");let o=[],s=t.getService(In);return s?o.push(new nn(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new en(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Yt(e)),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new Kt(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){ho("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=t.getService(In);if(a&&a.captureUserLogs===!0?r.push(new nn(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new en(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new Yt(e)),!y.instance.build.COMPATIBILITY_FLAGS.removeLegacyLogInitialization&&(o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&(f("logging.google.legacy-initialization"),r.push(new Xt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME}))),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY)){f("logging.datadog.legacy-initialization");let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new tn({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return Ze.forEach(u=>{u instanceof le&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new Kt(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,t,r,o,s,a){ho("Gateway.createRequestLoggers");let u=new Mn(r,o,s,a),c=new Qt(e,t,this.systemCoreLogger,u);return{userRequestLogger:new Qt(e,t,this.userCoreLogger,u),systemRequestLogger:c}}};var bt=class{static{i(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},Fn=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}};var yo=class{static{i(this,"UrlPatternRouterEntry")}constructor(e,t,r){this.fullPath=e,this.config=t,this.executableHandler=r;try{this.urlPattern=new URLPattern({pathname:this.fullPath})}catch(o){throw new Y(`Invalid path '${e}'. ${o.message}`)}}urlPattern;fullPath;config;executableHandler},jn=class{static{i(this,"UrlPatternRouter")}routeEntries=[];addRoute(e,t){if(!(e instanceof Je||e instanceof pe))throw new Y("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r;"pathPattern"in e&&e.pathPattern?r=e.pathPattern:r=e.path;try{let o=new yo(r,e,t);Object.freeze(o.config),this.routeEntries.push(o)}catch(o){throw new Fn(`addRoute-error: Invalid path '${r}'. '${o.message}'`,{cause:o})}}lookup(e,t){if(typeof t>"u")throw new g(`Invalid request - Method was undefined. Path: '${e}'`);for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r];if(o.config.methods.includes(t)){let s=o.urlPattern.exec({pathname:e});if(s!==null)return new bt(o.config,o.executableHandler,s.pathname.groups)}}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],s=o.urlPattern.exec({pathname:e});if(s!==null){let a=new bt(o.config,o.executableHandler,s.pathname.groups);t.push(a)}}return t}};import{AsyncLocalStorage as ll}from"node:async_hooks";var zn={context:new ll};var bo;function Pa(n){bo=n}i(Pa,"setGlobalZuploEventContext");function Qe(){if(bo===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return bo}i(Qe,"getGlobalZuploEventContext");function Ia({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);Ls.includes(o.toLowerCase())&&!_s.includes(r.toLowerCase())&&t.delete(r)}t.delete(Is)}else ks.forEach(r=>{t.delete(r)});return t}i(Ia,"normalizeIncomingRequestHeaders");var Ye=be("zuplo:runtime"),ge=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;Ye("Gateway.constructor"),this.#n=this.setupRoutes(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(Ye("Gateway.initialize"),!n.#e){let s=await Zn.init(r),a=await e(),u={...a,corsPolicies:Ks(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(){Ye("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=[Nn,Ln,Pe];setupRoutes=i(()=>{Ye("Gateway.setupRoutes");let e=this.routeData,t=new jn;if(e.routes.length===0)return jr(t,this),Qr(t,this),Kr(t,this),Qs(t,this),t;let{enabled:r,version:o}=this.runtimeSettings.developerPortal;r&&o==="legacy"&&(da(t,this),la(t,this)),jr(t,this),Qr(t,this),Kr(t,this);for(let s of Ze)s instanceof fe&&s.registerRoutes(t,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 g(`Invalid state - No handler on route for path '${s.path}'`);let u=new he({processors:this.#r,handler:a,gateway:this}),c=new Je(s);t.addRoute(c,u.execute)}),Ys(t,this),t},"setupRoutes");errorHandler(e,t,r,o){Ye("Gateway.internalErrorResponse"),t.log.error(r,o);let s={};if(y.instance.isLocalDevelopment||y.instance.isWorkingCopy)if(o instanceof k&&o.extensionMembers)s=o.extensionMembers;else if(o.cause){let a=at(o.cause);"stack"in a&&(a.stack=so(a.stack)),s={cause:a}}else{let a=at(o);"stack"in a&&(a.stack=so(a.stack)),s={cause:a}}return T.internalServerError(e,t,{detail:o.message,...s})}async handleRequest(e,t,r){let o=e.headers.get(mt)??e.headers.get(Ps)??r?.parentContext?.requestId??crypto.randomUUID(),s=e.headers.get(ot);Pa(t);let a=Ia({headers:e.headers,removeAllVendorHeadersExceptListed:y.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(mt,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let Z=new Headers(u.headers);Z.set(vr,"true"),u=new Request(u,{headers:Z,body:null})}u=await Zs(u);let c=new URL(u.url),l=c.pathname,d=this.#n.lookup(l,u.method);if(!d)throw new Y(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let p={},{userRequestLogger:m,systemRequestLogger:h}=this.#t.createRequestLoggers(o,s,t,p,u,d.routeConfiguration);gt(c)||m.debug(`Request received '${c.pathname}'`,{method:u.method,url:c.pathname,hostname:c.hostname,route:d.routeConfiguration.path});let I=new Bn(e.headers),b=new ee(u,{params:d.params}),E=new Gn({logger:m,route:d.routeConfiguration,requestId:o,event:t,custom:p,incomingRequestProperties:I,parentContext:r?.parentContext}),L=zn.context.getStore();L&&(L.context=E);let O=d.routeConfiguration.raw();dl.getActiveSpan()?.setAttributes({"http.route":E.route.path??E.route.pathPattern,"cloud.region":E.incomingRequestProperties.colo,[ze.RoutePathPattern]:E.route.pathPattern,[ze.RouteOperationId]:O.operationId,[ze.RouteTrace]:O["x-zuplo-trace"],[ze.RouteSystem]:gt(c)?!0:void 0}),Re.initialize(E,b);try{if(J.addLogger(E,h),y.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!gt(c):!c.pathname.startsWith("/__zuplo")){let S=await Us(b,E);if(S instanceof Response)return S;{let H=Re.getContextExtensions(E);b=S,H.latestRequest=b}}let Z=d.executableHandler;pl(Z,d,u),Ye("Gateway.handleRequest - call user handler");let M=await Z(b,E);if(Ye("Gateway.handleRequest - user handler"),!(M instanceof Response))throw new k(`Invalid Response type from the request handler: ${typeof M}`);if(M.bodyUsed)throw new k("The response object has already been used. Return a new response instead.");let F;if(M.headers.get(mt)===null&&!M.webSocket){let S=new Headers(M.headers);S.set(mt,o),F=new Response(M.body,{status:M.status,statusText:M.statusText,headers:S,cf:M.cf})}else F=M;return F}catch(Z){return Z instanceof k?(m.error(Z),h.warn(Z)):h.error(Z),await this.errorHandler(b,E,"Error executing handler",Z)}}};function pl(n,e,t){if(Ye("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new g(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new g(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}i(pl,"checkHandler");import{SpanStatusCode as Ea,trace as xa}from"@opentelemetry/api";var Ta=i(async(n,e,t)=>{let r=ge.instance.routeData.policies,o=Wt([n],r);if(o.length===0)throw new k(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);let s=o[0];return await xa.getTracer("pipeline").startActiveSpan(`policy:${s.policyName}`,async c=>{try{let l=await s.handler(e,t);if(l instanceof Request||l instanceof ee||l instanceof Response)return l instanceof Response||l instanceof ee?l:new ee(l);{let d=new g(`Invalid state - invalid handler on policy '${s.policyName}' invoked via 'invokeInboundPolicy' on route '${t.route.path}'. The result of an inbound policy must be a Response or Request.`);throw c.setStatus({code:Ea.ERROR}),c.recordException(d),d}}finally{c.end()}})},"invokeInboundPolicy"),va=i(async(n,e,t,r)=>{let o=ge.instance.routeData.policies,s=Jt([n],o);if(s.length===0)throw new k(`Invalid 'invokeOutboundPolicy call' - no policy '${n}' found.`);let a=s[0];return await xa.getTracer("pipeline").startActiveSpan(`policy:${a.policyName}`,async l=>{try{let d=await a.handler(e,t,r);if(d instanceof Response)return d;{let p=new g(`Invalid state - invalid handler on policy '${a.policyName}' invoked via 'invokeOutboundPolicy' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw l.setStatus({code:Ea.ERROR}),l.recordException(p),p}}finally{l.end()}})},"invokeOutboundPolicy");function ml(n){let e={};if(!n)return e;try{let t=n.split(","),r={};return t.forEach(o=>{let[s,a]=o.split("=");s&&a&&(r[s.trim()]=a.trim())}),r.asnum&&(e[Mt]=r.asnum),r.zip&&(e[qt]=r.zip.split("+")[0]),r.dma&&(e[Ut]=r.dma),r.region_code&&(e[Ht]=r.region_code),r.timezone&&(e[$t]=r.timezone),r.city&&(e[yn]=r.city),r.continent&&(e[bn]=r.continent),r.country_code&&(e[wn]=r.country_code),r.long&&(e[Rn]=r.long),r.lat&&(e[Pn]=r.lat),e}catch{return{}}}i(ml,"parseEdgeScapeHeader");function Ca(n,e){let t=ml(e);for(let[r,o]of Object.entries(t))n.has(r)||n.set(r,o)}i(Ca,"setZpHeadersFromAkamaiEdgeScapeHeader");var Bn=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e;let t=e.get(Dr);if(t){let r=new Headers(e);Ca(r,t),this.#e=r}}get asn(){try{let e=this.#e.get(Mt);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Lr)??void 0}get city(){return this.#e.get(Cr)??this.#e.get(yn)??void 0}get continent(){return this.#e.get(Sr)??this.#e.get(bn)??void 0}get country(){return this.#e.get(Or)??this.#e.get(wn)??void 0}get latitude(){return this.#e.get(kr)??this.#e.get(Pn)??void 0}get longitude(){return this.#e.get(Ar)??this.#e.get(Rn)??void 0}get colo(){return this.#e.get(_r)??void 0}get postalCode(){return this.#e.get(vs)??this.#e.get(qt)??void 0}get metroCode(){return this.#e.get(Ts)??this.#e.get(Ut)??void 0}get region(){return this.#e.get(Es)??this.#e.get(Nr)??void 0}get regionCode(){return this.#e.get(xs)??this.#e.get(Ht)??void 0}get timezone(){return this.#e.get(Cs)??this.#e.get($t)??void 0}get httpProtocol(){return this.#e.get(As)??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,httpProtocol:this.httpProtocol}}};function Xe(n){return{contextId:n.contextId,incomingRequestProperties:n.incomingRequestProperties,requestId:n.requestId,route:n.route,custom:n.custom,parentContext:n.parentContext}}i(Xe,"createRewriteContext");var Bt=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},Gt=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},Re=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 k(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;#t;#n;#r;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[],this.#r=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}addHandlerResponseHook(e){this.#r.push(e)}onResponseSendingFinal=i(async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)},"onResponseSendingFinal");onResponseSending=i(async(e,t,r)=>{let o=e;for(let s of this.#n)o=await s(e,t,r);return o},"onResponseSending");onHandlerResponse=i(async(e,t,r)=>{for(let o of this.#r)await o(e,t,r)},"onHandlerResponse")},Gn=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:s,incomingRequestProperties:a,parentContext:u}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=s,this.incomingRequestProperties=a,this.parentContext=u,this.#e=o,this.invokeInboundPolicy=(c,l)=>Ta(c,l,this),this.contextId=crypto.randomUUID(),this.invokeOutboundPolicy=(c,l,d)=>va(c,l,d,this),this.invokeRoute=async(c,l)=>{let d=new ee(c,l);return ge.instance.handleRequest(d,this,{parentContext:this})},this.waitUntil=c=>{this.#e.waitUntil(c)},this.addResponseSendingHook=c=>{Re.getContextExtensions(this).addResponseSendingHook(c)},this.addResponseSendingFinalHook=c=>{Re.getContextExtensions(this).addResponseSendingFinalHook(c)},Object.freeze(this)}#e;contextId;requestId;log;route;custom;incomingRequestProperties;parentContext;invokeInboundPolicy;invokeOutboundPolicy;invokeRoute;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 gl="Error initializing gateway. Check your configuration for errors or contact support.",fl="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",wo=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=i(async(e,t,r)=>{y.initialize({build:this.buildEnvironment,runtime:t});try{await Fs(this.runtimeInit)}catch(s){this.handleError(s,fl,e)}return Ms(i(async(s,a)=>{let u;try{u=await ge.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(l){return this.handleError(l,gl,s)}let c={context:void 0};return zn.context.run(c,async()=>u.handleRequest(s,a))},"innerHandler"))(e,r)},"requestHandler");handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof g&&(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:y.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};function hl(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(hl,"lexer");function Po(n,e){e===void 0&&(e={});for(var t=hl(n),r=e.prefixes,o=r===void 0?"./":r,s=e.delimiter,a=s===void 0?"/#?":s,u=[],c=0,l=0,d="",p=i(function(j){if(l<t.length&&t[l].type===j)return t[l++].value},"tryConsume"),m=i(function(j){var v=p(j);if(v!==void 0)return v;var x=t[l],q=x.type,ce=x.index;throw new TypeError("Unexpected ".concat(q," at ").concat(ce,", expected ").concat(j))},"mustConsume"),h=i(function(){for(var j="",v;v=p("CHAR")||p("ESCAPED_CHAR");)j+=v;return j},"consumeText"),I=i(function(j){for(var v=0,x=a;v<x.length;v++){var q=x[v];if(j.indexOf(q)>-1)return!0}return!1},"isSafe"),b=i(function(j){var v=u[u.length-1],x=j||(v&&typeof v=="string"?v:"");if(v&&!x)throw new TypeError('Must have text between two parameters, missing text after "'.concat(v.name,'"'));return!x||I(x)?"[^".concat(Ro(a),"]+?"):"(?:(?!".concat(Ro(x),")[^").concat(Ro(a),"])+?")},"safePattern");l<t.length;){var E=p("CHAR"),L=p("NAME"),O=p("PATTERN");if(L||O){var Z=E||"";o.indexOf(Z)===-1&&(d+=Z,Z=""),d&&(u.push(d),d=""),u.push({name:L||c++,prefix:Z,suffix:"",pattern:O||b(Z),modifier:p("MODIFIER")||""});continue}var M=E||p("ESCAPED_CHAR");if(M){d+=M;continue}d&&(u.push(d),d="");var F=p("OPEN");if(F){var Z=h(),S=p("NAME")||"",H=p("PATTERN")||"",V=h();m("CLOSE"),u.push({name:S||(H?c++:""),pattern:S&&!H?b(Z):H,prefix:Z,suffix:V,modifier:p("MODIFIER")||""});continue}m("END")}return u}i(Po,"parse");function Sa(n,e){return yl(Po(n,e),e)}i(Sa,"compile");function yl(n,e){e===void 0&&(e={});var t=bl(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 m=c?c[p.name]:void 0,h=p.modifier==="?"||p.modifier==="*",I=p.modifier==="*"||p.modifier==="+";if(Array.isArray(m)){if(!I)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(m.length===0){if(h)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var b=0;b<m.length;b++){var E=o(m[b],p);if(a&&!u[d].test(E))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(E,'"'));l+=p.prefix+E+p.suffix}continue}if(typeof m=="string"||typeof m=="number"){var E=o(String(m),p);if(a&&!u[d].test(E))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(E,'"'));l+=p.prefix+E+p.suffix;continue}if(!h){var L=I?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(L))}}return l}}i(yl,"tokensToFunction");function Ro(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(Ro,"escapeString");function bl(n){return n&&n.sensitive?"":"i"}i(bl,"flags");var wl=be("zuplo:runtime"),Eo=new TextEncoder,Oa={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"},Rl=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],wt=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 xo(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){wl("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,t),a=$.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 g("An unknown error occurred, ensure retries is not negative")}},xo=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:m,appendSessionToken:h,allHeaders:I,singleEncode:b}){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 E,L;(!c||!l)&&([E,L]=Pl(this.url,this.headers)),this.service=c||E||"",this.region=l||L||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=h||this.service==="iotdevicegateway",this.headers.delete("Host");let O=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"),O.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&O.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(M=>I||!Rl.includes(M)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(M=>M+":"+(M==="host"?this.url.host:(this.headers.get(M)||"").replace(/\s+/g," "))).join(`
66
+ `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!O.has("X-Amz-Expires")&&O.set("X-Amz-Expires","86400"),O.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),O.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),O.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,"/");b||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=ka(this.encodedPath);let Z=new Set;this.encodedSearch=[...this.url.searchParams].filter(([M])=>{if(!M)return!1;if(this.service==="s3"){if(Z.has(M))return!1;Z.add(M)}return!0}).map(M=>M.map(F=>ka(encodeURIComponent(F)))).sort(([M,F],[S,H])=>M<S?-1:M>S?1:F<H?-1:F>H?1:0).map(M=>M.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 rn("AWS4"+this.secretAccessKey,e),s=await rn(o,this.region),a=await rn(s,this.service);r=await rn(a,"aws4_request"),this.cache.set(t,r)}return Io(await rn(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Io(await Aa(await this.canonicalString()))].join(`
67
67
  `)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
68
68
  `,this.signedHeaders,await this.hexBodyHash()].join(`
69
- `)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new k("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Io(await Sa(this.body||""))}return e}};async function rn(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?Eo.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,Eo.encode(e))}i(rn,"hmac");async function Sa(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?Eo.encode(n):n)}i(Sa,"hash");function Io(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}i(Io,"buf2hex");function Oa(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(Oa,"encodeRfc3986");function wl(n,e){let{hostname:t,pathname:r}=n,o=t.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[s,a]=(o||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",s="s3";else if(s==="iot")t.startsWith("iot.")?s="execute-api":t.startsWith("data.jobs.iot.")?s="iot-jobs-data":s=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(s==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?s="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(s="autoscaling-plans")}else a==null&&s.startsWith("s3-")?(a=s.slice(3).replace(/^fips-|^external-1/,""),s="s3"):s.endsWith("-fips")?s=s.slice(0,-5):a&&/-\d$/.test(s)&&!/-\d$/.test(a)&&([s,a]=[a,s]);return s in Ca?[Ca[s],a]:[s,a]}i(wl,"guessServiceRegion");function Rl(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(Rl,"b64ToUint6");function Aa(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|=Rl(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(Aa,"base64Decode");function Vn(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}i(Vn,"uint6ToB64");function ka(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(Vn(o>>>18&63),Vn(o>>>12&63),Vn(o>>>6&63),Vn(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}i(ka,"base64Encode");function Rt(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}i(Rt,"numberToString");function Pl(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=Rt(Math.floor(t/60)),s=Rt(t%60);return`${r}${o}${s}`}i(Pl,"getCLFOffset");function To(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=Rt(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),s=Rt(n.getHours()),a=Rt(n.getMinutes()),u=Rt(n.getSeconds()),c=Pl(n);return`${t}/${r}/${o}:${s}:${a}:${u} ${c}`}i(To,"toCLFDate");var La=be("zuplo:runtime"),Il="X-Amzn-Trace-Id",El="x-amzn-errortype",_a=[],xl=i(async(n,e,t)=>{let r=t;for await(let o of _a)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),Ce=class extends k{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(Il)??void 0,this.errorType=t.get(El)??void 0}},Tl={addSendingAwsLambdaEventHook:i(n=>{_a.push(n)},"addSendingAwsLambdaEventHook")};async function vl(n,e){f("handler.aws-lambda");let{accessKeyId:t,secretAccessKey:r,region:o,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!t)throw new g("awsAccessKeyId is not set in the handler options");if(!r)throw new g("secretAccessKey is not set in the handler options");if(!o)throw new g("region is not set in the handler options");if(!s)throw new g("functionName is not set in the handler options");let l=new wt({accessKeyId:t,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(La(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,m]=await Al(n,{binaryMediaTypes:c}),{options:h}=e.route.handler,I;h&&typeof h=="object"&&"payloadFormatVersion"in h&&h.payloadFormatVersion==="2.0"?I=Ol(n,e):I=await Sl(n,e,{useAwsResourcePathStyle:u}),La("Calling onSendingAwsLambdaEvent hook");let b=await xl(n,e,I);b.body=p,b.isBase64Encoded=m;let E=await l.fetch(d,{body:JSON.stringify(b)});try{return Cl(E)}catch(L){if(L instanceof Ce){let O=h&&typeof h=="object"&&"returnAmazonTraceIdHeader"in h&&h.returnAmazonTraceIdHeader&&L.traceId?{AMZN_TRACE_ID_HEADER:L.traceId}:void 0;return T.internalServerError(n,e,void 0,O)}throw L}}i(vl,"awsLambdaHandler");async function Cl(n){let e;try{e=await n.json()}catch{throw new Ce("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 Ce(e.message,n.headers):new Ce(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new Ce(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 Ce(`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 Ce(`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 Ce(`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 Ce("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new Ce("Response was set to base64 encoded but body was not a string",n.headers);r=Aa(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 Ce(`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(Cl,"getResponse");async function Sl(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]||(a[l]=[]),a[l].push(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:To(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Ll(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}i(Sl,"buildEventVersion1");function Ol(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:To(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}i(Ol,"buildEventVersion2");async function Al(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&&kl(e,o)){let s=await n.arrayBuffer();t=ka(new Uint8Array(s)),r=!0}else t=await n.clone().text();return[t,r]}i(Al,"getBodyResult");function kl(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}i(kl,"matchesContentType");function Ll(n,e=!1){if(!e)return n;let t=Po(n),r=va(n),o={};return t.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),r(o)}i(Ll,"getResourcePath");var _l=[502,503,504];async function Pt(n,e){if(_l.includes(n.status)){let t=J.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(Pt,"logBadGatewayResponses");var vo;function et(n){if(vo===void 0){let t=y.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),vo=t}return n.log[vo]}i(et,"getHandlerUserLogFunction");async function Nl(n,e){f("handler.open-api");let t=y.instance.build.BUILD_ID,{buildAssetsUrl:r}=y.instance,o=e.route.handler.options,{openApiFilePath:s}=o;if(!s)throw new g("Open API Spec Handler must have 'openApiFilePath' specified");let a=Dl(s);if(!a.isValid)throw new g(a.error);let u=`${r}/${t}${s.substring(1)}`,c=await $.fetch(u,{method:n.method,body:n.body,headers:n.headers});if(c.status!==200)return T.notFound(n,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json","content-encoding":c.headers.get("content-encoding")||"",vary:"Accept-Encoding"},status:c.status,statusText:c.statusText});return Pt(l,e),l}i(Nl,"openApiSpecHandler");var Dl=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 Ml(n,e){f("handler.redirect");let t=e.route.handler.options;if(!t.location)throw new g("Redirect Handler must have 'location' specified");let r=t.status??302;return new Response(null,{status:r,headers:{location:t.location}})}i(Ml,"redirectHandler");async function ql(n){if(f("handler.zuplo-service-proxy"),Object.entries(n.params).length!==1)throw new g("The service proxy handler only supports one wildcard path parameter. Change your url to something like '/service/{path}'");let e=new URL(n.params.path,y.instance.zuploEdgeApiUrl),t=new Headers(n.headers);return t.set("Authorization",`Bearer ${y.instance.authApiJWT}`),$.fetch(e,{method:n.method,headers:t,body:n.body})}i(ql,"zuploServiceProxy");function Ul(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(Ul,"join");async function Hl(n,e){f("handler.url-forward");let t=et(e),r=e.route.handler.options,o=r.forwardSearch!==!1,s;if(y.instance.build.COMPATIBILITY_FLAGS.useForwardRedirectsPropOnUrlForwardHandler?s=r.followRedirects===!0?"follow":"manual":typeof r.followRedirects<"u"&&f("handler.url-forward.follow-redirects"),!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new g("Invalid options for this route");let a=Xe(e),u=new URL(n.url),c=r.__rewriteFunction(n,a),l=Ul(c,u.pathname),d=o?`${l}${u.search}`:l.toString(),p=Date.now();t(`URL Forwarding to '${d}'`);let m=await fetch(d,{method:n.method,body:n.body,headers:n.headers,redirect:s}),h=Date.now()-p;return t(`URL Forward received response ${m.status} - ${m.statusText} in ${h}ms`),Pt(m,e),m}i(Hl,"urlForwardHandler");var $l=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 Zl(n,e){f("handler.url-rewrite");let t=et(e),r=e.route.handler.options,o=r.forwardSearch!==!1,s=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new g("Invalid options for this route");let a=Xe(e),u=r.__rewriteFunction(n,a),c=o?$l(u,n.url):u,l=Date.now();t(`URL Rewriting to '${c}'`);let d=await fetch(c.toString(),{method:n.method,body:n.body,headers:n.headers,redirect:s?"follow":"manual"}),p=Date.now()-l;return t(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),Pt(d,e),d}i(Zl,"urlRewriteHandler");async function Fl(n,e){f("handler.websocket");let t=e.route.handler.options,r=et(e);if(!t||!t.rewritePattern)throw new g("WebSocket Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return T.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new g("Invalid options for this route");let s=Xe(e),a=t.__rewriteFunction(n,s),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let d=await c.text(),p=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${d}'`;throw new Error(p)}let l=Date.now()-u;return r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${l}ms`),new Response(null,{status:101,webSocket:c.webSocket})}i(Fl,"webSocketHandler");var Co=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 g(`${a} - Websocket policy must be a valid function (${u})`)}return s}),"getWebSocketPolicyFunctions"),Na=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 Da(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 Na(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(Da,"wireUpListeners");async function jl(n,e){f("handler.websocket-pipeline");let t=e.route.handler.options,r=et(e);if(!t||!t.rewritePattern)throw new g("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return T.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new g("Invalid options for this route");let s=Xe(e),a=t.__rewriteFunction(n,s),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let E=await c.text(),L=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${E}'`;throw new Error(L)}let l=new WebSocketPair,[d,p]=Object.values(l),m=Date.now()-u;r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${m}ms`);let h=c.webSocket;h.accept(),p.accept();let I=t.policies&&t.policies.inbound?Co(t.policies.inbound,"inbound"):[],b=t.policies&&t.policies.outbound?Co(t.policies.outbound,"outbound"):[];return Da(p,h,n,e,I),Da(h,p,n,e,b),new Response(null,{status:101,webSocket:d})}i(jl,"webSocketPipelineHandler");var So=class extends le{constructor(t){super();this.options=t}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new Oo(this.options)}},Oo=class{static{i(this,"DynaTraceTransport")}constructor(e){f("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName,this.#i=e.fields??{}}#e;#t;#n;#r;#o;#i;log(e,t){e.messages.forEach(r=>{let o=Object.assign({timestamp:new Date().toISOString(),message:ve(r),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.atomicCounter":e.vectorClock,"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.#i);this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#s=i(async e=>{if(e.length!==0)try{let t=await $.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}});t.ok||await Q({level:"error",messages:[`Failed to send logs to Dynatrace: ${t.status} - ${t.statusText}`]},t)}catch{await Q({level:"error",messages:["Failed to connect to Dynatrace logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new K("dyna-trace-log-transport",10,this.#s)};var Ao=class extends le{constructor(t){super();this.options=t}static{i(this,"NewRelicLoggingPlugin")}getTransport(){return new ko(this.options)}},ko=class{static{i(this,"NewRelicTransport")}constructor(e){f("logging.newrelic"),this.#e=e.url??"https://log-api.newrelic.com/log/v1",this.#t=e.apiKey,this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName,this.#i=e.fields??{},this.#s=e.service??"Zuplo"}#e;#t;#n;#r;#o;#i;#s;log(e,t){e.messages.forEach(r=>{let o=Object.assign({message:ve(r),level:e.level,timestamp:Date.now(),service:this.#s,request_id:e.requestId,atomic_counter:e.vectorClock,environment:this.#n,environment_stage:this.#o,environment_type:this.#r,logging_id:e.loggingId,ray_id:e.rayId===null?void 0:e.rayId,log_source:e.logSource},this.#i);this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=i(async e=>{if(e.length!==0)try{let t=await $.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json","Api-Key":this.#t}});t.ok||await Q({level:"error",messages:[`Failed to send logs to New Relic: ${t.status} - ${t.statusText}`]},t)}catch{await Q({level:"error",messages:["Failed to connect to New Relic logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new K("new-relic-log-transport",10,this.#a)};var Lo=class extends le{constructor(t){super();this.options=t}static{i(this,"LokiLoggingPlugin")}getTransport(){return new No(this.options)}},_o=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=i(e=>this.level===e.level&&this.requestId===e.requestId,"equals")};function zl(n,e){return btoa(`${n}:${e}`)}i(zl,"createBasicDigest");var No=class{static{i(this,"LokiTransport")}constructor(e){f("logging.loki"),this.#n=e.url,this.#r=zl(e.username,e.password),this.#i=y.instance.loggingEnvironmentType,this.#s=y.instance.loggingEnvironmentStage,this.#o=y.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo",this.#a=e.fields??{}}#e;#t;#n;#r;#o;#i;#s;#a;log(e,t){let r=new _o(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(o=>{let s=Object.assign({stream:r,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:ve(o),nanoSecondEpoch:`${e.timestamp.getTime()}000000`},this.#a);this.batcher.enqueue(s)}),t.waitUntil(this.batcher.waitUntilFlushed())}#u=i(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:JSON.stringify(r.atomicCounter)}]:[r.nanoSecondEpoch,r.message])}),t},"#convertToLokiStreamsBatch");#c=i(async e=>{if(e.length===0)return;let t=this.#u(e);try{let r=await $.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}});r.ok||await Q({level:"error",messages:[`Failed to send logs to Loki: ${r.status} - ${r.statusText}`]},r)}catch{await Q({level:"error",messages:["Failed to connect to Loki logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new K("loki-log-transport",10,this.#c)};var Do=class extends le{constructor(t){super();this.options=t}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new Mo(this.options)}},Mo=class{static{i(this,"SumoLogicTransport")}constructor(e){f("logging.sumologic"),this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=y.instance.loggingEnvironmentType,this.#r=y.instance.loggingEnvironmentStage,this.#t=y.instance.deploymentName,this.#s=e.fields??{}}#e;#t;#n;#r;#o;#i;#s;log(e,t){e.messages.forEach(r=>{let o=Object.assign({timestamp:new Date().toISOString(),message:ve(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.#s);this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=i(async e=>{if(e.length===0)return;let t=e.map(o=>JSON.stringify(o)).join(`
70
- `),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);try{let o=await $.fetch(this.#e,{method:"POST",body:t,headers:r});o.ok||await Q({level:"error",messages:[`Failed to send logs to Sumologic: ${o.status} - ${o.statusText}`]},o)}catch{await Q({level:"error",messages:["Failed to connect to Sumologic logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new K("sumo-logic-log-transport",10,this.#a)};var Bl="d3a5b78f823648f5b1df4fe269d41172",qo=class extends le{constructor(t){super();this.options=t}static{i(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new Uo(this.options)}},Uo=class{static{i(this,"VMWareLogInsightTransport")}constructor(e){f("logging.vmware-loginsight");let t;try{t=new URL(e.url),t.pathname==="/"&&(t.pathname=`/api/v1/events/ingest/${e.agentId??Bl}`)}catch{throw new g(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=t.toString(),this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.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=da(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=ao(a);u&&o.fields.push({name:s,content:u})}),this.#i&&(o=this.#i(o)),o}#a=i(async e=>{if(e.length!==0)try{let t=await $.fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});t.ok||await Q({level:"error",messages:[`Failed to send logs to Log Insight: ${t.status} - ${t.statusText}`]},t)}catch{await Q({level:"error",messages:["Failed to connect to Log Insight logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new K("vmware-log-insights-log-transport",10,this.#a)};var Ho=class extends le{constructor(t){super();this.options=t}static{i(this,"AWSLoggingPlugin")}getTransport(){return new $o(this.options)}},$o=class{static{i(this,"AWSLogTransport")}awsClient;environment;environmentType;environmentStage;logGroupName;logStreamName;region;fields;batcher=new K("aws-log-transport",10,async e=>{if(e.length===0)return;let t=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});try{let r=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}});r.ok||await Q({level:"error",messages:[`Failed to send logs to AWS: ${r.status} - ${r.statusText}`]},r)}catch{await Q({level:"error",messages:["Failed to connect to AWS logging service. Check that the URL is correct."]})}});constructor({accessKeyId:e,logStreamName:t,logGroupName:r,secretAccessKey:o,region:s,fields:a}){f("logging.aws"),this.awsClient=new wt({accessKeyId:e,secretAccessKey:o,service:"logs",region:s}),this.logGroupName=r,this.logStreamName=t,this.region=s,this.environmentType=y.instance.loggingEnvironmentType,this.environmentStage=y.instance.loggingEnvironmentStage,this.environment=y.instance.deploymentName,this.fields=a??{}}log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify(Object.assign({data:ve(r),severity:e.level,source:e.logSource,environment:this.environment,atomicCounter:e.vectorClock,requestId:e.requestId,environmentType:this.environmentType,environmentStage:this.environmentStage,rayId:e.rayId===null?void 0:e.rayId},this.fields))};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}};var Zo=class extends le{constructor(t){super();this.options=t}static{i(this,"SplunkLoggingPlugin")}getTransport(){return new Fo(this.options)}},Fo=class{static{i(this,"SplunkTransport")}constructor(e){f("logging.splunk"),this.#e=e.url,this.#t=e.token,this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName,this.#i=e.fields??{},this.#s=e.index??"main",this.#a=e.sourcetype??"json",this.#u=e.host??"zuplo-api",this.#c=e.channel}#e;#t;#n;#r;#o;#i;#s;#a;#u;#c;log(e,t){e.messages.forEach(r=>{let s={event:{message:ve(r),level:e.level,timestamp:new Date().toISOString(),request_id:e.requestId,atomic_counter:e.vectorClock,environment:this.#n,environment_stage:this.#o,environment_type:this.#r,logging_id:e.loggingId,ray_id:e.rayId===null?void 0:e.rayId,log_source:e.logSource,...this.#i},sourcetype:this.#a,host:this.#u,index:this.#s,time:Math.floor(Date.now()/1e3)};this.batcher.enqueue(s)}),t.waitUntil(this.batcher.waitUntilFlushed())}#l=i(async e=>{if(e.length!==0)try{for(let t of e){let r={"Content-Type":"application/json",Authorization:`Splunk ${this.#t}`};this.#c&&(r["X-Splunk-Request-Channel"]=this.#c);let o=await $.fetch(this.#e,{method:"POST",body:JSON.stringify(t),headers:r});if(!o.ok){let s=await o.text();await Q({level:"error",messages:[`Failed to send logs to Splunk: ${o.status} - ${o.statusText}`,`Response: ${s}`]},o)}}}catch(t){await Q({level:"error",messages:["Failed to connect to Splunk logging service. Check that the URL is correct.",`Error: ${t instanceof Error?t.message:String(t)}`]})}},"#dispatchFunction");batcher=new K("splunk-log-transport",10,this.#l)};var jo=new WeakMap,Gl={tags:[]},zo=class extends qe{constructor(t){super();this.options=t;f("metrics.datadog")}static{i(this,"DataDogMetricsPlugin")}getTransport(){return new Bo(this.options)}static setContext(t,r){let o=jo.get(t);o||(o=Gl);let s=Object.assign({...o},r);jo.set(t,s)}},Bo=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 K("data-dog-metrics-transport",10,this.dispatchFunction,J.getLogger(t)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(jo.get(t)?.tags??[]);if(this.#o.country&&o.push(`country:${e.country}`),this.#o.httpMethod&&o.push(`httpMethod:${e.method}`),this.#o.statusCode&&o.push(`statusCode:${e.statusCode}`),this.#o.path){let s=e.systemRouteName||e.routePath;o.push(`path:${s}`)}this.#n.latency&&this.#i.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:r,value:e.durationMs}],tags:o}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:r,value:e.requestContentLength}],tags:o}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:r,value:e.responseContentLength}],tags:o}),t.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let t=JSON.stringify({series:e}),r=await $.fetch(this.#t,{method:"POST",body:t,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});r.ok||await Q({level:"error",messages:["Failed to send metrics to DataDog."]},r)}catch{await Q({level:"error",messages:["Failed to connect to DataDog metrics service. Check that the URL is correct."]})}},"dispatchFunction")};var Go=new WeakMap,Vl={dimensions:[]},Vo=class extends qe{constructor(t){super();this.options=t;f("metrics.dynatrace")}static{i(this,"DynatraceMetricsPlugin")}getTransport(){return new Wo(this.options)}static setContext(t,r){let o=Go.get(t);o||(o=Vl);let s=Object.assign({...o},r);Go.set(t,s)}},Wo=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 K("dynatrace-metrics-transport",10,this.dispatchFunction,J.getLogger(t)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(Go.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=i(async e=>{if(e.length!==0)try{let t=e.join(`
71
- `),r=await $.fetch(this.#e,{method:"POST",body:t,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});r.ok||await Q({level:"error",messages:["Failed to send metrics to Dynatrace."]},r)}catch{await Q({level:"error",messages:["Failed to connect to Dynatrace metrics service. Check that the URL is correct."]})}},"dispatchFunction")};var Jo=new WeakMap,Wl={attributes:{}},Ko=class extends qe{constructor(t){super();this.options=t;f("metrics.newrelic")}static{i(this,"NewRelicMetricsPlugin")}getTransport(){return new Qo(this.options)}static setContext(t,r){let o=Jo.get(t);o||(o=Wl);let s=Object.assign({...o},r);Jo.set(t,s)}},Qo=class{static{i(this,"NewRelicMetricsTransport")}#e;#t;#n;#r;#o;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://metric-api.newrelic.com/metric/v1",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.#r=e.attributes??{service:"zuplo"}}pushMetrics(e,t){this.#i===void 0&&(this.#i=new K("new-relic-metrics-transport",10,this.dispatchFunction,J.getLogger(t)));let r=Math.floor(e.timestamp.getTime()),o={...this.#r,...Jo.get(t)?.attributes};if(this.#o.country&&(o.country=e.country),this.#o.httpMethod&&(o.httpMethod=e.method),this.#o.statusCode&&(o.statusCode=e.statusCode.toString()),this.#o.path){let s=e.systemRouteName||e.routePath;o.path=s}this.#n.latency&&this.#i.enqueue({name:"zuplo.request.latency",type:"gauge",value:e.durationMs,timestamp:r,attributes:o}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({name:"zuplo.request.content_length",type:"gauge",value:e.requestContentLength,timestamp:r,attributes:o}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({name:"zuplo.response.content_length",type:"gauge",value:e.responseContentLength,timestamp:r,attributes:o}),t.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let t=JSON.stringify([{metrics:e}]),r=await $.fetch(this.#t,{method:"POST",body:t,headers:{"Content-Type":"application/json","Api-Key":this.#e}});r.ok||await Q({level:"error",messages:[`Failed to send metrics to New Relic. Status: ${r.status} ${r.statusText}`]},r)}catch{await Q({level:"error",messages:["Failed to connect to New Relic metrics service. Check that the URL is correct."]})}},"dispatchFunction")};var Yo=class{static{i(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e,f("audit-logs.datastax")}#e;writeLogBatch=i(async e=>{await Promise.allSettled(e.map(async t=>{await $.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(t)})}))},"writeLogBatch")};var Xo=class extends fe{static{i(this,"AuditLogPlugin")}constructor(e,t){super(),this.#e=e,this.#t=t,f("audit-logs")}#e;#t;async initialize(e){new ei(e,this.#e,this.#t)}},Ma=i(n=>{let e={};return n.forEach((t,r)=>{e[r]=t}),e},"serializableHeaders"),Jl={requestFilter:i(async()=>!0,"requestFilter"),include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},ei=class{static{i(this,"AuditPluginImpl")}constructor(e,t,r){this.#t=t;let o={...Jl};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 K("audit-log",10,this.#r)}#e;#t;#n;#r=i(async e=>{await this.#t.writeLogBatch(e)},"#dispatch");#o=i(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?Ma(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?Ma(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)}},"#asyncPrepLogs");#i=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(m=>{t.log.error(m)});t.waitUntil(p)}),e}catch(r){return t.log.error(r),e}},"#auditHook")};var ti={None:0,JsonEscape:1},on=class{constructor(e,t={}){this.stream=e;this.options=t;this.placeholder=`__STREAM_TOKEN_${crypto.randomUUID()}__`}static{i(this,"StreamToken")}placeholder;getRawStream(){return this.stream}getOptions(){return this.options}getSafeToken(){return this.placeholder}async getContent(){if(!this.stream)return this.options.useEmptyStringIfNull?"":null;let e=this.stream.getReader(),t=[];try{for(;;){let{done:u,value:c}=await e.read();if(u)break;t.push(c)}}finally{e.releaseLock()}let r=t.reduce((u,c)=>u+c.length,0),o=new Uint8Array(r),s=0;for(let u of t)o.set(u,s),s+=u.length;let a=new TextDecoder().decode(o);return this.options.base64Encode&&(a=btoa(a)),a}},Wn=class{static{i(this,"StreamBuilder")}template;tokens;flags;constructor(e){this.template=e.template,this.tokens=e.tokens,this.flags=e.flags}escapeJsonString(e){return e.replace(/[\\\"\n\r\t\f\b]/g,t=>{switch(t){case"\\":return"\\\\";case'"':return'\\"';case`
69
+ `)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new k("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Io(await Aa(this.body||""))}return e}};async function rn(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?Eo.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,Eo.encode(e))}i(rn,"hmac");async function Aa(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?Eo.encode(n):n)}i(Aa,"hash");function Io(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}i(Io,"buf2hex");function ka(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(ka,"encodeRfc3986");function Pl(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 Oa?[Oa[s],a]:[s,a]}i(Pl,"guessServiceRegion");function Il(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(Il,"b64ToUint6");function La(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|=Il(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(La,"base64Decode");function Vn(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}i(Vn,"uint6ToB64");function _a(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(Vn(o>>>18&63),Vn(o>>>12&63),Vn(o>>>6&63),Vn(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}i(_a,"base64Encode");function Rt(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}i(Rt,"numberToString");function El(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=Rt(Math.floor(t/60)),s=Rt(t%60);return`${r}${o}${s}`}i(El,"getCLFOffset");function To(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=Rt(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),s=Rt(n.getHours()),a=Rt(n.getMinutes()),u=Rt(n.getSeconds()),c=El(n);return`${t}/${r}/${o}:${s}:${a}:${u} ${c}`}i(To,"toCLFDate");var Na=be("zuplo:runtime"),xl="X-Amzn-Trace-Id",Tl="x-amzn-errortype",Da=[],vl=i(async(n,e,t)=>{let r=t;for await(let o of Da)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),Ce=class extends k{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(xl)??void 0,this.errorType=t.get(Tl)??void 0}},Cl={addSendingAwsLambdaEventHook:i(n=>{Da.push(n)},"addSendingAwsLambdaEventHook")};async function Sl(n,e){f("handler.aws-lambda");let{accessKeyId:t,secretAccessKey:r,region:o,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!t)throw new g("awsAccessKeyId is not set in the handler options");if(!r)throw new g("secretAccessKey is not set in the handler options");if(!o)throw new g("region is not set in the handler options");if(!s)throw new g("functionName is not set in the handler options");let l=new wt({accessKeyId:t,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(Na(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,m]=await Ll(n,{binaryMediaTypes:c}),{options:h}=e.route.handler,I;h&&typeof h=="object"&&"payloadFormatVersion"in h&&h.payloadFormatVersion==="2.0"?I=kl(n,e):I=await Al(n,e,{useAwsResourcePathStyle:u}),Na("Calling onSendingAwsLambdaEvent hook");let b=await vl(n,e,I);b.body=p,b.isBase64Encoded=m;let E=await l.fetch(d,{body:JSON.stringify(b)});try{return Ol(E)}catch(L){if(L instanceof Ce){let O=h&&typeof h=="object"&&"returnAmazonTraceIdHeader"in h&&h.returnAmazonTraceIdHeader&&L.traceId?{AMZN_TRACE_ID_HEADER:L.traceId}:void 0;return T.internalServerError(n,e,void 0,O)}throw L}}i(Sl,"awsLambdaHandler");async function Ol(n){let e;try{e=await n.json()}catch{throw new Ce("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 Ce(e.message,n.headers):new Ce(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new Ce(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 Ce(`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 Ce(`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 Ce(`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 Ce("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new Ce("Response was set to base64 encoded but body was not a string",n.headers);r=La(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 Ce(`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(Ol,"getResponse");async function Al(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]||(a[l]=[]),a[l].push(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:To(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Nl(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}i(Al,"buildEventVersion1");function kl(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:To(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}i(kl,"buildEventVersion2");async function Ll(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&&_l(e,o)){let s=await n.arrayBuffer();t=_a(new Uint8Array(s)),r=!0}else t=await n.clone().text();return[t,r]}i(Ll,"getBodyResult");function _l(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}i(_l,"matchesContentType");function Nl(n,e=!1){if(!e)return n;let t=Po(n),r=Sa(n),o={};return t.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),r(o)}i(Nl,"getResourcePath");var Dl=[502,503,504];async function Pt(n,e){if(Dl.includes(n.status)){let t=J.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(Pt,"logBadGatewayResponses");var vo;function et(n){if(vo===void 0){let t=y.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),vo=t}return n.log[vo]}i(et,"getHandlerUserLogFunction");async function Ml(n,e){f("handler.open-api");let t=y.instance.build.BUILD_ID,{buildAssetsUrl:r}=y.instance,o=e.route.handler.options,{openApiFilePath:s}=o;if(!s)throw new g("Open API Spec Handler must have 'openApiFilePath' specified");let a=ql(s);if(!a.isValid)throw new g(a.error);let u=`${r}/${t}${s.substring(1)}`,c=await $.fetch(u,{method:n.method,body:n.body,headers:n.headers});if(c.status!==200)return T.notFound(n,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json","content-encoding":c.headers.get("content-encoding")||"",vary:"Accept-Encoding"},status:c.status,statusText:c.statusText});return Pt(l,e),l}i(Ml,"openApiSpecHandler");var ql=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 Ul(n,e){f("handler.redirect");let t=e.route.handler.options;if(!t.location)throw new g("Redirect Handler must have 'location' specified");let r=t.status??302;return new Response(null,{status:r,headers:{location:t.location}})}i(Ul,"redirectHandler");async function Hl(n){if(f("handler.zuplo-service-proxy"),Object.entries(n.params).length!==1)throw new g("The service proxy handler only supports one wildcard path parameter. Change your url to something like '/service/{path}'");let e=new URL(n.params.path,y.instance.zuploEdgeApiUrl),t=new Headers(n.headers);return t.set("Authorization",`Bearer ${y.instance.authApiJWT}`),$.fetch(e,{method:n.method,headers:t,body:n.body})}i(Hl,"zuploServiceProxy");function $l(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($l,"join");async function Zl(n,e){f("handler.url-forward");let t=et(e),r=e.route.handler.options,o=r.forwardSearch!==!1,s;if(y.instance.build.COMPATIBILITY_FLAGS.useForwardRedirectsPropOnUrlForwardHandler?s=r.followRedirects===!0?"follow":"manual":typeof r.followRedirects<"u"&&f("handler.url-forward.follow-redirects"),!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new g("Invalid options for this route");let a=Xe(e),u=new URL(n.url),c=r.__rewriteFunction(n,a),l=$l(c,u.pathname),d=o?`${l}${u.search}`:l.toString(),p=Date.now();t(`URL Forwarding to '${d}'`);let m=await fetch(d,{method:n.method,body:n.body,headers:n.headers,redirect:s}),h=Date.now()-p;return t(`URL Forward received response ${m.status} - ${m.statusText} in ${h}ms`),Pt(m,e),m}i(Zl,"urlForwardHandler");var Fl=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 jl(n,e){f("handler.url-rewrite");let t=et(e),r=e.route.handler.options,o=r.forwardSearch!==!1,s=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new g("Invalid options for this route");let a=Xe(e),u=r.__rewriteFunction(n,a),c=o?Fl(u,n.url):u,l=Date.now();t(`URL Rewriting to '${c}'`);let d=await fetch(c.toString(),{method:n.method,body:n.body,headers:n.headers,redirect:s?"follow":"manual"}),p=Date.now()-l;return t(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),Pt(d,e),d}i(jl,"urlRewriteHandler");async function zl(n,e){f("handler.websocket");let t=e.route.handler.options,r=et(e);if(!t||!t.rewritePattern)throw new g("WebSocket Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return T.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new g("Invalid options for this route");let s=Xe(e),a=t.__rewriteFunction(n,s),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let d=await c.text(),p=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${d}'`;throw new Error(p)}let l=Date.now()-u;return r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${l}ms`),new Response(null,{status:101,webSocket:c.webSocket})}i(zl,"webSocketHandler");var Co=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 g(`${a} - Websocket policy must be a valid function (${u})`)}return s}),"getWebSocketPolicyFunctions"),Ma=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 qa(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 Ma(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(qa,"wireUpListeners");async function Bl(n,e){f("handler.websocket-pipeline");let t=e.route.handler.options,r=et(e);if(!t||!t.rewritePattern)throw new g("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return T.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new g("Invalid options for this route");let s=Xe(e),a=t.__rewriteFunction(n,s),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let E=await c.text(),L=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${E}'`;throw new Error(L)}let l=new WebSocketPair,[d,p]=Object.values(l),m=Date.now()-u;r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${m}ms`);let h=c.webSocket;h.accept(),p.accept();let I=t.policies&&t.policies.inbound?Co(t.policies.inbound,"inbound"):[],b=t.policies&&t.policies.outbound?Co(t.policies.outbound,"outbound"):[];return qa(p,h,n,e,I),qa(h,p,n,e,b),new Response(null,{status:101,webSocket:d})}i(Bl,"webSocketPipelineHandler");var So=class extends le{constructor(t){super();this.options=t}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new Oo(this.options)}},Oo=class{static{i(this,"DynaTraceTransport")}constructor(e){f("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName,this.#i=e.fields??{}}#e;#t;#n;#r;#o;#i;log(e,t){e.messages.forEach(r=>{let o=Object.assign({timestamp:new Date().toISOString(),message:ve(r),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.atomicCounter":e.vectorClock,"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.#i);this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#s=i(async e=>{if(e.length!==0)try{let t=await $.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}});t.ok||await Q({level:"error",messages:[`Failed to send logs to Dynatrace: ${t.status} - ${t.statusText}`]},t)}catch{await Q({level:"error",messages:["Failed to connect to Dynatrace logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new K("dyna-trace-log-transport",10,this.#s)};var Ao=class extends le{constructor(t){super();this.options=t}static{i(this,"NewRelicLoggingPlugin")}getTransport(){return new ko(this.options)}},ko=class{static{i(this,"NewRelicTransport")}constructor(e){f("logging.newrelic"),this.#e=e.url??"https://log-api.newrelic.com/log/v1",this.#t=e.apiKey,this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName,this.#i=e.fields??{},this.#s=e.service??"Zuplo"}#e;#t;#n;#r;#o;#i;#s;log(e,t){e.messages.forEach(r=>{let o=Object.assign({message:ve(r),level:e.level,timestamp:Date.now(),service:this.#s,request_id:e.requestId,atomic_counter:e.vectorClock,environment:this.#n,environment_stage:this.#o,environment_type:this.#r,logging_id:e.loggingId,ray_id:e.rayId===null?void 0:e.rayId,log_source:e.logSource},this.#i);this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=i(async e=>{if(e.length!==0)try{let t=await $.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json","Api-Key":this.#t}});t.ok||await Q({level:"error",messages:[`Failed to send logs to New Relic: ${t.status} - ${t.statusText}`]},t)}catch{await Q({level:"error",messages:["Failed to connect to New Relic logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new K("new-relic-log-transport",10,this.#a)};var Lo=class extends le{constructor(t){super();this.options=t}static{i(this,"LokiLoggingPlugin")}getTransport(){return new No(this.options)}},_o=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=i(e=>this.level===e.level&&this.requestId===e.requestId,"equals")};function Gl(n,e){return btoa(`${n}:${e}`)}i(Gl,"createBasicDigest");var No=class{static{i(this,"LokiTransport")}constructor(e){f("logging.loki"),this.#n=e.url,this.#r=Gl(e.username,e.password),this.#i=y.instance.loggingEnvironmentType,this.#s=y.instance.loggingEnvironmentStage,this.#o=y.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo",this.#a=e.fields??{}}#e;#t;#n;#r;#o;#i;#s;#a;log(e,t){let r=new _o(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(o=>{let s=Object.assign({stream:r,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:ve(o),nanoSecondEpoch:`${e.timestamp.getTime()}000000`},this.#a);this.batcher.enqueue(s)}),t.waitUntil(this.batcher.waitUntilFlushed())}#u=i(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:JSON.stringify(r.atomicCounter)}]:[r.nanoSecondEpoch,r.message])}),t},"#convertToLokiStreamsBatch");#c=i(async e=>{if(e.length===0)return;let t=this.#u(e);try{let r=await $.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}});r.ok||await Q({level:"error",messages:[`Failed to send logs to Loki: ${r.status} - ${r.statusText}`]},r)}catch{await Q({level:"error",messages:["Failed to connect to Loki logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new K("loki-log-transport",10,this.#c)};var Do=class extends le{constructor(t){super();this.options=t}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new Mo(this.options)}},Mo=class{static{i(this,"SumoLogicTransport")}constructor(e){f("logging.sumologic"),this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=y.instance.loggingEnvironmentType,this.#r=y.instance.loggingEnvironmentStage,this.#t=y.instance.deploymentName,this.#s=e.fields??{}}#e;#t;#n;#r;#o;#i;#s;log(e,t){e.messages.forEach(r=>{let o=Object.assign({timestamp:new Date().toISOString(),message:ve(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.#s);this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=i(async e=>{if(e.length===0)return;let t=e.map(o=>JSON.stringify(o)).join(`
70
+ `),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);try{let o=await $.fetch(this.#e,{method:"POST",body:t,headers:r});o.ok||await Q({level:"error",messages:[`Failed to send logs to Sumologic: ${o.status} - ${o.statusText}`]},o)}catch{await Q({level:"error",messages:["Failed to connect to Sumologic logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new K("sumo-logic-log-transport",10,this.#a)};var Vl="d3a5b78f823648f5b1df4fe269d41172",qo=class extends le{constructor(t){super();this.options=t}static{i(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new Uo(this.options)}},Uo=class{static{i(this,"VMWareLogInsightTransport")}constructor(e){f("logging.vmware-loginsight");let t;try{t=new URL(e.url),t.pathname==="/"&&(t.pathname=`/api/v1/events/ingest/${e.agentId??Vl}`)}catch{throw new g(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=t.toString(),this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.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=ma(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=ao(a);u&&o.fields.push({name:s,content:u})}),this.#i&&(o=this.#i(o)),o}#a=i(async e=>{if(e.length!==0)try{let t=await $.fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});t.ok||await Q({level:"error",messages:[`Failed to send logs to Log Insight: ${t.status} - ${t.statusText}`]},t)}catch{await Q({level:"error",messages:["Failed to connect to Log Insight logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new K("vmware-log-insights-log-transport",10,this.#a)};var Ho=class extends le{constructor(t){super();this.options=t}static{i(this,"AWSLoggingPlugin")}getTransport(){return new $o(this.options)}},$o=class{static{i(this,"AWSLogTransport")}awsClient;environment;environmentType;environmentStage;logGroupName;logStreamName;region;fields;batcher=new K("aws-log-transport",10,async e=>{if(e.length===0)return;let t=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});try{let r=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}});r.ok||await Q({level:"error",messages:[`Failed to send logs to AWS: ${r.status} - ${r.statusText}`]},r)}catch{await Q({level:"error",messages:["Failed to connect to AWS logging service. Check that the URL is correct."]})}});constructor({accessKeyId:e,logStreamName:t,logGroupName:r,secretAccessKey:o,region:s,fields:a}){f("logging.aws"),this.awsClient=new wt({accessKeyId:e,secretAccessKey:o,service:"logs",region:s}),this.logGroupName=r,this.logStreamName=t,this.region=s,this.environmentType=y.instance.loggingEnvironmentType,this.environmentStage=y.instance.loggingEnvironmentStage,this.environment=y.instance.deploymentName,this.fields=a??{}}log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify(Object.assign({data:ve(r),severity:e.level,source:e.logSource,environment:this.environment,atomicCounter:e.vectorClock,requestId:e.requestId,environmentType:this.environmentType,environmentStage:this.environmentStage,rayId:e.rayId===null?void 0:e.rayId},this.fields))};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}};var Zo=class extends le{constructor(t){super();this.options=t}static{i(this,"SplunkLoggingPlugin")}getTransport(){return new Fo(this.options)}},Fo=class{static{i(this,"SplunkTransport")}constructor(e){f("logging.splunk"),this.#e=e.url,this.#t=e.token,this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName,this.#i=e.fields??{},this.#s=e.index??"main",this.#a=e.sourcetype??"json",this.#u=e.host??"zuplo-api",this.#c=e.channel}#e;#t;#n;#r;#o;#i;#s;#a;#u;#c;log(e,t){e.messages.forEach(r=>{let s={event:{message:ve(r),level:e.level,timestamp:new Date().toISOString(),request_id:e.requestId,atomic_counter:e.vectorClock,environment:this.#n,environment_stage:this.#o,environment_type:this.#r,logging_id:e.loggingId,ray_id:e.rayId===null?void 0:e.rayId,log_source:e.logSource,...this.#i},sourcetype:this.#a,host:this.#u,index:this.#s,time:Math.floor(Date.now()/1e3)};this.batcher.enqueue(s)}),t.waitUntil(this.batcher.waitUntilFlushed())}#l=i(async e=>{if(e.length!==0)try{for(let t of e){let r={"Content-Type":"application/json",Authorization:`Splunk ${this.#t}`};this.#c&&(r["X-Splunk-Request-Channel"]=this.#c);let o=await $.fetch(this.#e,{method:"POST",body:JSON.stringify(t),headers:r});if(!o.ok){let s=await o.text();await Q({level:"error",messages:[`Failed to send logs to Splunk: ${o.status} - ${o.statusText}`,`Response: ${s}`]},o)}}}catch(t){await Q({level:"error",messages:["Failed to connect to Splunk logging service. Check that the URL is correct.",`Error: ${t instanceof Error?t.message:String(t)}`]})}},"#dispatchFunction");batcher=new K("splunk-log-transport",10,this.#l)};var jo=new WeakMap,Wl={tags:[]},zo=class extends qe{constructor(t){super();this.options=t;f("metrics.datadog")}static{i(this,"DataDogMetricsPlugin")}getTransport(){return new Bo(this.options)}static setContext(t,r){let o=jo.get(t);o||(o=Wl);let s=Object.assign({...o},r);jo.set(t,s)}},Bo=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 K("data-dog-metrics-transport",10,this.dispatchFunction,J.getLogger(t)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(jo.get(t)?.tags??[]);if(this.#o.country&&o.push(`country:${e.country}`),this.#o.httpMethod&&o.push(`httpMethod:${e.method}`),this.#o.statusCode&&o.push(`statusCode:${e.statusCode}`),this.#o.path){let s=e.systemRouteName||e.routePath;o.push(`path:${s}`)}this.#n.latency&&this.#i.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:r,value:e.durationMs}],tags:o}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:r,value:e.requestContentLength}],tags:o}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:r,value:e.responseContentLength}],tags:o}),t.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let t=JSON.stringify({series:e}),r=await $.fetch(this.#t,{method:"POST",body:t,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});r.ok||await Q({level:"error",messages:["Failed to send metrics to DataDog."]},r)}catch{await Q({level:"error",messages:["Failed to connect to DataDog metrics service. Check that the URL is correct."]})}},"dispatchFunction")};var Go=new WeakMap,Jl={dimensions:[]},Vo=class extends qe{constructor(t){super();this.options=t;f("metrics.dynatrace")}static{i(this,"DynatraceMetricsPlugin")}getTransport(){return new Wo(this.options)}static setContext(t,r){let o=Go.get(t);o||(o=Jl);let s=Object.assign({...o},r);Go.set(t,s)}},Wo=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 K("dynatrace-metrics-transport",10,this.dispatchFunction,J.getLogger(t)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(Go.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=i(async e=>{if(e.length!==0)try{let t=e.join(`
71
+ `),r=await $.fetch(this.#e,{method:"POST",body:t,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});r.ok||await Q({level:"error",messages:["Failed to send metrics to Dynatrace."]},r)}catch{await Q({level:"error",messages:["Failed to connect to Dynatrace metrics service. Check that the URL is correct."]})}},"dispatchFunction")};var Jo=new WeakMap,Kl={attributes:{}},Ko=class extends qe{constructor(t){super();this.options=t;f("metrics.newrelic")}static{i(this,"NewRelicMetricsPlugin")}getTransport(){return new Qo(this.options)}static setContext(t,r){let o=Jo.get(t);o||(o=Kl);let s=Object.assign({...o},r);Jo.set(t,s)}},Qo=class{static{i(this,"NewRelicMetricsTransport")}#e;#t;#n;#r;#o;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://metric-api.newrelic.com/metric/v1",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.#r=e.attributes??{service:"zuplo"}}pushMetrics(e,t){this.#i===void 0&&(this.#i=new K("new-relic-metrics-transport",10,this.dispatchFunction,J.getLogger(t)));let r=Math.floor(e.timestamp.getTime()),o={...this.#r,...Jo.get(t)?.attributes};if(this.#o.country&&(o.country=e.country),this.#o.httpMethod&&(o.httpMethod=e.method),this.#o.statusCode&&(o.statusCode=e.statusCode.toString()),this.#o.path){let s=e.systemRouteName||e.routePath;o.path=s}this.#n.latency&&this.#i.enqueue({name:"zuplo.request.latency",type:"gauge",value:e.durationMs,timestamp:r,attributes:o}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({name:"zuplo.request.content_length",type:"gauge",value:e.requestContentLength,timestamp:r,attributes:o}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({name:"zuplo.response.content_length",type:"gauge",value:e.responseContentLength,timestamp:r,attributes:o}),t.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let t=JSON.stringify([{metrics:e}]),r=await $.fetch(this.#t,{method:"POST",body:t,headers:{"Content-Type":"application/json","Api-Key":this.#e}});r.ok||await Q({level:"error",messages:[`Failed to send metrics to New Relic. Status: ${r.status} ${r.statusText}`]},r)}catch{await Q({level:"error",messages:["Failed to connect to New Relic metrics service. Check that the URL is correct."]})}},"dispatchFunction")};var Yo=class{static{i(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e,f("audit-logs.datastax")}#e;writeLogBatch=i(async e=>{await Promise.allSettled(e.map(async t=>{await $.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(t)})}))},"writeLogBatch")};var Xo=class extends fe{static{i(this,"AuditLogPlugin")}constructor(e,t){super(),this.#e=e,this.#t=t,f("audit-logs")}#e;#t;async initialize(e){new ei(e,this.#e,this.#t)}},Ua=i(n=>{let e={};return n.forEach((t,r)=>{e[r]=t}),e},"serializableHeaders"),Ql={requestFilter:i(async()=>!0,"requestFilter"),include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},ei=class{static{i(this,"AuditPluginImpl")}constructor(e,t,r){this.#t=t;let o={...Ql};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 K("audit-log",10,this.#r)}#e;#t;#n;#r=i(async e=>{await this.#t.writeLogBatch(e)},"#dispatch");#o=i(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?Ua(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?Ua(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)}},"#asyncPrepLogs");#i=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(m=>{t.log.error(m)});t.waitUntil(p)}),e}catch(r){return t.log.error(r),e}},"#auditHook")};var ti={None:0,JsonEscape:1},on=class{constructor(e,t={}){this.stream=e;this.options=t;this.placeholder=`__STREAM_TOKEN_${crypto.randomUUID()}__`}static{i(this,"StreamToken")}placeholder;getRawStream(){return this.stream}getOptions(){return this.options}getSafeToken(){return this.placeholder}async getContent(){if(!this.stream)return this.options.useEmptyStringIfNull?"":null;let e=this.stream.getReader(),t=[];try{for(;;){let{done:u,value:c}=await e.read();if(u)break;t.push(c)}}finally{e.releaseLock()}let r=t.reduce((u,c)=>u+c.length,0),o=new Uint8Array(r),s=0;for(let u of t)o.set(u,s),s+=u.length;let a=new TextDecoder().decode(o);return this.options.base64Encode&&(a=btoa(a)),a}},Wn=class{static{i(this,"StreamBuilder")}template;tokens;flags;constructor(e){this.template=e.template,this.tokens=e.tokens,this.flags=e.flags}escapeJsonString(e){return e.replace(/[\\\"\n\r\t\f\b]/g,t=>{switch(t){case"\\":return"\\\\";case'"':return'\\"';case`
72
72
  `:return"\\n";case"\r":return"\\r";case" ":return"\\t";case"\f":return"\\f";case"\b":return"\\b";default:return t}})}async toString(){let t=this.getStream().getReader(),r=new TextDecoder,o="";for(;;){let{done:s,value:a}=await t.read();if(s)break;o+=r.decode(a,{stream:!0})}return o+=r.decode(),o}getStream(){let e=this.template,t=this.flags,r=new TextEncoder,o=new Map;for(let m of this.tokens)o.set(m.getSafeToken(),m);let s=/"(__STREAM_TOKEN_[^"]+__)"|(__STREAM_TOKEN_[^"]+__)/g,a=[],u=0,c;for(;(c=s.exec(e))!==null;){if(c.index>u&&a.push({type:"literal",value:e.substring(u,c.index)}),c[1]){let m=o.get(c[1]);m?a.push({type:"token",token:m,isQuoted:!0}):a.push({type:"literal",value:c[0]})}else if(c[2]){let m=o.get(c[2]);m?a.push({type:"token",token:m,isQuoted:!1}):a.push({type:"literal",value:c[0]})}u=s.lastIndex}u<e.length&&a.push({type:"literal",value:e.substring(u)});function l(){let m="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",h=new Uint8Array(0);return new TransformStream({transform(I,b){let E=new Uint8Array(h.length+I.length);E.set(h),E.set(I,h.length);let L=E.length%3,O=E.length-L;if(O>0){let Z=E.subarray(0,O),M="";for(let F=0;F<Z.length;F+=3){let S=Z[F],H=Z[F+1],V=Z[F+2],j=S<<16|H<<8|V;M+=m[j>>18&63],M+=m[j>>12&63],M+=m[j>>6&63],M+=m[j&63]}b.enqueue(M)}h=E.subarray(E.length-L)},flush(I){if(h.length>0){let b=h[0],E=h.length>1?h[1]:0,L=b<<16|E<<8,O="";O+=m[L>>18&63],O+=m[L>>12&63],O+=h.length===2?m[L>>6&63]:"=",O+="=",I.enqueue(O)}}})}i(l,"createBase64EncodeTransformStream");function d(){return new TransformStream({transform(m,h){let I=m.replace(/[\\\"\n\r\t\f\b]/g,b=>{switch(b){case"\\":return"\\\\";case'"':return'\\"';case`
73
- `:return"\\n";case"\r":return"\\r";case" ":return"\\t";case"\f":return"\\f";case"\b":return"\\b";default:return b}});h.enqueue(I)}})}i(d,"createJsonEscapeTransformStream");async function*p(){for(let m of a)if(m.type==="literal")yield r.encode(m.value);else{let h=m.token,I=h.getRawStream();if(!I){m.isQuoted?yield r.encode(h.getOptions().useEmptyStringIfNull?'""':"null"):yield r.encode(h.getOptions().useEmptyStringIfNull?"":"null");continue}let b;h.getOptions().base64Encode?b=I.pipeThrough(l()):b=I.pipeThrough(new TextDecoderStream),!h.getOptions().base64Encode&&t&ti.JsonEscape&&(b=b.pipeThrough(d())),m.isQuoted&&(yield r.encode('"'));let E="";try{let L=b.getReader(),O=await L.read();if(O.done)throw new Error("Token stream already exhausted.");for(E+=O.value;;){let{done:Z,value:M}=await L.read();if(Z)break;E+=M}}catch(L){E=`Error: reading stream failed - ${L instanceof Error?L.message:String(L)}`}yield r.encode(E),m.isQuoted&&(yield r.encode('"'))}}return i(p,"generateChunks"),new ReadableStream({async start(m){for await(let h of p())m.enqueue(h);m.close()}})}};function qa(n){try{let e=n.split(".")[1],t=Buffer.from(e,"base64").toString("utf8");return JSON.parse(t)}catch{return null}}i(qa,"decodeJWT");function Ua(n,e,t){if(n.IP&&t&&n.IP[t])return{blocked:!0,id:n.IP[t],source:`IP/${t}`};if(n.Header)for(let[r,o]of Object.entries(n.Header)){let s=e.headers.get(r);if(s){if(o.RAW&&o.RAW[s])return{blocked:!0,id:o.RAW[s],source:`Header/${r}/RAW/${s}`};if(o.JWT){let a=s;if(r.toLowerCase()==="authorization"){let c=s.split(" ");c.length===2&&c[0].toLowerCase()==="bearer"&&(a=c[1])}let u=qa(a);if(u){for(let[c,l]of Object.entries(o.JWT))if(u[c]&&l[u[c]])return{blocked:!0,id:l[u[c]],source:`Header/${r}/JWT/${c}/${u[c]}`}}}if(r.toLowerCase()==="cookie"&&o.COOKIE){let a=s.split(";").reduce((u,c)=>{let[l,d]=c.trim().split("=");return u[l]=d,u},{});for(let[u,c]of Object.entries(o.COOKIE))if(a[u]&&c[a[u]])return{blocked:!0,id:c[a[u]],source:`Header/Cookie/${u}/${a[u]}`}}}}if(n.Query){let r=new URL(e.url);for(let[o,s]of Object.entries(n.Query)){let a=r.searchParams.get(o);if(a){if(s.RAW&&s.RAW[a])return{blocked:!0,id:s.RAW[a],source:`Query/${o}/RAW/${a}`};if(s.JWT){let u=qa(a);if(u){for(let[c,l]of Object.entries(s.JWT))if(u[c]&&l[u[c]])return{blocked:!0,id:l[u[c]],source:`Query/${o}/JWT/${c}/${u[c]}`}}}}}}return{blocked:!1}}i(Ua,"checkRequest");var Kl=1048576,Ql=1e3;function Ha(n,e){if(!n.body||n.body===null)return!1;let t=n.headers.get("content-length");return!(Number(t)>Kl||(n.headers.get("content-type")??"").includes("stream")||e!=null&&e===101)}i(Ha,"shouldGatherBody");var Yl="unused",ni={type:63,version:"3.0.1"},ri,Xl="plugin.akamai-api-security-plugin",oi=class extends fe{static{i(this,"AkamaiApiSecurityPlugin")}constructor(e){super(),this.#r=e,this.#n=nd(e.hostname),f(Xl)}async initialize(e){e.addRequestHook(async(t,r)=>{if(ri=r,this.#r.enableProtection===!0)try{let a=await this.#t.get(Yl);this.#r.debug&&r.log.debug("AkamaiApiSecurityPlugin: Loaded ProtectionResponse",a);let u=Ua(a,t);if(u.blocked===!0)return r.log.debug(`AkamaiApiSecurityPlugin: Request Blocked by rule '${u.source}':'${u.id}'`),T.forbidden(t,r,{detail:"Access to this resource has been forbidden"})}catch(a){r.log.error(`AkamaiApiSecurityPlugin: Error loading ProtectionResponse '${a.message}'`)}if(this.#r.shouldLog&&!await this.#r.shouldLog(t,r))return t;let o=Date.now(),s=null;return Ha(t)&&(s=t.clone().body),r.addResponseSendingFinalHook(async(a,u,c)=>{let l=null;Ha(a)&&(l=a.clone().body);let d=this.#o(s,l,u,a,c,o);c.waitUntil(d)}),t})}#e=i(async()=>{let e=await fetch(`${this.#n}/integrations-adapter/get-prevention-rules?source-index=${this.#r.index}&source-key=${this.#r.key}&source-type=${ni.type}`);if(e.status!==200)throw new Error(`Unexpected response from protection endpoint ${e.status}: ${await e.text()}`);let t=await e.text();try{return JSON.parse(t)}catch(r){throw new Error(`Error parsing response from protection endpoint '${r}' in '${t}'`)}},"#protectionFetch");#t=new sn(this.#e,{ttlSeconds:60,loaderTimeoutSeconds:60});#n;#r;#o=i(async(e,t,r,o,s,a)=>{let u=new on(e,{base64Encode:!0,useEmptyStringIfNull:!0}),c=new on(t,{base64Encode:!0,useEmptyStringIfNull:!0}),l=await this.#i(o,r,c,u,s,a),p=new Wn({template:JSON.stringify(l),tokens:[u,c],flags:ti.JsonEscape}).getStream(),m=new AbortController,h=setTimeout(()=>m.abort(),Ql);try{let I=await fetch(`${this.#n}/engine?structure=base64-payload`,{method:"POST",headers:{"content-type":"application/json"},body:p,signal:m.signal});this.#r.debug&&ri.log.debug({message:"AkamaiApiSecurityPlugin: Dispatched entry",status:I.status,responseText:await I.text()})}catch(I){this.#r.debug&&ri.log.debug({message:`AkamaiApiSecurityPlugin: Error dispatching entry '${I.message}'`})}finally{clearTimeout(h)}},"#finalizeDispatch");#i=i(async(e,t,r,o,s,a)=>{let u=new URL(t.url),c=t.headers.get("true-client-ip")??"";return{ip:{v:td(c),src:c,dst:"1.1.1.1"},tcp:{src:0,dst:ed(u)},http:{v:s.incomingRequestProperties.httpProtocol?.replace("HTTP/","")||"1.1",request:{ts:a,method:t.method,url:u.pathname+u.search,headers:Object.fromEntries(t.headers.entries()),body:o.getSafeToken()},response:{ts:Date.now(),status:e.status,headers:Object.fromEntries(e.headers.entries()),body:r.getSafeToken()}},source:{type:ni.type,index:this.#r.index,version:ni.version,key:this.#r.key,resource:{type:"ZUPLO",properties:{account:ye.ZUPLO_ACCOUNT_NAME??"",project:ye.ZUPLO_PROJECT_NAME??"",environment:ye.ZUPLO_ENVIRONMENT_NAME??"",route:s.route.path}}}}},"#generateStreamTemplate")};function ed(n){return n.port?parseInt(n.port):n.protocol==="https:"?443:80}i(ed,"guessPort");function td(n){return n.includes("::")||(n.match(/:/g)||[]).length>1?"6":"4"}i(td,"detectIPVersion");function nd(n){let e=n.replace(/\/+$/,"");return e.startsWith("http://")||e.startsWith("https://")?e:`https://${e}`}i(nd,"normalizeHostname");var an=class{static{i(this,"BackgroundDispatcher")}#e;constructor(e,t){if(!t||t.msDelay===void 0)throw new g("BackgroundDispatcher: options.msDelay is required");this.#e=new K(t.name??"",t.msDelay,e)}enqueue=i(e=>{this.#e.enqueue(e),Qe().waitUntil(this.#e.waitUntilFlushed())},"enqueue")};var ii,He=class{static{i(this,"RequestLoggerCore")}constructor(e,t){let o=(e.batchPeriodSeconds??.01)*1e3;this.#n=new an(this.#t,{msDelay:o}),this.#e=e,this.initialize(t)}initialize(e){e.addRequestHook((t,r)=>{ii=r;let o=Date.now();return r.addResponseSendingFinalHook(async s=>{let a={deploymentName:y.instance.deploymentName??"",instanceId:y.instance.instanceId,systemUserAgent:y.instance.systemUserAgent,requestStartTime:new Date(o),durationMs:Date.now()-o},u=await this.#e.generateLogEntry(s,t,r,a);this.#n.enqueue(u)}),t})}#e;#t=i(async e=>{if(e.length!==0)try{await this.#e.dispatchFunction(e)}catch(t){rd(t,this.#e.name)}},"#dispatch");#n};function rd(n,e){if(!ii){let r=Qe(),o=Q({level:"error",messages:[`RequestLoggerCore '${e}': No context available to log user errors`]});r.waitUntil(o);return}let t;n instanceof Error?t={message:n.message,status:-1,details:n.stack??""}:t=n,ii.log.error(`RequestLoggerCore '${e}': Error dispatching log entries.`,t)}i(rd,"logError");var $a="plugin.azure-blob-request-logger",od=i(()=>`${new Date().toISOString().replace(/[:-]/g,"-").replace("T","-").split(".")[0]}-${y.instance.instanceId}.csv`,"defaultGenerateBlobName"),Za,ai=class extends fe{static{i(this,"AzureBlobPlugin")}constructor(e){super(),this.#e=e,f($a)}async initialize(e){new He({name:$a,generateLogEntry:this.#e.generateLogEntry,batchPeriodSeconds:this.#e.batchPeriodSeconds,dispatchFunction:this.#t},e)}#e;#t=i(async e=>{if(e.length===0)return;let t=id(e[0]),r=ad(e,t),s=(this.#e.generateBlobName??od)(e);await ud(r,this.#e,s)},"#dispatch")};function id(n){return Object.keys(n)}i(id,"getHeaders");function sd(n){if(n==null)return"";let e=String(n);return(e.includes('"')||e.includes(",")||e.includes(`
74
- `)||e.includes("\r"))&&(e=e.replace(/"/g,'""'),e=`"${e}"`),e}i(sd,"escapeCsvValue");function ad(n,e){let t=[];t.push(e.join(","));for(let r of n){let o=[];for(let s of e){let a=r[s];o.push(sd(a))}t.push(o.join(","))}return t.join(`
75
- `)}i(ad,"generateCsvContent");async function ud(n,e,t){let{sasUrl:r}=e,o=r.split("?"),s=`${o[0]}/${t}?${o[1]}`;try{let a=await $.fetch(s,{method:"PUT",headers:{"x-ms-blob-type":"BlockBlob","Content-Type":"text/csv"},body:n});a.ok||(si({message:a.statusText,status:a.status,details:await a.text()}),si({message:a.statusText,status:a.status,details:await a.text()}))}catch(a){si(a)}}i(ud,"uploadToAzureBlobStorage");function si(n){if(!Za){let t=Qe(),r=Q({level:"error",messages:["AzureBlobCsvPlugin: No context available to log user errors"]});t.waitUntil(r);return}let e;n instanceof Error?e={message:n.message,status:-1,details:n.stack??""}:e=n,Za.log.error("AzureBlobCsvPlugin: Error uploading to Azure Blob Storage",e)}i(si,"logError");var Fa="plugin.azure-event-hubs-request-logger",cd=60*60,ld=5*60;function ja(){return Math.floor(Date.now()/1e3)}i(ja,"nowEpochSeconds");var ui=class extends fe{static{i(this,"AzureEventHubsRequestLoggerPlugin")}#e;#t;#n=null;constructor(e){super(),this.#e=e,this.#t=this.#r(e.connectionString),f(Fa)}#r(e){let t=e.split(";"),r=new Map;for(let s of t){let[a,...u]=s.split("=");a&&u.length>0&&r.set(a,u.join("="))}return{endpoint:r.get("Endpoint")||"",sharedAccessKeyName:r.get("SharedAccessKeyName")||"",sharedAccessKey:r.get("SharedAccessKey")||"",entityPath:r.get("EntityPath")||""}}async#o(e,t,r){let o=new TextEncoder,s=e.replace(/^https?:\/\//,""),a=encodeURIComponent(s),c=ja()+cd,l=`${a}
76
- ${c}`,d={name:"HMAC",hash:{name:"SHA-256"}},p=await crypto.subtle.importKey("raw",o.encode(r),d,!1,["sign"]),m=await crypto.subtle.sign("HMAC",p,o.encode(l)),h=new Uint8Array(m),I=btoa(String.fromCharCode(...h)),b=encodeURIComponent(I);return{token:`SharedAccessSignature sr=${a}&sig=${b}&se=${c}&skn=${t}`,expiryEpochSeconds:c}}async#i(){let e=ja();if(this.#n&&e<this.#n.expiryEpochSeconds-ld)return this.#n.token;let t=this.#t.entityPath?this.#t.entityPath:(this.#e.eventHubName??"").trim();if(!t)throw new Error("No entity path - either set EntityPath in the connection string or supply eventHubName");let o=`${this.#t.endpoint.replace(/\/$/,"").toLowerCase()}/${t}`,s=await this.#o(o,this.#t.sharedAccessKeyName,this.#t.sharedAccessKey);return this.#n=s,s.token}async initialize(e){new He({name:Fa,generateLogEntry:this.#e.generateLogEntry,batchPeriodSeconds:this.#e.batchPeriodSeconds,dispatchFunction:this.#s},e)}#s=i(async e=>{if(e.length===0)return;let t=this.#t.entityPath?this.#t.entityPath:(this.#e.eventHubName??"").trim(),o=`https://${this.#t.endpoint.replace(/\/$/,"").replace(/^sb:\/\//,"")}/${t}/messages?timeout=60`,s=await this.#i(),a=await fetch(o,{method:"POST",headers:{Authorization:s,"Content-Type":"application/json"},body:JSON.stringify(e)});if(!a.ok)throw new Error(`AzureEventHubsRequestLoggerPlugin: Failed to send logs to ${o}
73
+ `:return"\\n";case"\r":return"\\r";case" ":return"\\t";case"\f":return"\\f";case"\b":return"\\b";default:return b}});h.enqueue(I)}})}i(d,"createJsonEscapeTransformStream");async function*p(){for(let m of a)if(m.type==="literal")yield r.encode(m.value);else{let h=m.token,I=h.getRawStream();if(!I){m.isQuoted?yield r.encode(h.getOptions().useEmptyStringIfNull?'""':"null"):yield r.encode(h.getOptions().useEmptyStringIfNull?"":"null");continue}let b;h.getOptions().base64Encode?b=I.pipeThrough(l()):b=I.pipeThrough(new TextDecoderStream),!h.getOptions().base64Encode&&t&ti.JsonEscape&&(b=b.pipeThrough(d())),m.isQuoted&&(yield r.encode('"'));let E="";try{let L=b.getReader(),O=await L.read();if(O.done)throw new Error("Token stream already exhausted.");for(E+=O.value;;){let{done:Z,value:M}=await L.read();if(Z)break;E+=M}}catch(L){E=`Error: reading stream failed - ${L instanceof Error?L.message:String(L)}`}yield r.encode(E),m.isQuoted&&(yield r.encode('"'))}}return i(p,"generateChunks"),new ReadableStream({async start(m){for await(let h of p())m.enqueue(h);m.close()}})}};function Ha(n){try{let e=n.split(".")[1],t=Buffer.from(e,"base64").toString("utf8");return JSON.parse(t)}catch{return null}}i(Ha,"decodeJWT");function $a(n,e,t){if(n.IP&&t&&n.IP[t])return{blocked:!0,id:n.IP[t],source:`IP/${t}`};if(n.Header)for(let[r,o]of Object.entries(n.Header)){let s=e.headers.get(r);if(s){if(o.RAW&&o.RAW[s])return{blocked:!0,id:o.RAW[s],source:`Header/${r}/RAW/${s}`};if(o.JWT){let a=s;if(r.toLowerCase()==="authorization"){let c=s.split(" ");c.length===2&&c[0].toLowerCase()==="bearer"&&(a=c[1])}let u=Ha(a);if(u){for(let[c,l]of Object.entries(o.JWT))if(u[c]&&l[u[c]])return{blocked:!0,id:l[u[c]],source:`Header/${r}/JWT/${c}/${u[c]}`}}}if(r.toLowerCase()==="cookie"&&o.COOKIE){let a=s.split(";").reduce((u,c)=>{let[l,d]=c.trim().split("=");return u[l]=d,u},{});for(let[u,c]of Object.entries(o.COOKIE))if(a[u]&&c[a[u]])return{blocked:!0,id:c[a[u]],source:`Header/Cookie/${u}/${a[u]}`}}}}if(n.Query){let r=new URL(e.url);for(let[o,s]of Object.entries(n.Query)){let a=r.searchParams.get(o);if(a){if(s.RAW&&s.RAW[a])return{blocked:!0,id:s.RAW[a],source:`Query/${o}/RAW/${a}`};if(s.JWT){let u=Ha(a);if(u){for(let[c,l]of Object.entries(s.JWT))if(u[c]&&l[u[c]])return{blocked:!0,id:l[u[c]],source:`Query/${o}/JWT/${c}/${u[c]}`}}}}}}return{blocked:!1}}i($a,"checkRequest");var Yl=1048576,Xl=1e3;function Za(n,e){if(!n.body||n.body===null)return!1;let t=n.headers.get("content-length");return!(Number(t)>Yl||(n.headers.get("content-type")??"").includes("stream")||e!=null&&e===101)}i(Za,"shouldGatherBody");var ed="unused",ni={type:63,version:"3.0.1"},ri,td="plugin.akamai-api-security-plugin",oi=class extends fe{static{i(this,"AkamaiApiSecurityPlugin")}constructor(e){super(),this.#r=e,this.#n=od(e.hostname),f(td)}async initialize(e){e.addRequestHook(async(t,r)=>{if(ri=r,this.#r.enableProtection===!0)try{let a=await this.#t.get(ed);this.#r.debug&&r.log.debug("AkamaiApiSecurityPlugin: Loaded ProtectionResponse",a);let u=$a(a,t);if(u.blocked===!0)return r.log.debug(`AkamaiApiSecurityPlugin: Request Blocked by rule '${u.source}':'${u.id}'`),T.forbidden(t,r,{detail:"Access to this resource has been forbidden"})}catch(a){r.log.error(`AkamaiApiSecurityPlugin: Error loading ProtectionResponse '${a.message}'`)}if(this.#r.shouldLog&&!await this.#r.shouldLog(t,r))return t;let o=Date.now(),s=null;return Za(t)&&(s=t.clone().body),r.addResponseSendingFinalHook(async(a,u,c)=>{let l=null;Za(a)&&(l=a.clone().body);let d=this.#o(s,l,u,a,c,o);c.waitUntil(d)}),t})}#e=i(async()=>{let e=await fetch(`${this.#n}/integrations-adapter/get-prevention-rules?source-index=${this.#r.index}&source-key=${this.#r.key}&source-type=${ni.type}`);if(e.status!==200)throw new Error(`Unexpected response from protection endpoint ${e.status}: ${await e.text()}`);let t=await e.text();try{return JSON.parse(t)}catch(r){throw new Error(`Error parsing response from protection endpoint '${r}' in '${t}'`)}},"#protectionFetch");#t=new sn(this.#e,{ttlSeconds:60,loaderTimeoutSeconds:60});#n;#r;#o=i(async(e,t,r,o,s,a)=>{let u=new on(e,{base64Encode:!0,useEmptyStringIfNull:!0}),c=new on(t,{base64Encode:!0,useEmptyStringIfNull:!0}),l=await this.#i(o,r,c,u,s,a),p=new Wn({template:JSON.stringify(l),tokens:[u,c],flags:ti.JsonEscape}).getStream(),m=new AbortController,h=setTimeout(()=>m.abort(),Xl);try{let I=await fetch(`${this.#n}/engine?structure=base64-payload`,{method:"POST",headers:{"content-type":"application/json"},body:p,signal:m.signal});this.#r.debug&&ri.log.debug({message:"AkamaiApiSecurityPlugin: Dispatched entry",status:I.status,responseText:await I.text()})}catch(I){this.#r.debug&&ri.log.debug({message:`AkamaiApiSecurityPlugin: Error dispatching entry '${I.message}'`})}finally{clearTimeout(h)}},"#finalizeDispatch");#i=i(async(e,t,r,o,s,a)=>{let u=new URL(t.url),c=t.headers.get("true-client-ip")??"";return{ip:{v:rd(c),src:c,dst:"1.1.1.1"},tcp:{src:0,dst:nd(u)},http:{v:s.incomingRequestProperties.httpProtocol?.replace("HTTP/","")||"1.1",request:{ts:a,method:t.method,url:u.pathname+u.search,headers:Object.fromEntries(t.headers.entries()),body:o.getSafeToken()},response:{ts:Date.now(),status:e.status,headers:Object.fromEntries(e.headers.entries()),body:r.getSafeToken()}},source:{type:ni.type,index:this.#r.index,version:ni.version,key:this.#r.key,resource:{type:"ZUPLO",properties:{account:ye.ZUPLO_ACCOUNT_NAME??"",project:ye.ZUPLO_PROJECT_NAME??"",environment:ye.ZUPLO_ENVIRONMENT_NAME??"",route:s.route.path}}}}},"#generateStreamTemplate")};function nd(n){return n.port?parseInt(n.port):n.protocol==="https:"?443:80}i(nd,"guessPort");function rd(n){return n.includes("::")||(n.match(/:/g)||[]).length>1?"6":"4"}i(rd,"detectIPVersion");function od(n){let e=n.replace(/\/+$/,"");return e.startsWith("http://")||e.startsWith("https://")?e:`https://${e}`}i(od,"normalizeHostname");var an=class{static{i(this,"BackgroundDispatcher")}#e;constructor(e,t){if(!t||t.msDelay===void 0)throw new g("BackgroundDispatcher: options.msDelay is required");this.#e=new K(t.name??"",t.msDelay,e)}enqueue=i(e=>{this.#e.enqueue(e),Qe().waitUntil(this.#e.waitUntilFlushed())},"enqueue")};var ii,He=class{static{i(this,"RequestLoggerCore")}constructor(e,t){let o=(e.batchPeriodSeconds??.01)*1e3;this.#n=new an(this.#t,{msDelay:o}),this.#e=e,this.initialize(t)}initialize(e){e.addRequestHook((t,r)=>{ii=r;let o=Date.now();return r.addResponseSendingFinalHook(async s=>{let a={deploymentName:y.instance.deploymentName??"",instanceId:y.instance.instanceId,systemUserAgent:y.instance.systemUserAgent,requestStartTime:new Date(o),durationMs:Date.now()-o},u=await this.#e.generateLogEntry(s,t,r,a);this.#n.enqueue(u)}),t})}#e;#t=i(async e=>{if(e.length!==0)try{await this.#e.dispatchFunction(e)}catch(t){id(t,this.#e.name)}},"#dispatch");#n};function id(n,e){if(!ii){let r=Qe(),o=Q({level:"error",messages:[`RequestLoggerCore '${e}': No context available to log user errors`]});r.waitUntil(o);return}let t;n instanceof Error?t={message:n.message,status:-1,details:n.stack??""}:t=n,ii.log.error(`RequestLoggerCore '${e}': Error dispatching log entries.`,t)}i(id,"logError");var Fa="plugin.azure-blob-request-logger",sd=i(()=>`${new Date().toISOString().replace(/[:-]/g,"-").replace("T","-").split(".")[0]}-${y.instance.instanceId}.csv`,"defaultGenerateBlobName"),ja,ai=class extends fe{static{i(this,"AzureBlobPlugin")}constructor(e){super(),this.#e=e,f(Fa)}async initialize(e){new He({name:Fa,generateLogEntry:this.#e.generateLogEntry,batchPeriodSeconds:this.#e.batchPeriodSeconds,dispatchFunction:this.#t},e)}#e;#t=i(async e=>{if(e.length===0)return;let t=ad(e[0]),r=cd(e,t),s=(this.#e.generateBlobName??sd)(e);await ld(r,this.#e,s)},"#dispatch")};function ad(n){return Object.keys(n)}i(ad,"getHeaders");function ud(n){if(n==null)return"";let e=String(n);return(e.includes('"')||e.includes(",")||e.includes(`
74
+ `)||e.includes("\r"))&&(e=e.replace(/"/g,'""'),e=`"${e}"`),e}i(ud,"escapeCsvValue");function cd(n,e){let t=[];t.push(e.join(","));for(let r of n){let o=[];for(let s of e){let a=r[s];o.push(ud(a))}t.push(o.join(","))}return t.join(`
75
+ `)}i(cd,"generateCsvContent");async function ld(n,e,t){let{sasUrl:r}=e,o=r.split("?"),s=`${o[0]}/${t}?${o[1]}`;try{let a=await $.fetch(s,{method:"PUT",headers:{"x-ms-blob-type":"BlockBlob","Content-Type":"text/csv"},body:n});a.ok||(si({message:a.statusText,status:a.status,details:await a.text()}),si({message:a.statusText,status:a.status,details:await a.text()}))}catch(a){si(a)}}i(ld,"uploadToAzureBlobStorage");function si(n){if(!ja){let t=Qe(),r=Q({level:"error",messages:["AzureBlobCsvPlugin: No context available to log user errors"]});t.waitUntil(r);return}let e;n instanceof Error?e={message:n.message,status:-1,details:n.stack??""}:e=n,ja.log.error("AzureBlobCsvPlugin: Error uploading to Azure Blob Storage",e)}i(si,"logError");var za="plugin.azure-event-hubs-request-logger",dd=60*60,pd=5*60;function Ba(){return Math.floor(Date.now()/1e3)}i(Ba,"nowEpochSeconds");var ui=class extends fe{static{i(this,"AzureEventHubsRequestLoggerPlugin")}#e;#t;#n=null;constructor(e){super(),this.#e=e,this.#t=this.#r(e.connectionString),f(za)}#r(e){let t=e.split(";"),r=new Map;for(let s of t){let[a,...u]=s.split("=");a&&u.length>0&&r.set(a,u.join("="))}return{endpoint:r.get("Endpoint")||"",sharedAccessKeyName:r.get("SharedAccessKeyName")||"",sharedAccessKey:r.get("SharedAccessKey")||"",entityPath:r.get("EntityPath")||""}}async#o(e,t,r){let o=new TextEncoder,s=e.replace(/^https?:\/\//,""),a=encodeURIComponent(s),c=Ba()+dd,l=`${a}
76
+ ${c}`,d={name:"HMAC",hash:{name:"SHA-256"}},p=await crypto.subtle.importKey("raw",o.encode(r),d,!1,["sign"]),m=await crypto.subtle.sign("HMAC",p,o.encode(l)),h=new Uint8Array(m),I=btoa(String.fromCharCode(...h)),b=encodeURIComponent(I);return{token:`SharedAccessSignature sr=${a}&sig=${b}&se=${c}&skn=${t}`,expiryEpochSeconds:c}}async#i(){let e=Ba();if(this.#n&&e<this.#n.expiryEpochSeconds-pd)return this.#n.token;let t=this.#t.entityPath?this.#t.entityPath:(this.#e.eventHubName??"").trim();if(!t)throw new Error("No entity path - either set EntityPath in the connection string or supply eventHubName");let o=`${this.#t.endpoint.replace(/\/$/,"").toLowerCase()}/${t}`,s=await this.#o(o,this.#t.sharedAccessKeyName,this.#t.sharedAccessKey);return this.#n=s,s.token}async initialize(e){new He({name:za,generateLogEntry:this.#e.generateLogEntry,batchPeriodSeconds:this.#e.batchPeriodSeconds,dispatchFunction:this.#s},e)}#s=i(async e=>{if(e.length===0)return;let t=this.#t.entityPath?this.#t.entityPath:(this.#e.eventHubName??"").trim(),o=`https://${this.#t.endpoint.replace(/\/$/,"").replace(/^sb:\/\//,"")}/${t}/messages?timeout=60`,s=await this.#i(),a=await fetch(o,{method:"POST",headers:{Authorization:s,"Content-Type":"application/json"},body:JSON.stringify(e)});if(!a.ok)throw new Error(`AzureEventHubsRequestLoggerPlugin: Failed to send logs to ${o}
77
77
  Status: ${a.status} - ${a.statusText}
78
- Body: ${await a.text()}`)},"#dispatch")};var dd=i(async(n,e,t,r)=>({deploymentName:r.deploymentName,timestamp:r.requestStartTime.toISOString(),requestId:t.requestId,routePath:t.route.path,url:e.url,colo:t.incomingRequestProperties.colo,city:t.incomingRequestProperties.city,country:t.incomingRequestProperties.country,continent:t.incomingRequestProperties.continent,latitude:t.incomingRequestProperties.latitude,longitude:t.incomingRequestProperties.longitude,postalCode:t.incomingRequestProperties.postalCode,metroCode:t.incomingRequestProperties.metroCode,region:t.incomingRequestProperties.region,regionCode:t.incomingRequestProperties.regionCode,timezone:t.incomingRequestProperties.timezone,asn:t.incomingRequestProperties.asn?.toString(),asOrganization:t.incomingRequestProperties.asOrganization,statusCode:n.status,durationMs:r.durationMs,method:e.method,userSub:e.user?.sub,instanceId:r.instanceId,clientIP:e.headers.get("true-client-ip")??void 0,zuploUserAgent:r.systemUserAgent}),"defaultGenerateHydrolixEntry"),za="plugin.hydrolix-request-logger",ci=class extends fe{static{i(this,"HydrolixRequestLoggerPlugin")}constructor(e){super(),e.batchPeriodSeconds||(e.batchPeriodSeconds=1),this.#e=e,f(za)}async initialize(e){new He({name:za,generateLogEntry:this.#e.generateLogEntry,batchPeriodSeconds:this.#e.batchPeriodSeconds,dispatchFunction:this.#t},e)}#e;#t=i(async e=>{if(e.length===0)return;let t={"x-hdx-table":this.#e.table,"x-hdx-transform":this.#e.transform,"content-type":"application/json"};this.#e.token&&(t["x-hdx-token"]=this.#e.token,t.authorization=`Basic ${btoa(`${this.#e.username}:${this.#e.password}`)}`),await $.fetch(`https://${this.#e.hostname}/ingest/event`,{method:"POST",headers:t,body:JSON.stringify(e)})},"#dispatch")};var pd="plugin.request-logger",li=class extends fe{static{i(this,"RequestLoggerPlugin")}constructor(e){super(),this.#e=e,f(pd)}async initialize(e){new He(this.#e,e)}#e};var di=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}},$e=class extends di{static{i(this,"StripeSignatureVerificationError")}header;payload;constructor(e,t,r={}){super(r),this.header=e,this.payload=t}};var md="v1",gd=300;async function Ba(n,e,t,r=gd,o){return await hd(n,e,t,r,o),n instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(n)):JSON.parse(n)}i(Ba,"constructEventAsync");function fd(n,e){return`${e.timestamp}.${n}`}i(fd,"makeHMACContent");async function hd(n,e,t,r,o){let{decodedHeader:s,decodedPayload:a,details:u,suspectPayloadType:c}=yd(n,e,md),l=/\s/.test(t),d=await Pd(fd(a,u),t);return bd(a,s,u,d,r,c,l,o)}i(hd,"verifyHeaderAsync");function yd(n,e,t){if(!n)throw new $e(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 $e(e,n,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=wd(a,t);if(!u||u.timestamp===-1)throw new $e(a,s,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new $e(a,s,{message:"No signatures found with expected scheme"});return{decodedPayload:s,decodedHeader:a,details:u,suspectPayloadType:r}}i(yd,"parseEventDetails");function bd(n,e,t,r,o,s,a,u){let c=!!t.signatures.filter(m=>Rd(m,r)).length,l=`
78
+ Body: ${await a.text()}`)},"#dispatch")};var md=i(async(n,e,t,r)=>({deploymentName:r.deploymentName,timestamp:r.requestStartTime.toISOString(),requestId:t.requestId,routePath:t.route.path,url:e.url,colo:t.incomingRequestProperties.colo,city:t.incomingRequestProperties.city,country:t.incomingRequestProperties.country,continent:t.incomingRequestProperties.continent,latitude:t.incomingRequestProperties.latitude,longitude:t.incomingRequestProperties.longitude,postalCode:t.incomingRequestProperties.postalCode,metroCode:t.incomingRequestProperties.metroCode,region:t.incomingRequestProperties.region,regionCode:t.incomingRequestProperties.regionCode,timezone:t.incomingRequestProperties.timezone,asn:t.incomingRequestProperties.asn?.toString(),asOrganization:t.incomingRequestProperties.asOrganization,statusCode:n.status,durationMs:r.durationMs,method:e.method,userSub:e.user?.sub,instanceId:r.instanceId,clientIP:e.headers.get("true-client-ip")??void 0,zuploUserAgent:r.systemUserAgent}),"defaultGenerateHydrolixEntry"),Ga="plugin.hydrolix-request-logger",ci=class extends fe{static{i(this,"HydrolixRequestLoggerPlugin")}constructor(e){super(),e.batchPeriodSeconds||(e.batchPeriodSeconds=1),this.#e=e,f(Ga)}async initialize(e){new He({name:Ga,generateLogEntry:this.#e.generateLogEntry,batchPeriodSeconds:this.#e.batchPeriodSeconds,dispatchFunction:this.#t},e)}#e;#t=i(async e=>{if(e.length===0)return;let t={"x-hdx-table":this.#e.table,"x-hdx-transform":this.#e.transform,"content-type":"application/json"};this.#e.token&&(t["x-hdx-token"]=this.#e.token,t.authorization=`Basic ${btoa(`${this.#e.username}:${this.#e.password}`)}`),await $.fetch(`https://${this.#e.hostname}/ingest/event`,{method:"POST",headers:t,body:JSON.stringify(e)})},"#dispatch")};var gd="plugin.request-logger",li=class extends fe{static{i(this,"RequestLoggerPlugin")}constructor(e){super(),this.#e=e,f(gd)}async initialize(e){new He(this.#e,e)}#e};var di=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}},$e=class extends di{static{i(this,"StripeSignatureVerificationError")}header;payload;constructor(e,t,r={}){super(r),this.header=e,this.payload=t}};var fd="v1",hd=300;async function Va(n,e,t,r=hd,o){return await bd(n,e,t,r,o),n instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(n)):JSON.parse(n)}i(Va,"constructEventAsync");function yd(n,e){return`${e.timestamp}.${n}`}i(yd,"makeHMACContent");async function bd(n,e,t,r,o){let{decodedHeader:s,decodedPayload:a,details:u,suspectPayloadType:c}=wd(n,e,fd),l=/\s/.test(t),d=await Ed(yd(a,u),t);return Rd(a,s,u,d,r,c,l,o)}i(bd,"verifyHeaderAsync");function wd(n,e,t){if(!n)throw new $e(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 $e(e,n,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=Pd(a,t);if(!u||u.timestamp===-1)throw new $e(a,s,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new $e(a,s,{message:"No signatures found with expected scheme"});return{decodedPayload:s,decodedHeader:a,details:u,suspectPayloadType:r}}i(wd,"parseEventDetails");function Rd(n,e,t,r,o,s,a,u){let c=!!t.signatures.filter(m=>Id(m,r)).length,l=`
79
79
  Learn more about webhook signing and explore webhook integration examples for various frameworks at https://github.com/stripe/stripe-node#webhook-signing`,d=a?`
80
80
 
81
81
  Note: The provided signing secret contains whitespace. This often indicates an extra newline or space is in the value`:"";if(!c)throw s?new $e(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.
@@ -84,11 +84,11 @@ Signature verification is impossible without access to the original signed mater
84
84
  `+d}):new $e(e,n,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
85
85
  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.
86
86
  `+l+`
87
- `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new $e(e,n,{message:"Timestamp outside the tolerance zone"});return!0}i(bd,"validateComputedSignature");function wd(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(wd,"parseHeader");function Rd(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(Rd,"secureCompare");async function Pd(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]=pi[s[u]];return a.join("")}i(Pd,"computeHMACSignatureAsync");var pi=new Array(256);for(let n=0;n<pi.length;n++)pi[n]=n.toString(16).padStart(2,"0");function W(n,e,t="policy",r){let o=`${t} '${e}'`;if(!st(n))throw new g(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let s=i((c,l,d)=>{let p=n[c],m=r?`${r}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new g(`Value of '${m}' 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 g(`Value of '${m}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new g(`Value of '${m}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new g(`Value of '${m}' 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 g(`Value of '${m}' 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(W,"optionValidator");var un=class extends ae{static{i(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),f("policy.inbound.stripe-webhook-verification")}async handler(e,t){W(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 Ba(o,r,this.options.signingSecret)}catch(o){let s=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a,s.startsWith("No signatures found matching the expected signature for payload")&&(s="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",s),T.badRequest(e,t,{title:"Webhook Error",detail:s})}return e}};function Ga(n){return n!==null&&typeof n=="object"&&"id"in n&&Te(n.id)&&"type"in n&&Te(n.type)}i(Ga,"isStripeWebhookEvent");var Id={getSubscription:i(async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await $.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 k(s)}return o},"getSubscription"),getCustomer:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await $.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 k(s)}return o},"getCustomer"),getUpcomingInvoice:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await $.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 k(s)}return o},"getUpcomingInvoice")},Jn=Id;var mi="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Va="My API Key";async function Wa({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=y.instance,c=new URL(`/v1/buckets/${n}/consumers`,mi);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Va,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await we({retryDelayMs:5,retries:2,logger:J.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),m=await p.json();if(p.status!==200){let h="Error creating API Key Consumer";throw a.log.error(h,m),new k(h)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(Wa,"createConsumer");async function Ja({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=y.instance,u=new URL(`/v1/buckets/${n}/consumers`,mi);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:Va,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await we({retryDelayMs:5,retries:2,logger:J.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 m="Error creating API Key Consumer";throw s.log.error(m,p),new k(m)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(Ja,"createConsumerInvite");async function Ka({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=y.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,mi);o.searchParams.set("with-api-key","true");let s=await we({retryDelayMs:5,retries:2,logger:J.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 k(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(Ka,"deleteConsumer");async function Qa({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:m}=y.instance;if(!ft(p))throw new Y("No Zuplo JWT token set.");let h=await we({retryDelayMs:5,retries:2,logger:J.getLogger(n)},`${m}/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 I=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,b,E="";try{b=await h.json(),E=b.detail??b.title}catch{b={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:h.status,detail:h.statusText}}throw n.log.error(I,b),new k(`${I} ${E}`)}n.log.info("Successfully created monetization subscription.",d)}i(Qa,"createSubscription");async function It({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=y.instance;if(!ft(o))throw new Y("No Zuplo JWT token set.");let a=await we({retryDelayMs:5,retries:2,logger:J.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 k(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}i(It,"updateSubscription");async function Et({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=y.instance;if(!ft(o))throw new Y("No Zuplo JWT token set.");let a=await we({retryDelayMs:5,retries:2,logger:J.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 k(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(c),new k(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(c),new k(c)}return u.data[0]}i(Et,"getSubscription");var ue="Skipping since we're unable to process the webhook event.",tt="Successfully processed the webhook event",xe="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function Kn(n){return n.replaceAll("_","-")}i(Kn,"stripeStatusToMeteringStatus");function ut(n){return new Date(n*1e3).toISOString()}i(ut,"unixTimestampToISOString");async function gi(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),T.ok(n,e,{title:ue,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),T.ok(n,e,{title:ue,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=t.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),T.ok(n,e,{title:ue,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!==y.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),T.ok(n,e,{title:ue,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+xe});let u=s.product,c,l,d;try{if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_email&&t.data.object.metadata.zuplo_created_by_sub)l=t.data.object.metadata.zuplo_created_by_email,d=t.data.object.metadata.zuplo_created_by_sub,c=await Wa({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await Jn.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),T.ok(n,e,{title:ue,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Ja({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}}catch(p){return e.log.warn(`Failed to create API Key Consumer. Error: ${p.message}`),T.ok(n,e,{title:ue,detail:p.message})}if(!c)return T.ok(n,e,{title:ue,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=Kn(t.data.object.status),m;l&&d&&(m={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:ut(t.data.object.trial_end),trialStartDate:ut(t.data.object.trial_start)}),await Qa({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:m,trial:h})}catch(p){return await Ka({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),T.ok(n,e,{title:ue,detail:p.message})}return T.ok(n,e,{title:tt})}i(gi,"onCustomerSubscriptionCreated");async function fi(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),T.ok(n,e,{title:ue,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),T.ok(n,e,{title:ue,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!==y.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),T.ok(n,e,{title:ue,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+xe});try{let a=await Et({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});await It({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return T.ok(n,e,{title:ue,detail:`The event 'customer.subscription.deleted' could not be processed. ${a.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. `+xe})}return T.ok(n,e,{title:tt})}i(fi,"onCustomerSubscriptionDeleted");async function hi(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to include '.data.object.id' as the subscription ID.`),T.ok(n,e,{title:ue,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),T.ok(n,e,{title:ue,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!==y.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),T.ok(n,e,{title:ue,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+xe});if(t.data.previous_attributes){let a=t.data.previous_attributes;if(a.status&&a.status!==t.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${t.id}'.`);let u=await Et({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=Kn(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=ut(t.data.object.trial_end)),await It({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return T.ok(n,e,{title:ue,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+xe})}return T.ok(n,e,{title:tt})}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 Et({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await Jn.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(m=>m.proration&&m.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 It({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return T.ok(n,e,{title:ue,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+xe})}return T.ok(n,e,{title:tt})}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 Et({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?ut(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?ut(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await It({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return T.ok(n,e,{title:ue,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+xe})}return T.ok(n,e,{title:tt})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),T.ok(n,e,{title:ue,detail:"This 'customer.subscription.updated' event could not be processed. The Stripe monetization plugin only supports update events for subscription plan changes or subscription status changes."+xe})}i(hi,"onCustomerSubscriptionUpdated");var Ya=class extends En{constructor(t){super();this.options=t;f("monetization.stripe")}static{i(this,"StripeMonetizationPlugin")}registerRoutes(t,r){let o=i(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(ye.ZUPLO_METERING_SERVICE_BUCKET_ID)d=ye.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(ye.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=ye.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new g("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!y.instance.build.ACCOUNT_NAME)throw new Y("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let m=this.options.primaryDataRegion??"us-central1";if(!Ed(m))throw new g(`StripeMonetizationPlugin - The value '${m}' on the property 'primaryDataRegion' is invalid.`);let h=await c.json();if(!Ga(h))return T.ok(c,l,{title:ue,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+xe});switch(l.log.info(`Received Stripe webhook event of type '${h.type}' with ID '${h.id}'.`),h.type){case"customer.subscription.created":return await gi(c,l,h,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await hi(c,l,h,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await fi(c,l,h,{meteringBucketId:d});default:return T.ok(c,l,{title:ue,detail:`Event '${h.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+xe})}},"stripeWebhookHandler"),s=ea({inboundPolicies:[new un({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});W(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new he({processors:[Pe,s],handler:o,gateway:r}),u=new pe({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function Ed(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}i(Ed,"isMetricsRegion");var eu=new WeakMap,Xa={},yi=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){eu.set(e,t)}};async function xd(n,e,t,r){if(f("policy.inbound.amberflo-metering"),!t.statusCodes)throw new g(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=We(t.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=eu.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new k(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=Fe(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)},m=Xa[t.apiKey];if(!m){let h=t.apiKey,I=n.headers.get("zm-test-id")??"";m=new K("amberflo-ingest-meter",10,async b=>{try{let E=t.url??"https://app.amberflo.io/ingest",L=await $.fetch(E,{method:"POST",body:JSON.stringify(b),headers:{"content-type":"application/json","x-api-key":h,"zm-test-id":I}});L.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${L.status}: ${await L.text()}`)}catch(E){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${E.message}`),E}}),Xa[h]=m}m.enqueue(p),e.waitUntil(m.waitUntilFlushed())}}),n}i(xd,"AmberfloMeteringInboundPolicy");async function ct(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(ct,"sha256");var tu=new Map;async function ie(n,e,t){let r,o=`${n}-${e}`,s=tu.get(o);return s!==void 0?r=s:(r=`zuplo-policy-${await ct(JSON.stringify({policyName:n,options:t}))}`,tu.set(n,r)),r}i(ie,"getPolicyCacheName");var nu="key-metadata-cache-type";function Td(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}i(Td,"getKeyValue");async function bi(n,e,t,r){if(f("policy.inbound.api-key"),!t.bucketName)if(ye.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=ye.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new g(`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 g(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let s=i(L=>o.allowUnauthenticatedRequests?n:T.unauthorized(n,e,{detail:L}),"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 vd(u),l=await ie(r,void 0,o),d=new re(l,e),p=await d.get(c);if(p&&p.isValid===!0)return n.user=p.user,n;if(p&&!p.isValid)return p.typeId!==nu&&J.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let m={key:u},h=new Headers({"content-type":"application/json"});De(h,e.requestId);let I=await we({retryDelayMs:5,retries:2,logger:J.getLogger(e)},`${y.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:h,body:JSON.stringify(m)});if(I.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(I.status!==200){try{let L=await I.text(),O=JSON.parse(L);e.log.error("Unexpected response from key service",O)}catch{e.log.error("Invalid response from key service")}throw new k(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${I.status}`)}let b=await I.json(),E={isValid:!0,typeId:nu,user:{apiKeyId:b.id,sub:b.name,data:b.metadata}};return n.user=E.user,d.put(c,E,o.cacheTtlSeconds),n}i(bi,"ApiKeyInboundPolicy");async function vd(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(vd,"hashValue");var Cd=bi;var ru=Symbol("aserto-authz-resource-context"),wi=class extends ae{static{i(this,"AsertoAuthZInboundPolicy")}cache;authorizationUrl;static setAuthorizationContext(e,t){oe.set(e,ru,t)}constructor(e,t){if(super(e,t),W(e,t).required("tenantId","string").required("authorizerApiKey","string").required("serviceName","string").optional("policyName","string").optional("authorizerApiUrl","string").optional("allowUnauthorizedRequests","boolean").optional("userSubPropertyPath","string"),this.options.authorizerApiUrl)try{new URL(this.options.authorizerApiUrl)}catch{throw new g(`${this.policyType} '${this.policyName}' - Value of 'authorizerApiUrl' is not a valid URL. If using an environment variable, check that it is set correctly.`)}this.authorizationUrl=new URL("/api/v2/authz/is",this.options.authorizerApiUrl??"https://authorizer.prod.aserto.com")}async handler(e,t){if(!this.cache){let c=await ie(this.policyName,void 0,this.options);this.cache=new re(c,t)}let r=i(c=>this.options.allowUnauthorizedRequests?e:T.forbidden(e,t,{detail:c}),"forbiddenResponse");if(!e.user)return t.log.error(`${this.policyType} '${this.policyName}' - User is not authenticated. An authentication policy must come before the authorization policy.`),T.unauthorized(e,t);let o=oe.get(t,ru),s;o?.policyInstance?s=o.policyInstance:this.options.policyName?s={name:this.options.policyName}:s={name:"api-auth"};let a=this.options.userSubPropertyPath&&e.user?Fe(e.user,this.options.userSubPropertyPath,"userSubPropertyPath"):e.user.sub,u={identityContext:o?.identityContext??{type:"IDENTITY_TYPE_SUB",identity:a},resourceContext:o?.resourceContext??{object_type:"endpoint",object_id:`${this.options.serviceName}:${e.method}:${t.route.path}`,relation:"can_invoke"},policyContext:o?.policyContext??{decisions:["allowed"],path:"rebac.check"},policyInstance:s};try{t.log.debug("Aserto Request",u);let c=await $.fetch(this.authorizationUrl,{headers:{"Content-Type":"application/json","Aserto-Tenant-ID":this.options.tenantId,Authorization:`basic ${this.options.authorizerApiKey}`},method:"POST",body:JSON.stringify(u)});if(c.status!==200){let d=`Error calling Aserto service. Status: ${c.status}`;try{d=(await c.json()).message}catch{}return t.log.error(`${this.policyType} '${this.policyName}' - ${d}`),c.status>=400&&c.status<500?r(d):T.internalServerError(e,t)}let l=await c.json();return t.log.debug("Aserto Response",l),l.decisions?.[0].is?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,l),r("The request was not authorized."))}catch(c){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling Aserto service`,c),T.internalServerError(e,t)}}};import{createRemoteJWKSet as Od,jwtVerify as iu}from"jose";import{createLocalJWKSet as Sd}from"jose";var Ri=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 Pi&&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",y.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=Sd(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 $.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new Ii("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new xt("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 xt("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function ou(n,e,t){let r=new Ri(n,e,t);return async(o,s)=>r.getKey(o,s)}i(ou,"createRemoteJWKSet");var xt=class extends k{static{i(this,"JWKSError")}},Pi=class extends xt{static{i(this,"JWKSNoMatchingKey")}},Ii=class extends xt{static{i(this,"JWKSTimeout")}};var Qn={},Ad=i((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new g("Invalid State - jwkUrl not set");if(!Qn[r.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(s=r.useExperimentalInMemoryCache),s){let a=await ie(n,void 0,r),u=new re(a,e);Qn[r.jwkUrl]=ou(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else Qn[r.jwkUrl]=Od(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await iu(t,Qn[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),kd=i(async(n,e)=>{let t;if(e.secret===void 0)throw new g("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 iu(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),Ee=i(async(n,e,t,r)=>{f("policy.inbound.open-id-jwt-auth");let o=t.authHeader??"Authorization",s=n.headers.get(o),a="bearer ",u=i(h=>T.unauthorized(n,e,{detail:h}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new g(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new g(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let c=t.jwkUrl?Ad(r,e):kd,d=await i(async()=>{if(!s)return u("No authorization header");if(s.toLowerCase().indexOf(a)!==0)return u("Invalid bearer token format for authorization header");let h=s.substring(a.length);if(!h||h.length===0)return u("No bearer token on authorization header");try{return await c(h,t)}catch(I){let b=new URL(n.url);return"code"in I&&I.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${b.pathname} `,I):e.log.warn(`Invalid token on: ${n.method} ${b.pathname}`,I),u("Invalid token")}},"getJwtOrRejectedResponse")();if(d instanceof Response)return t.allowUnauthenticatedRequests===!0?n:d;let p=t.subPropertyName??"sub",m=d[p];return m?(n.user={sub:m,data:d},n):u(`Token is not valid, no '${p}' property found.`)},"OpenIdJwtInboundPolicy");var Ld=i(async(n,e,t,r)=>(f("policy.inbound.auth0-jwt-auth"),Ee(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"Auth0JwtInboundPolicy");var su=new Map;function _d(n){let e=[],t=0;for(;t<n.length;){if(n[t]==="."){t++;continue}if(n[t]==="["){for(t++;t<n.length&&/\s/.test(n[t]);)t++;let r=n[t];if(r!=='"'&&r!=="'"){for(;t<n.length&&n[t]!=="]";)t++;t++;continue}t++;let o=t;for(;t<n.length&&n[t]!==r;)t++;let s=n.substring(o,t);for(e.push(s),t++;t<n.length&&/\s/.test(n[t]);)t++;n[t]==="]"&&t++}else{let r=t;for(;t<n.length&&n[t]!=="."&&n[t]!=="[";)t++;let o=n.substring(r,t).trim();o.length>0&&e.push(o)}}return e}i(_d,"parsePropertyPath");function Yn(n,e){let t="$authzen-prop(";if(!n.startsWith(t)||!n.endsWith(")"))return n;let r=n.slice(t.length,-1),o=su.get(r);o||(o=_d(r),su.set(r,o));let s=e;for(let a of o){if(s==null)return;typeof s.get=="function"?s=s.get(a):s=s[a]}return s}i(Yn,"evaluateAuthzenProp");var au=Symbol("AUTHZEN_CONTEXT_DATA_52a5cf22-d922-4673-9815-6dc3d49071d9"),Ei=class n extends ae{static{i(this,"AuthZenInboundPolicy")}#e;#t;constructor(e,t){if(super(e,t),W(e,t).required("authorizerHostname","string").optional("authorizerAuthorizationHeader","string").optional("subject","object").optional("resource","object").optional("action","object").optional("throwOnError","boolean"),e.subject&&!e.subject.type)throw new g(`${this.policyType} '${this.policyName}' - subject.type is required.`);if(e.subject&&!e.subject.id)throw new g(`${this.policyType} '${this.policyName}' - subject.id is required.`);if(e.resource&&!e.resource.type)throw new g(`${this.policyType} '${this.policyName}' - resource.type is required.`);if(e.resource&&!e.resource.id)throw new g(`${this.policyType} '${this.policyName}' - resource.id is required.`);if(e.action&&!e.action.name)throw new g(`${this.policyType} '${this.policyName}' - action.name is required.`);this.#e=(e.authorizerHostname.startsWith("https://")?e.authorizerHostname:`https://${e.authorizerHostname}`)+"/access/v1/evaluation";try{new URL(this.#e)}catch(r){throw new g(`${this.policyType} '${this.policyName}' - authorizerUrl '${this.#e}' is not valid
87
+ `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new $e(e,n,{message:"Timestamp outside the tolerance zone"});return!0}i(Rd,"validateComputedSignature");function Pd(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(Pd,"parseHeader");function Id(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(Id,"secureCompare");async function Ed(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]=pi[s[u]];return a.join("")}i(Ed,"computeHMACSignatureAsync");var pi=new Array(256);for(let n=0;n<pi.length;n++)pi[n]=n.toString(16).padStart(2,"0");function W(n,e,t="policy",r){let o=`${t} '${e}'`;if(!st(n))throw new g(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let s=i((c,l,d)=>{let p=n[c],m=r?`${r}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new g(`Value of '${m}' 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 g(`Value of '${m}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new g(`Value of '${m}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new g(`Value of '${m}' 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 g(`Value of '${m}' 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(W,"optionValidator");var un=class extends ae{static{i(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),f("policy.inbound.stripe-webhook-verification")}async handler(e,t){W(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 Va(o,r,this.options.signingSecret)}catch(o){let s=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a,s.startsWith("No signatures found matching the expected signature for payload")&&(s="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",s),T.badRequest(e,t,{title:"Webhook Error",detail:s})}return e}};function Wa(n){return n!==null&&typeof n=="object"&&"id"in n&&Te(n.id)&&"type"in n&&Te(n.type)}i(Wa,"isStripeWebhookEvent");var xd={getSubscription:i(async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await $.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 k(s)}return o},"getSubscription"),getCustomer:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await $.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 k(s)}return o},"getCustomer"),getUpcomingInvoice:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await $.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 k(s)}return o},"getUpcomingInvoice")},Jn=xd;var mi="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Ja="My API Key";async function Ka({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=y.instance,c=new URL(`/v1/buckets/${n}/consumers`,mi);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Ja,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await we({retryDelayMs:5,retries:2,logger:J.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),m=await p.json();if(p.status!==200){let h="Error creating API Key Consumer";throw a.log.error(h,m),new k(h)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(Ka,"createConsumer");async function Qa({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=y.instance,u=new URL(`/v1/buckets/${n}/consumers`,mi);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:Ja,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await we({retryDelayMs:5,retries:2,logger:J.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 m="Error creating API Key Consumer";throw s.log.error(m,p),new k(m)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(Qa,"createConsumerInvite");async function Ya({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=y.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,mi);o.searchParams.set("with-api-key","true");let s=await we({retryDelayMs:5,retries:2,logger:J.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 k(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(Ya,"deleteConsumer");async function Xa({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:m}=y.instance;if(!ft(p))throw new Y("No Zuplo JWT token set.");let h=await we({retryDelayMs:5,retries:2,logger:J.getLogger(n)},`${m}/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 I=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,b,E="";try{b=await h.json(),E=b.detail??b.title}catch{b={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:h.status,detail:h.statusText}}throw n.log.error(I,b),new k(`${I} ${E}`)}n.log.info("Successfully created monetization subscription.",d)}i(Xa,"createSubscription");async function It({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=y.instance;if(!ft(o))throw new Y("No Zuplo JWT token set.");let a=await we({retryDelayMs:5,retries:2,logger:J.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 k(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}i(It,"updateSubscription");async function Et({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=y.instance;if(!ft(o))throw new Y("No Zuplo JWT token set.");let a=await we({retryDelayMs:5,retries:2,logger:J.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 k(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(c),new k(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(c),new k(c)}return u.data[0]}i(Et,"getSubscription");var ue="Skipping since we're unable to process the webhook event.",tt="Successfully processed the webhook event",xe="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function Kn(n){return n.replaceAll("_","-")}i(Kn,"stripeStatusToMeteringStatus");function ut(n){return new Date(n*1e3).toISOString()}i(ut,"unixTimestampToISOString");async function gi(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),T.ok(n,e,{title:ue,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),T.ok(n,e,{title:ue,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=t.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),T.ok(n,e,{title:ue,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!==y.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),T.ok(n,e,{title:ue,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+xe});let u=s.product,c,l,d;try{if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_email&&t.data.object.metadata.zuplo_created_by_sub)l=t.data.object.metadata.zuplo_created_by_email,d=t.data.object.metadata.zuplo_created_by_sub,c=await Ka({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await Jn.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),T.ok(n,e,{title:ue,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Qa({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}}catch(p){return e.log.warn(`Failed to create API Key Consumer. Error: ${p.message}`),T.ok(n,e,{title:ue,detail:p.message})}if(!c)return T.ok(n,e,{title:ue,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=Kn(t.data.object.status),m;l&&d&&(m={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:ut(t.data.object.trial_end),trialStartDate:ut(t.data.object.trial_start)}),await Xa({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:m,trial:h})}catch(p){return await Ya({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),T.ok(n,e,{title:ue,detail:p.message})}return T.ok(n,e,{title:tt})}i(gi,"onCustomerSubscriptionCreated");async function fi(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),T.ok(n,e,{title:ue,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),T.ok(n,e,{title:ue,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!==y.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),T.ok(n,e,{title:ue,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+xe});try{let a=await Et({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});await It({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return T.ok(n,e,{title:ue,detail:`The event 'customer.subscription.deleted' could not be processed. ${a.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. `+xe})}return T.ok(n,e,{title:tt})}i(fi,"onCustomerSubscriptionDeleted");async function hi(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to include '.data.object.id' as the subscription ID.`),T.ok(n,e,{title:ue,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),T.ok(n,e,{title:ue,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!==y.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),T.ok(n,e,{title:ue,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+xe});if(t.data.previous_attributes){let a=t.data.previous_attributes;if(a.status&&a.status!==t.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${t.id}'.`);let u=await Et({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=Kn(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=ut(t.data.object.trial_end)),await It({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return T.ok(n,e,{title:ue,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+xe})}return T.ok(n,e,{title:tt})}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 Et({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await Jn.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(m=>m.proration&&m.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 It({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return T.ok(n,e,{title:ue,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+xe})}return T.ok(n,e,{title:tt})}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 Et({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?ut(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?ut(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await It({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return T.ok(n,e,{title:ue,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+xe})}return T.ok(n,e,{title:tt})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),T.ok(n,e,{title:ue,detail:"This 'customer.subscription.updated' event could not be processed. The Stripe monetization plugin only supports update events for subscription plan changes or subscription status changes."+xe})}i(hi,"onCustomerSubscriptionUpdated");var eu=class extends En{constructor(t){super();this.options=t;f("monetization.stripe")}static{i(this,"StripeMonetizationPlugin")}registerRoutes(t,r){let o=i(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(ye.ZUPLO_METERING_SERVICE_BUCKET_ID)d=ye.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(ye.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=ye.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new g("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!y.instance.build.ACCOUNT_NAME)throw new Y("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let m=this.options.primaryDataRegion??"us-central1";if(!Td(m))throw new g(`StripeMonetizationPlugin - The value '${m}' on the property 'primaryDataRegion' is invalid.`);let h=await c.json();if(!Wa(h))return T.ok(c,l,{title:ue,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+xe});switch(l.log.info(`Received Stripe webhook event of type '${h.type}' with ID '${h.id}'.`),h.type){case"customer.subscription.created":return await gi(c,l,h,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await hi(c,l,h,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await fi(c,l,h,{meteringBucketId:d});default:return T.ok(c,l,{title:ue,detail:`Event '${h.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+xe})}},"stripeWebhookHandler"),s=na({inboundPolicies:[new un({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});W(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new he({processors:[Pe,s],handler:o,gateway:r}),u=new pe({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function Td(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}i(Td,"isMetricsRegion");var nu=new WeakMap,tu={},yi=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){nu.set(e,t)}};async function vd(n,e,t,r){if(f("policy.inbound.amberflo-metering"),!t.statusCodes)throw new g(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=We(t.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=nu.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new k(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=Fe(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)},m=tu[t.apiKey];if(!m){let h=t.apiKey,I=n.headers.get("zm-test-id")??"";m=new K("amberflo-ingest-meter",10,async b=>{try{let E=t.url??"https://app.amberflo.io/ingest",L=await $.fetch(E,{method:"POST",body:JSON.stringify(b),headers:{"content-type":"application/json","x-api-key":h,"zm-test-id":I}});L.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${L.status}: ${await L.text()}`)}catch(E){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${E.message}`),E}}),tu[h]=m}m.enqueue(p),e.waitUntil(m.waitUntilFlushed())}}),n}i(vd,"AmberfloMeteringInboundPolicy");async function ct(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(ct,"sha256");var ru=new Map;async function ie(n,e,t){let r,o=`${n}-${e}`,s=ru.get(o);return s!==void 0?r=s:(r=`zuplo-policy-${await ct(JSON.stringify({policyName:n,options:t}))}`,ru.set(n,r)),r}i(ie,"getPolicyCacheName");var ou="key-metadata-cache-type";function Cd(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}i(Cd,"getKeyValue");async function bi(n,e,t,r){if(f("policy.inbound.api-key"),!t.bucketName)if(ye.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=ye.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new g(`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 g(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let s=i(L=>o.allowUnauthenticatedRequests?n:T.unauthorized(n,e,{detail:L}),"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=Cd(a,o);if(!u||u==="")return s("No key present");let c=await Sd(u),l=await ie(r,void 0,o),d=new re(l,e),p=await d.get(c);if(p&&p.isValid===!0)return n.user=p.user,n;if(p&&!p.isValid)return p.typeId!==ou&&J.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let m={key:u},h=new Headers({"content-type":"application/json"});De(h,e.requestId);let I=await we({retryDelayMs:5,retries:2,logger:J.getLogger(e)},`${y.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:h,body:JSON.stringify(m)});if(I.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(I.status!==200){try{let L=await I.text(),O=JSON.parse(L);e.log.error("Unexpected response from key service",O)}catch{e.log.error("Invalid response from key service")}throw new k(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${I.status}`)}let b=await I.json(),E={isValid:!0,typeId:ou,user:{apiKeyId:b.id,sub:b.name,data:b.metadata}};return n.user=E.user,d.put(c,E,o.cacheTtlSeconds),n}i(bi,"ApiKeyInboundPolicy");async function Sd(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(Sd,"hashValue");var Od=bi;var iu=Symbol("aserto-authz-resource-context"),wi=class extends ae{static{i(this,"AsertoAuthZInboundPolicy")}cache;authorizationUrl;static setAuthorizationContext(e,t){oe.set(e,iu,t)}constructor(e,t){if(super(e,t),W(e,t).required("tenantId","string").required("authorizerApiKey","string").required("serviceName","string").optional("policyName","string").optional("authorizerApiUrl","string").optional("allowUnauthorizedRequests","boolean").optional("userSubPropertyPath","string"),this.options.authorizerApiUrl)try{new URL(this.options.authorizerApiUrl)}catch{throw new g(`${this.policyType} '${this.policyName}' - Value of 'authorizerApiUrl' is not a valid URL. If using an environment variable, check that it is set correctly.`)}this.authorizationUrl=new URL("/api/v2/authz/is",this.options.authorizerApiUrl??"https://authorizer.prod.aserto.com")}async handler(e,t){if(!this.cache){let c=await ie(this.policyName,void 0,this.options);this.cache=new re(c,t)}let r=i(c=>this.options.allowUnauthorizedRequests?e:T.forbidden(e,t,{detail:c}),"forbiddenResponse");if(!e.user)return t.log.error(`${this.policyType} '${this.policyName}' - User is not authenticated. An authentication policy must come before the authorization policy.`),T.unauthorized(e,t);let o=oe.get(t,iu),s;o?.policyInstance?s=o.policyInstance:this.options.policyName?s={name:this.options.policyName}:s={name:"api-auth"};let a=this.options.userSubPropertyPath&&e.user?Fe(e.user,this.options.userSubPropertyPath,"userSubPropertyPath"):e.user.sub,u={identityContext:o?.identityContext??{type:"IDENTITY_TYPE_SUB",identity:a},resourceContext:o?.resourceContext??{object_type:"endpoint",object_id:`${this.options.serviceName}:${e.method}:${t.route.path}`,relation:"can_invoke"},policyContext:o?.policyContext??{decisions:["allowed"],path:"rebac.check"},policyInstance:s};try{t.log.debug("Aserto Request",u);let c=await $.fetch(this.authorizationUrl,{headers:{"Content-Type":"application/json","Aserto-Tenant-ID":this.options.tenantId,Authorization:`basic ${this.options.authorizerApiKey}`},method:"POST",body:JSON.stringify(u)});if(c.status!==200){let d=`Error calling Aserto service. Status: ${c.status}`;try{d=(await c.json()).message}catch{}return t.log.error(`${this.policyType} '${this.policyName}' - ${d}`),c.status>=400&&c.status<500?r(d):T.internalServerError(e,t)}let l=await c.json();return t.log.debug("Aserto Response",l),l.decisions?.[0].is?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,l),r("The request was not authorized."))}catch(c){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling Aserto service`,c),T.internalServerError(e,t)}}};import{createRemoteJWKSet as kd,jwtVerify as au}from"jose";import{createLocalJWKSet as Ad}from"jose";var Ri=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 Pi&&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",y.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=Ad(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 $.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new Ii("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new xt("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 xt("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function su(n,e,t){let r=new Ri(n,e,t);return async(o,s)=>r.getKey(o,s)}i(su,"createRemoteJWKSet");var xt=class extends k{static{i(this,"JWKSError")}},Pi=class extends xt{static{i(this,"JWKSNoMatchingKey")}},Ii=class extends xt{static{i(this,"JWKSTimeout")}};var Qn={},Ld=i((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new g("Invalid State - jwkUrl not set");if(!Qn[r.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(s=r.useExperimentalInMemoryCache),s){let a=await ie(n,void 0,r),u=new re(a,e);Qn[r.jwkUrl]=su(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else Qn[r.jwkUrl]=kd(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await au(t,Qn[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),_d=i(async(n,e)=>{let t;if(e.secret===void 0)throw new g("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 au(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),Ee=i(async(n,e,t,r)=>{f("policy.inbound.open-id-jwt-auth");let o=t.authHeader??"Authorization",s=n.headers.get(o),a="bearer ",u=i(h=>T.unauthorized(n,e,{detail:h}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new g(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new g(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let c=t.jwkUrl?Ld(r,e):_d,d=await i(async()=>{if(!s)return u("No authorization header");if(s.toLowerCase().indexOf(a)!==0)return u("Invalid bearer token format for authorization header");let h=s.substring(a.length);if(!h||h.length===0)return u("No bearer token on authorization header");try{return await c(h,t)}catch(I){let b=new URL(n.url);return"code"in I&&I.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${b.pathname} `,I):e.log.warn(`Invalid token on: ${n.method} ${b.pathname}`,I),u("Invalid token")}},"getJwtOrRejectedResponse")();if(d instanceof Response)return t.allowUnauthenticatedRequests===!0?n:d;let p=t.subPropertyName??"sub",m=d[p];return m?(n.user={sub:m,data:d},n):u(`Token is not valid, no '${p}' property found.`)},"OpenIdJwtInboundPolicy");var Nd=i(async(n,e,t,r)=>(f("policy.inbound.auth0-jwt-auth"),Ee(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"Auth0JwtInboundPolicy");var uu=new Map;function Dd(n){let e=[],t=0;for(;t<n.length;){if(n[t]==="."){t++;continue}if(n[t]==="["){for(t++;t<n.length&&/\s/.test(n[t]);)t++;let r=n[t];if(r!=='"'&&r!=="'"){for(;t<n.length&&n[t]!=="]";)t++;t++;continue}t++;let o=t;for(;t<n.length&&n[t]!==r;)t++;let s=n.substring(o,t);for(e.push(s),t++;t<n.length&&/\s/.test(n[t]);)t++;n[t]==="]"&&t++}else{let r=t;for(;t<n.length&&n[t]!=="."&&n[t]!=="[";)t++;let o=n.substring(r,t).trim();o.length>0&&e.push(o)}}return e}i(Dd,"parsePropertyPath");function Yn(n,e){let t="$authzen-prop(";if(!n.startsWith(t)||!n.endsWith(")"))return n;let r=n.slice(t.length,-1),o=uu.get(r);o||(o=Dd(r),uu.set(r,o));let s=e;for(let a of o){if(s==null)return;typeof s.get=="function"?s=s.get(a):s=s[a]}return s}i(Yn,"evaluateAuthzenProp");var cu=Symbol("AUTHZEN_CONTEXT_DATA_52a5cf22-d922-4673-9815-6dc3d49071d9"),Ei=class n extends ae{static{i(this,"AuthZenInboundPolicy")}#e;#t;constructor(e,t){if(super(e,t),W(e,t).required("authorizerHostname","string").optional("authorizerAuthorizationHeader","string").optional("subject","object").optional("resource","object").optional("action","object").optional("throwOnError","boolean"),e.subject&&!e.subject.type)throw new g(`${this.policyType} '${this.policyName}' - subject.type is required.`);if(e.subject&&!e.subject.id)throw new g(`${this.policyType} '${this.policyName}' - subject.id is required.`);if(e.resource&&!e.resource.type)throw new g(`${this.policyType} '${this.policyName}' - resource.type is required.`);if(e.resource&&!e.resource.id)throw new g(`${this.policyType} '${this.policyName}' - resource.id is required.`);if(e.action&&!e.action.name)throw new g(`${this.policyType} '${this.policyName}' - action.name is required.`);this.#e=(e.authorizerHostname.startsWith("https://")?e.authorizerHostname:`https://${e.authorizerHostname}`)+"/access/v1/evaluation";try{new URL(this.#e)}catch(r){throw new g(`${this.policyType} '${this.policyName}' - authorizerUrl '${this.#e}' is not valid
88
88
  ${r}`)}}async handler(e,t){let r=this.options.throwOnError!==!1;try{await this.#o(t);let o=this.options.debug===!0,s={subject:Object.assign({},this.options.subject),resource:Object.assign({},this.options.resource),action:Object.assign({},this.options.action)},a={request:e,context:t};s.action?.name!==void 0&&(s.action.name=Yn(s.action.name,a)),s.subject?.id!==void 0&&(s.subject.id=Yn(s.subject.id,a)),s.resource?.id!==void 0&&(s.resource.id=Yn(s.resource.id,a)),o&&t.log.debug(`${this.policyType} '${this.policyName}' - Evaluated payload from options`,s);let u=n.getAuthorizationPayload(t);u&&Object.assign(s,u),o&&t.log.debug(`${this.policyType} '${this.policyName}' - Using context payload to override working payload`,{contextPayload:u,final:s}),this.#n(t,!s.subject?.type||!s.subject?.id,"Missing required subject type or id"),this.#n(t,!s.resource?.type||!s.resource?.id,"Missing required resource type or id"),this.#n(t,!s.action,"Missing required action");let c={"content-type":"application/json"};this.options.authorizerAuthorizationHeader&&(c.authorization=this.options.authorizerAuthorizationHeader);let l=await fetch(this.#e,{method:"POST",body:JSON.stringify(s),headers:c});if(!l.ok){let p=`${this.policyType} '${this.policyName}' - Unexpected response from PDP: ${l.status} - ${l.statusText}:
89
- ${await l.text()}`;if(r)throw new Error(p);return t.log.error(p),e}let d=await l.json();if(o&&t.log.debug(`${this.policyType} '${this.policyName}' - PDP response`,d),d.decision!==!0)return this.#r(e,t,d.reason)}catch(o){if(r)throw o;t.log.error(`${this.policyType} '${this.policyName}' - Error in policy: ${o}`)}return e}#n(e,t,r){if(t){let o=`${this.policyType} '${this.policyName}' - ${r}`;if(this.options.throwOnError)throw new g(o);e.log.warn(o)}}async#r(e,t,r){return T.forbidden(e,t,{detail:r})}async#o(e){if(!this.#t){let t=await ie(this.policyName,void 0,this.options);this.#t=new re(t,e)}}static setAuthorizationPayload(e,t){oe.set(e,au,t)}static getAuthorizationPayload(e){return oe.get(e,au)}};var Xn=class{constructor(e){this.options=e;this.authHeader=`Basic ${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 $.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 xi=class n extends ae{static{i(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static#e;static setAuthAttributes(e,t){n.#e||(n.#e=new WeakMap),n.#e.set(e,{Request:t})}constructor(e,t){super(e,t),f("policy.inbound.axiomatics-authz"),W(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new Xn(e)}async handler(e,t){let r=i(a=>this.options.allowUnauthorizedRequests?e:T.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=new URL(e.url),s=n.#e?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1&&e.user){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(s,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(s,"Action",a)}if(this.options.includeDefaultResourceAttributes!==!1){let a=[];a.push({AttributeId:"request.protocol",Value:o.protocol.substring(0,o.protocol.length-1)}),a.push({AttributeId:"request.host",Value:o.host}),a.push({AttributeId:"request.pathname",Value:o.pathname}),Object.entries(e.params).forEach(([u,c])=>{a.push({AttributeId:`request.params.${u}`,Value:c})}),o.searchParams.forEach((u,c)=>{a.push({AttributeId:`request.query.${c}`,Value:u})}),this.addAttributesToCategory(s,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:s,context:t});try{t.log.debug("PDP Request",s);let a=await this.pdpService.makePdpRequest(s);return t.log.debug("PDP Response",a),a.Response.every(u=>u.Decision==="Permit")?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling PDP service`,a),T.internalServerError(e,t)}}populateOptionAttributes({optionName:e,authzRequestCategory:t,authzRequest:r,context:o}){let s=this.options[e];if(s){let a=[];s.forEach(u=>{u.value?a.push({AttributeId:u.attributeId,Value:u.value}):o.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${u.attributeId} has no value. If using a selector, check that the selector is correct.`)}),this.addAttributesToCategory(r,t,a)}}addAttributesToCategory(e,t,r){e.Request[t]||(e.Request[t]=[]),e.Request[t].length===0?e.Request[t].push({Attribute:[]}):e.Request[t][0].Attribute=e.Request[t][0].Attribute??[],e.Request[t][0].Attribute.push(...r)}};var Nd=i(async(n,e,t)=>{f("policy.inbound.basic-auth");let r=n.headers.get("Authorization"),o="basic ",s=i(l=>T.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!r)return await s("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await s("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let m=d.substring(0,p),h=d.substring(p+1),I=t.accounts.find(b=>b.username===m&&b.password===h);return I||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 er(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}i(er,"extractDateElements");function uu(n,e){return new Date(n,e+1,0).getDate()}i(uu,"getDaysInMonth");function Ti(n,e){return n<=e?e-n:6-n+e+1}i(Ti,"getDaysBetweenWeekdays");var tr=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=uu(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(m=>m>=d)??this.weekdays[0]:this.reversed.weekdays.find(m=>m<=d)??this.reversed.weekdays[0];if(p!==void 0){let m=e==="next"?Ti(d,p):Ti(p,d);l=e==="next"?o+m:o-m,(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=er(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 m=this.findAllowedTime("next",t);if(m!==void 0)return new Date(u,c,d,m.hour,m.minute,m.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=er(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 m=this.findAllowedTime("prev",t);if(m!==void 0)return new Date(u,c,d,m.hour,m.minute,m.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}=er(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},Md={min:0,max:59},qd={min:0,max:23},Ud={min:1,max:31},Hd={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"}},$d={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},Zd={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 1 *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@hourly":"0 * * * *","@minutely":"* * * * *"};function lt(n,e){let t=new Set;if(n==="*"){for(let d=e.min;d<=e.max;d=d+1)t.add(d);return t}let r=n.split(",");if(r.length>1)return r.forEach(d=>{lt(d,e).forEach(m=>t.add(m))}),t;let o=i(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${n}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${n}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),s=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(s===null)return t.add(o(n)),t;let a=s[1]==="*"?e.min:o(s[3]),u=s[1]==="*"?e.max:o(s[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=s[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}i(lt,"parseElement");function vi(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=Zd[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 tr({seconds:lt(t,Dd),minutes:lt(r,Md),hours:lt(o,qd),days:lt(s,Ud),months:new Set(Array.from(lt(a,Hd)).map(c=>c-1)),weekdays:new Set(Array.from(lt(u,$d)).map(c=>c%7))})}i(vi,"parseCronExpression");var Ci=class extends ae{static{i(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),f("policy.inbound.brownout"),W(e,t).optional("problem","object"),e.problem&&W(e.problem,t,"policy","problem").optional("detail","string").optional("status","string").optional("title","string"),typeof e.cronSchedule!="string"&&!(typeof e.cronSchedule=="object"&&Array.isArray(e.cronSchedule)&&!e.cronSchedule.some(r=>typeof r!="string")))throw new g(`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=[vi(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>vi(r))}async handler(e,t){let r=new Date;if(r.setSeconds(0),r.setMilliseconds(0),this.crons.some(s=>s.matchDate(r))){let s=T.getProblemFromStatus(this.options.problem?.status??400,{detail:"This API is performing a scheduled brownout in advance of its pending deprecation. Please upgrade to a later version.",...this.options.problem});return T.format(s,e,t)}return e}};var Fd=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function jd(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(jd,"digestMessage");var zd=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 jd(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 Bd(n,e,t,r){f("policy.inbound.caching");let o=await ie(r,t.cacheId,t),s=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await zd(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 m=t?.expirationSecondsTtl??60,h=new Response(p.body,p);Fd.forEach(I=>h.headers.delete(I)),h.headers.set("cache-control",`s-maxage=${m}`),e.waitUntil(s.put(u,h))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}i(Bd,"CachingInboundPolicy");var Gd=i(async(n,e,t,r)=>{if(f("policy.inbound.change-method"),!t.method)throw new g(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new ee(n,{method:t.method})},"ChangeMethodInboundPolicy");var Vd=i(async(n,e,t)=>{f("policy.inbound.clear-headers");let r=[...t.exclude??[]],o=new Headers;return r.forEach(a=>{let u=n.headers.get(a);u&&o.set(a,u)}),new ee(n,{headers:o})},"ClearHeadersInboundPolicy");var Wd=i(async(n,e,t,r)=>{f("policy.outbound.clear-headers");let o=[...r.exclude??[]],s=new Headers;return o.forEach(u=>{let c=n.headers.get(u);c&&s.set(u,c)}),new Response(n.body,{headers:s,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var Jd=i(async(n,e,t,r)=>{f("policy.inbound.clerk-jwt-auth");let o=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),s=new URL(o);return s.pathname="/.well-known/jwks.json",Ee(n,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var Kd=i(async(n,e,t,r)=>{if(f("policy.inbound.cognito-jwt-auth"),!t.userPoolId)throw new g("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new g("region must be set in the options for CognitoJwtInboundPolicy");return Ee(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 nr=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},Si=class extends nr{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Oi=class extends nr{static{i(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function Qd(n,e){if(Gs(n))throw new Si(e)}i(Qd,"throwIfUndefinedOrNull");function cu(n,e){if(Qd(n,e),!Te(n))throw new Oi(e,"string")}i(cu,"throwIfNotString");var Ai=class{static{i(this,"InMemoryRateLimitClient")}keyValueStore;constructor(){this.keyValueStore=new Map}getCountAndUpdateExpiry(e,t){let o=Math.floor(t*60),s=Date.now()+o*1e3,a=this.keyValueStore.get(e);a?Date.now()>a.expiresAt?this.keyValueStore.set(e,{value:1,expiresAt:s}):this.keyValueStore.set(e,{value:a.value+1,expiresAt:a.expiresAt}):this.keyValueStore.set(e,{value:1,expiresAt:s});let u=this.keyValueStore.get(e);return Promise.resolve({count:u.value,ttlSeconds:Math.round((u.expiresAt-Date.now())/1e3)})}multiIncrement(e,t){throw new Error("In memory complex rate limits are not currently supported.")}multiCount(e,t){throw new Error("In memory complex rate limits are not currently supported.")}setQuota(e,t,r){throw new Error("In memory quotas are not currently supported.")}getQuota(e,t){throw new Error("In memory quotas are not currently supported.")}},Yd=500,ki=class{constructor(e){this.clientUrl=e}static{i(this,"RemoteRateLimitClient")}static instance;async fetch({url:e,body:t,method:r,requestId:o}){cu(e,"url");let s=new AbortController;setTimeout(()=>{s.abort()},Yd);let a,u=new Headers({"content-type":"application/json"});De(u,o);try{a=await $.fetch(`${this.clientUrl}${e}`,{method:r,body:t,signal:s.signal,headers:u})}catch(l){throw console.error("Rate limit service timed out",l),new Y("Rate limiting service failed.",{cause:l})}let c=a.headers.get("Content-Type")?.includes("application/json")?await a.json():await a.text();if(a.ok)return c;throw a.status===401?new Y("Rate limiting service failed with 401: Unauthorized"):new Y(`Rate limiting service failed with (${a.status})`)}async multiCount(e,t){return(await this.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async multiIncrement(e,t){return(await this.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async getCountAndUpdateExpiry(e,t,r){let o=Math.floor(t*60);return await this.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:o,key:e}),requestId:r})}async getQuota(e,t){let r=await ct(e);return await this.fetch({url:`/quota/${r}`,method:"GET",requestId:t})}async setQuota(e,t,r){let o=await ct(e);await this.fetch({url:`/quota/${o}`,method:"POST",body:JSON.stringify(t),requestId:r})}},Tt;function nt(n,e){let{redisURL:t,authApiJWT:r}=y.instance;if(Tt)return Tt;if(!r)return e.info("Using in-memory rate limit client for local development."),Tt=new Ai,Tt;if(!Te(t))throw new Y(`RateLimitClient used in policy '${n}' - rate limit service not configured`);if(!Te(r))throw new Y(`RateLimitClient used in policy '${n}' - rate limit service not configured`);return Tt=new ki(t),Tt}i(nt,"getRateLimitClient");var Xd=i(n=>{let e=n.headers.get("x-real-ip")??n.headers.get("true-client-ip")??n.headers.get("cf-connecting-ip");if(e)return e;let t=n.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP");function vt(n,e){return{function:rp(e,"RateLimitInboundPolicy",n),user:tp,ip:ep,all:np}[e.rateLimitBy??"ip"]}i(vt,"getRateLimitByFunctions");var ep=i(async n=>({key:`ip-${Xd(n)}`}),"getIP"),tp=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),np=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll");function rp(n,e,t){let r;if(n.rateLimitBy==="function"){if(!n.identifier)throw new g(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new g(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new g(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=n.identifier.module[n.identifier.export],!r||typeof r!="function")throw new g(`${e} '${t}' - Custom rate limit function must be a valid function`)}return i(async(s,a,u)=>{let c=await r(s,a,u);if(!c||typeof c!="object"){let l=`${e} '${u}' - Custom rate limit function must return a valid object.`;throw a.log.error(l),new k(l)}if(!("key"in c)){let l=`${e} '${u}' - Custom rate limit function must return a valid key property.`;throw a.log.error(l,c),new k(l)}if(typeof c.key!="string"){let l=`${e} '${u}' - Custom rate limit function must return a valid key property of type string. Received type '${typeof c.key}'`;throw a.log.error(l),new k(l)}return c},"outerFunction")}i(rp,"wrapUserFunction");var Ct="Retry-After";var lu=be("zuplo:policies:ComplexRateLimitInboundPolicy"),Li=Symbol("complex-rate-limit-counters"),_i=class n extends ae{static{i(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let r=oe.get(e,Li)??{};Object.assign(r,t),oe.set(e,Li,t)}static getIncrements(e){return oe.get(e,Li)??{}}constructor(e,t){super(e,t),f("policy.inbound.complex-rate-limit-inbound"),W(e,t).required("rateLimitBy","string").required("timeWindowMinutes","number").required("limits","object").optional("headerMode","string").optional("throwOnFailure","boolean").optional("mode","string").optional("identifier","object"),e.identifier&&W(e.identifier,t,"policy","identifier").required("export","string").required("module","object");for(let[r,o]of Object.entries(e.limits))if(typeof o!="number")throw new g(`ComplexRateLimitInboundPolicy '${this.policyName}' - The value of the limits must be numbers. The limit ${r} is set to type '${typeof e}'.`)}async handler(e,t){let r=Date.now(),o=J.getLogger(t),s=nt(this.policyName,o),a=i((c,l)=>{if(this.options.throwOnFailure)throw new Y(c,{cause:l});o.error(c,l)},"throwOrLog"),u=i((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[Ct]=l.toString()),T.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l=await vt(this.policyName,this.options)(e,t,this.policyName),d=y.instance.isTestMode||y.instance.isWorkingCopy?y.instance.build.BUILD_ID:"",p=Object.assign({},this.options.limits,l.limits),m=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;t.addResponseSendingFinalHook(async()=>{try{let E=n.getIncrements(t);lu(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(E)}`);let L=Object.entries(p).map(([Z])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${Z}`,ttlSeconds:m,increment:E[Z]??0})),O=s.multiIncrement(L,t.requestId);t.waitUntil(O),await O}catch(E){a(E.message,E)}});let h=Object.entries(p).map(([E,L])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${E}`,ttlSeconds:m,limit:L})),I=await s.multiCount(h,t.requestId);return op(I,h).length>0?u(this.options.headerMode??"retry-after",m):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-r;lu(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function op(n,e){let t=[];for(let r of n){let o=e.find(s=>s.key===r.key)?.limit||0;r.count>=o&&t.push(r)}return t}i(op,"findOverLimits");var ip=i(async(n,e,t,r)=>{if(f("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new g(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=ge.instance,s=Wt(t.policies,o?.routeData.policies);return no(s)(n,e)},"CompositeInboundPolicy");var sp=i(async(n,e,t,r,o)=>{if(f("policy.outbound.composite"),!r.policies||r.policies.length===0)throw new g(`CompositeOutboundPolicy '${o}' must have valid policies defined`);let s=ge.instance,a=Jt(r.policies,s?.routeData.policies);return ro(a)(n,e,t)},"CompositeOutboundPolicy");var ap=i(async(n,e,t,r)=>{f("policy.inbound.curity-phantom-token-auth");let o=n.headers.get("Authorization");if(!o)return T.unauthorized(n,e,{detail:"No authorization header"});let s=up(o);if(!s)return T.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await ie(r,void 0,t),u=new re(a,e),c=await u.get(s);if(!c){let l=await $.fetch(t.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${t.clientId}:${t.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(s,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),T.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):T.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function up(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(up,"getToken");var cp=i(async(n,e,t,r)=>(f("policy.inbound.firebase-jwt-auth"),W(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),Ee(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 lp=i(async(n,e,t)=>{f("policy.inbound.form-data-to-json");let r="application/x-www-form-urlencoded",o="multipart/form-data",s=n.headers.get("content-type")?.toLowerCase();if(!s||![o,r].includes(s))return t&&t.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):n;let a=await n.formData();if(t&&t.optionalHoneypotName&&a.get(t.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(n.headers);return c.set("content-type","application/json"),c.delete("content-length"),new ee(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var St="__unknown__",dp=i(async(n,e,t,r)=>{f("policy.inbound.geo-filter");let o={allow:{countries:At(t.allow?.countries,"allow.countries",r),regionCodes:At(t.allow?.regionCodes,"allow.regionCode",r),asns:At(t.allow?.asns,"allow.asOrganization",r)},block:{countries:At(t.block?.countries,"block.countries",r),regionCodes:At(t.block?.regionCodes,"block.regionCode",r),asns:At(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??St,a=e.incomingRequestProperties.regionCode?.toLowerCase()??St,u=e.incomingRequestProperties.asn?.toString()??St,c=o.ignoreUnknown&&s===St,l=o.ignoreUnknown&&a===St,d=o.ignoreUnknown&&u===St,p=o.allow.countries,m=o.allow.regionCodes,h=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||m.length>0&&!m.includes(a)&&!l||h.length>0&&!h.includes(u)&&!d)return Ot(n,e,r,s,a,u);let I=o.block.countries,b=o.block.regionCodes,E=o.block.asns;return I.length>0&&I.includes(s)&&!c||b.length>0&&b.includes(a)&&!l||E.length>0&&E.includes(u)&&!d?Ot(n,e,r,s,a,u):n},"GeoFilterInboundPolicy");function Ot(n,e,t,r,o,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${s}')`),T.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:s}})}i(Ot,"blockedResponse");function At(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 g(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}i(At,"toLowerStringArray");var pp=i(async(n,e,t)=>{f("policy.inbound.jwt-scope-validation");let r=n.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(r,t.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var mp=i(async(n,e,t,r)=>{f("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return Ni(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 Ni(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(m=>{a.push({responseName:u,contentName:l,exampleName:m,exampleValue:d[m]})})})}),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 du(a[u])}else return a.length>0?du(a[0]):Ni(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 du(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(du,"generateResponse");var Ni=i((n,e,t,r)=>{let o=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${r}`;return T.internalServerError(e,t,{detail:o})},"getProblemDetailResponse");var gp="Incoming",fp={logRequestBody:!0,logResponseBody:!0};function pu(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}i(pu,"headersToObject");function mu(){return new Date().toISOString()}i(mu,"timestamp");var Di=new WeakMap,hp={};function yp(n,e){let t=Di.get(n);t||(t=hp);let r=Object.assign({...t},e);Di.set(n,r)}i(yp,"setMoesifContext");async function gu(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(gu,"readBody");var bp={},Mi;function fu(){if(!Mi)throw new k("Invalid State - no _lastLogger");return Mi}i(fu,"getLastLogger");function wp(n){let e=bp[n];return e||(e=new K("moesif-inbound",100,async t=>{let r=JSON.stringify(t);fu().debug("posting",r);let o=await $.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||fu().error({status:o.status,body:await o.text()})})),e}i(wp,"getDispatcher");async function Rp(n,e,t,r){f("policy.inbound.moesif-analytics"),Mi=e.log;let o=mu(),s=Object.assign(fp,t);if(!s.applicationId)throw new g(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await gu(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=wp(s.applicationId),d=n.headers.get("true-client-ip"),p=Di.get(e)??{},m={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:pu(n.headers)},h=s.logResponseBody?await gu(u,e):void 0,I={time:mu(),status:u.status,headers:pu(u.headers),body:h},b={request:m,response:I,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:gp};l.enqueue(b),e.waitUntil(l.waitUntilFlushed())}),n}i(Rp,"MoesifInboundPolicy");async function hu(n,e,t,r){let o=J.getLogger(n),{authApiJWT:s,meteringServiceUrl:a}=y.instance,u;try{let l=await $.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription`,l)}let c=u&&u.data&&u.data.length>0?u.data:void 0;return c&&c.length>1?c.sort((d,p)=>d.createdOn>p.createdOn?-1:1)[0]:c&&c[0]}i(hu,"loadSubscription");async function yu(n,e,t,r,o){let{authApiJWT:s,meteringServiceUrl:a}=y.instance,u=J.getLogger(n);try{let c=await $.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`,c)}}i(yu,"consumeSubcriptionQuotas");var Pp=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function rr(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 g(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 g?new g(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}i(rr,"validateMeters");function bu(n,e){if(n)try{if(n.length===0)throw new g("Must set valid subscription statuses");let t=je(n),r=[];for(let o of t)Pp.has(o)||r.push(o);if(r.length>0)throw new g(`Found the following invalid statuses: ${r.join(", ")}`);return n}catch(t){throw t instanceof g?new g(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}i(bu,"parseAllowedSubscriptionStatuses");function wu(n,e){let t={},r={};for(let o in e)n.hasOwnProperty(o)?t[o]=e[o]:r[o]=e[o];return{metersInSubscription:t,metersNotInSubscription:r}}i(wu,"compareMeters");var qi=class extends ae{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return oe.get(e,Zt)}static setMeters(e,t){rr(t,"setMeters");let r=oe.get(e,Ft)??{};Object.assign(r,t),oe.set(e,Ft,r)}constructor(e,t){super(e,t),f("policy.inbound.monetization")}async handler(e,t){W(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let r=this.options.allowRequestsOverQuota??!1,o=We(this.options.meterOnStatusCodes),s=oe.get(t,Ft),a={...this.options.meters,...s};rr(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=bu(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(b,E,L)=>{let O=oe.get(L,Zt);if((this.options.allowRequestsWithoutSubscription??!1)&&!O){L.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(ye.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=ye.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let M=oe.get(L,Ft),F={...this.options.meters,...M};if(rr(F,this.policyName),o.includes(b.status)&&O&&F){L.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${O.id}' with meters '${JSON.stringify(F)} on response status '${b.status}'`);let{metersInSubscription:S,metersNotInSubscription:H}=wu(O.meters,F);if(H&&Object.keys(H).length>0){let V=Object.keys(H);L.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${V}'`)}await yu(L,O.id,this.policyName,this.options.bucketId,S)}});let l=e.user;if(!l)return u?e:T.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(ye.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=ye.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await hu(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:T.unauthorized(e,t,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return t.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),T.unauthorized(e,t,{detail:"No valid subscription found"});c.includes(p.status)&&(t.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),oe.set(t,Zt,p));let m=oe.get(t,Zt);if(!m)return u?e:(t.log.warn("Subscription is not available for user"),T.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(m&&Object.keys(m.meters).length===0)return t.log.error(`Quota is not set up for subscription '${m.id}'`),T.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let I=Object.keys(a).filter(b=>!Object.keys(m.meters).includes(b));if(I.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${I.join(", ")}`),T.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${I.join(", ")}`,title:"Quota Exceeded"});for(let b of Object.keys(a))if(m.meters[b].available<=0&&!r)return T.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${b}'`,title:"Quota Exceeded"});return e}};async function or(n,e){let t=new URLSearchParams({client_id:n.clientId,client_secret:n.clientSecret,grant_type:"client_credentials"});n.scope&&t.append("scope",n.scope),n.audience&&t.append("audience",n.audience);let r=await we({retries:n.retries?.maxRetries??3,retryDelayMs:n.retries?.delayMs??10},n.tokenEndpointUrl,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let s=await r.text();e.log.error(`Error getting token from identity provider. Status: ${r.status}`,s)}catch{}throw new k("Error getting token from identity provider.")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new k("Response returned from identity provider is not in the expected format.")}i(or,"getClientCredentialsAccessToken");var kt=class extends Error{constructor(t,r,o){super(r,o);this.code=t}static{i(this,"OpenFGAError")}},ir=class{static{i(this,"BaseOpenFGAClient")}apiUrl;storeId;authorizationModelId;constructor(e){this.apiUrl=e.apiUrl,this.storeId=e.storeId,this.authorizationModelId=e.authorizationModelId}getStoreId(e={},t=!1){let r=e?.storeId||this.storeId;if(!t&&!r)throw new g("storeId is required");return r}getAuthorizationModelId(e={}){return e?.authorizationModelId||this.authorizationModelId}async get(e,t){return this.fetch(e,"GET",t)}async put(e,t,r){return this.fetch(e,"PUT",r,t)}post(e,t,r){return this.fetch(e,"POST",r,t)}async fetch(e,t,r,o){let s=new Headers(r.headers||{});s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.set("User-Agent",y.instance.systemUserAgent);let a=`${this.apiUrl}${e}`,u=new Request(a,{method:t,headers:s,body:o?JSON.stringify(o):void 0}),c=await $.fetch(u);if(c.status!==200){let l;try{l=await c.json()}catch{}throw!l||!l.code||!l.message?new kt("unknown",`Unknown error. Status: ${c.status}`):new kt(l.code,l.message)}return c.json()}};function cn(n,e,t){!n[e]&&t&&(n[e]=t)}i(cn,"setHeaderIfNotSet");var Ru="X-OpenFGA-Client-Method",Pu="X-OpenFGA-Client-Bulk-Request-Id",ln=class extends ir{static{i(this,"OpenFGAClient")}async check(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/check`,{tuple_key:{user:e.user,relation:e.relation,object:e.object},context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]},authorization_model_id:this.getAuthorizationModelId(t)},t)}async batchCheck(e,t={}){let{headers:r={}}=t;return cn(r,Ru,"BatchCheck"),cn(r,Pu,crypto.randomUUID()),{responses:await Promise.all(e.map(async s=>this.check(s,Object.assign({},t,r)).then(a=>(a._request=s,a)).catch(a=>{if(a instanceof kt)throw a;return{allowed:void 0,error:a,_request:s}})))}}async expand(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/expand`,{authorization_model_id:this.getAuthorizationModelId(t),tuple_key:e},t)}async listObjects(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-objects`,{authorization_model_id:this.getAuthorizationModelId(t),user:e.user,relation:e.relation,type:e.type,context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]}},t)}async listRelations(e,t={}){let{user:r,object:o,relations:s,contextualTuples:a,context:u}=e,{headers:c={}}=t;if(cn(c,Ru,"ListRelations"),cn(c,Pu,crypto.randomUUID()),!s?.length)throw new Error("When calling listRelations, at least one relation must be passed in the relations field");let l=await this.batchCheck(s.map(p=>({user:r,relation:p,object:o,contextualTuples:a,context:u})),Object.assign({},t,c)),d=l.responses.find(p=>p.error);if(d)throw d.error;return{relations:l.responses.filter(p=>p.allowed).map(p=>p._request.relation)}}async listUsers(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-users`,{authorization_model_id:this.getAuthorizationModelId(t),relation:e.relation,object:e.object,user_filters:e.user_filters,context:e.context,contextual_tuples:e.contextualTuples||[]},t)}};var Iu=Symbol("openfga-authz-context-data"),Lt=class extends ae{static{i(this,"BaseOpenFGAAuthZInboundPolicy")}client;authorizer;cache;static setContextChecks(e,t){let r=Array.isArray(t)?t:[t];oe.set(e,Iu,r)}constructor(e,t){if(super(e,t),W(e,t).required("apiUrl","string").optional("storeId","string").optional("authorizationModelId","string"),!e.credentials)throw new g(`${this.policyType} '${this.policyName}' - The 'credentials' option is required.`);if(e.credentials.method==="client-credentials")W(e.credentials,t).required("clientId","string").required("clientSecret","string").required("oauthTokenEndpointUrl","string").optional("apiAudience","string");else if(e.credentials.method==="api-token")W(e.credentials,t).required("token","string").optional("headerName","string").optional("headerValuePrefix","string");else if(e.credentials.method==="header")W(e.credentials,t).optional("headerName","string");else if(e.credentials.method!=="none")throw new g(`${this.policyType} '${this.policyName}' - The 'credentials.method' option is invalid. It must be set to either 'none', 'api-token', 'client-credentials', or 'header'.`);this.authorizer=this.getAuthorizer(e.credentials),this.client=new ln({apiUrl:e.apiUrl,storeId:e.storeId,authorizationModelId:e.authorizationModelId})}async handler(e,t){if(!this.cache){let a=await ie(this.policyName,void 0,this.options);this.cache=new re(a,t)}let r=i(a=>this.options.allowUnauthorizedRequests?e:T.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=oe.get(t,Iu);if(!o||o.length===0)throw new k(`${this.policyType} '${this.policyName}' - No checks found in the context.`);let s=await this.authorizer(e,t);try{t.log.debug("OpenFGA checks",o);let a=await this.client.batchCheck(o,{headers:s});return t.log.debug("OpenFGA Response",a),a.responses.every(u=>u.allowed)?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling OpenFGA service`,a),T.internalServerError(e,t)}}getAuthorizer(e){if(e.method==="none")return async()=>({});if(e.method==="header")return async t=>{let r=e.headerName??"Authorization",o=t.headers.get(r);if(!o)throw new Y(`${this.policyType} '${this.policyName}' - The header '${r}' is missing.`);return{[r]:o}};if(e.method==="api-token")return async()=>({[e.headerName??"Authorization"]:`${e.headerValuePrefix??"Bearer "} ${e.token}`});if(e.method==="client-credentials")return async(t,r)=>{let o=await this.cache?.get("client_credentials_token");if(o)return{Authorization:`Bearer ${o}`};let s=await or({tokenEndpointUrl:e.oauthTokenEndpointUrl,clientId:e.clientId,clientSecret:e.clientSecret,audience:e.apiAudience},r);return this.cache?.put("client_credentials_token",s.access_token,s.expires_in),{Authorization:`Bearer ${s.access_token}`}};throw new k("Invalid state for credentials method is not valid. This should not happen.")}};var Eu=["us1","eu1","au1"],Ui=class extends Lt{static{i(this,"OktaFGAAuthZInboundPolicy")}constructor(e,t){if(!Eu.includes(e.region))throw new g(`OktaFGAAuthZInboundPolicy '${t}' - The 'region' option is invalid. Must be one of ${Eu.join(", ")}.`);let r={...e,apiUrl:`https://api.${e.region}.fga.dev`,credentials:{method:"client-credentials",oauthTokenEndpointUrl:"https://fga.us.auth0.com/oauth/token",clientId:e.credentials.clientId,clientSecret:e.credentials.clientSecret,apiAudience:`https://api.${e.region}.fga.dev/`}};super(r,t),f("policy.inbound.oktafga-authz")}};var Ip=i(async(n,e,t,r)=>(f("policy.inbound.okta-jwt-auth"),Ee(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"OktaJwtInboundPolicy");var Hi=class extends Lt{static{i(this,"OpenFGAAuthZInboundPolicy")}constructor(e,t){super(e,t),f("policy.inbound.openfga-authz")}};import{importSPKI as Ep}from"jose";var $i,xp=i(async(n,e,t,r)=>{if(f("policy.inbound.propel-auth-jwt-auth"),!$i)try{$i=await Ep(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return Ee(n,e,{issuer:t.authUrl,secret:$i,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Zi="quota-inbound-policy-f307056c-8c00-4f2c-b4ac-c0ac7d04eca0",xu="quota-usage-2017e968-4de8-4a63-8951-1e423df0d64b";var Fi=class n extends ae{static{i(this,"QuotaInboundPolicy")}constructor(e,t){super(e,t),f("policy.inbound.quota")}async handler(e,t){let r=this.options.debug??!1;t.log.debug({debug:r}),W(this.options,this.policyName).required("period","string").required("quotaBy","string").optional("quotaAnchorMode","string").optional("allowances","object"),n.setMeters(t,{requests:1});let o=J.getLogger(t);try{let s=Tp(this.options,this.policyName),a=s.functions.getAnchorDate(e,t,this.policyName),u=s.functions.getQuotaDetail(e,t,this.policyName),[c,l]=await Promise.all([a,u]),d=vp(l.key,this.policyName);r&&t.log.debug(`QuotaInboundPolicy: key - '${d}'`);let p=nt(this.policyName,o),m=await p.getQuota(d,t.requestId);n.#e(t,this.policyName,m),r&&t.log.debug("QuotaInboundPolicy: quotaResult",m),c&&new Date(m.anchorDate).getTime()!==c.getTime()&&t.log.warn(`QuotaInboundPolicy '${this.policyName}' provided anchorDate ('${c}') did not match the stored, immutable anchorDate ('${m.anchorDate}')`);let h=Object.assign({},s.defaultAllowances);Object.assign(h,l.allowances);let I=[],b="";if(Object.entries(h).forEach(([E,L])=>{r&&(b+=`${E} - allowed: ${L} value: ${m.meters[E]??0}
90
- `),(m.meters[E]??0)>=L&&I.push(E)}),r&&t.log.debug("QuotaInboundPolicy: debugTable",b),I.length>0)return T.tooManyRequests(e,t,{detail:`Quota exceeded for meters '${I.join(", ")}'`});t.addResponseSendingFinalHook(async(E,L,O)=>{if(r&&O.log.debug(`QuotaInboundPolicy: backend response - ${E.status}: ${E.statusText}`),!s.quotaOnStatusCodes.includes(E.status))return;let Z=oe.get(O,Zi),M={config:{period:s.period,anchorDate:c?.toISOString()??""},increments:Z};r&&O.log.debug("QuotaInboundPolicy: setQuotaDetails",M);let F=p.setQuota(d,M,O.requestId);O.waitUntil(F)})}catch(s){o.error(s),t.log.error(s)}return e}static setMeters(e,t){let r=oe.get(e,Zi)??{};Object.assign(r,t),oe.set(e,Zi,r)}static getUsage(e,t){let r=oe.get(e,`${xu}-${t}`);if(r===void 0)throw new k(`QuotaInboundPolicy.getUsage was called for policy named '${t}' but the policy itself has not yet executed.`);return r}static#e(e,t,r){oe.set(e,`${xu}-${t}`,r)}};function Tp(n,e){let t=i(async s=>({key:`user-1385b4e8-800f-488e-b089-c197544e5801-${s.user?.sub}`,allowances:n.allowances??{}}),"getQuotaDetail"),r=i(async()=>{},"getAnchorDate");if(n.quotaBy==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getQuotaDetailExport===void 0)throw new g(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getQuotaDetailExport' is required when 'quotaBy' is 'function'`);t=n.identifier.module[n.identifier.getQuotaDetailExport]}if(n.quotaAnchorMode==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getAnchorDateExport===void 0)throw new g(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getAnchorDateExport' is required when 'quotaAnchorMode' is 'function'`);r=n.identifier.module[n.identifier.getAnchorDateExport]}return{period:n.period,quotaBy:n.quotaBy??"user",quotaAnchorMode:n.quotaAnchorMode??"first-api-call",quotaOnStatusCodes:We(n.quotaOnStatusCodes??"200-299"),defaultAllowances:Object.assign({},n.allowances),functions:{getQuotaDetail:t,getAnchorDate:r}}}i(Tp,"validateAndParseOptions");function vp(n,e){return encodeURIComponent(`${e}-${n}`)}i(vp,"processKey");var Tu=be("zuplo:policies:RateLimitInboundPolicy"),vu=i(async(n,e,t,r)=>{let o=J.getLogger(e),s=i((F,S)=>{let H={};return(!F||F==="retry-after")&&(H[Ct]=S.toString()),T.tooManyRequests(n,e,void 0,H)},"rateLimited"),u=await vt(r,t)(n,e,r),c=u.key,l=u.requestsAllowed??t.requestsAllowed,d=u.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",m=nt(r,o),I=`rate-limit${y.instance.isTestMode?y.instance.build.BUILD_ID:""}/${r}/${c}`,b=await ie(r,void 0,t),E=new re(b,e),L=m.getCountAndUpdateExpiry(I,d,e.requestId),O;i(async()=>{let F=await L;if(F.count>l){let S=Date.now()+F.ttlSeconds*1e3;E.put(I,S,F.ttlSeconds),Tu(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${I}' (async mode)`),O=s(p,F.ttlSeconds)}},"asyncCheck")();let M=await E.get(I);if(M!==void 0&&M>Date.now()){Tu(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${I}' (async mode)`);let F=Math.round((M-Date.now())/1e3);return s(p,F)}return e.addResponseSendingHook(async F=>O??F),n},"AsyncRateLimitInboundPolicyImpl");function ji(n,e){if(n===null)throw new Error(`RateLimitInboundPolicy - Invalid ${e} value: null`);if(n==="")throw new Error(`RateLimitInboundPolicy - Invalid ${e} value: empty string`);if(typeof n=="number")return n;if(typeof n!="number"){let t=Number(n);if(isNaN(t)||!Number.isInteger(t))throw new Error(`RateLimitInboundPolicy - Invalid ${e} value not of type integer: ${n}`);return t}throw new Error(`RateLimitInboundPolicy - Invalid ${e} value: ${n}`)}i(ji,"convertToNumber");var Cu=be("zuplo:policies:RateLimitInboundPolicy"),Cp="strict",Su=i(async(n,e,t,r)=>{if(f("policy.inbound.rate-limit"),(t.mode??Cp)==="async")return vu(n,e,t,r);let s=Date.now(),a=J.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[Ct]=d.toString()),T.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await vt(r,t)(n,e,r),p=d.key,m=ji(d.requestsAllowed??t.requestsAllowed,"requestsAllowed"),h=ji(d.timeWindowMinutes??t.timeWindowMinutes,"timeWindowMinutes"),I=t.headerMode??"retry-after",b=nt(r,a),L=`rate-limit${y.instance.isTestMode||y.instance.isWorkingCopy?y.instance.build.BUILD_ID:""}/${r}/${p}`,O=await b.getCountAndUpdateExpiry(L,h,e.requestId);return O.count>m?(Cu(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${L}' (strict mode)`),c(I,O.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-s;Cu(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var zi;function Ou(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}i(Ou,"headersToNameValuePairs");function Sp(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}i(Sp,"queryToNameValueParis");function Op(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}i(Op,"parseIntOrUndefined");var Au={};async function Ap(n,e,t,r){f("policy.inbound.readme-metrics");let o=new Date,s=Date.now();return zi||(zi={name:"zuplo",version:y.instance.build.ZUPLO_VERSION,comment:`zuplo/${y.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?Fe(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?Fe(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:y.instance.isWorkingCopy||y.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:zi,entries:[{startedDateTime:o.toISOString(),time:Date.now()-s,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:Ou(n.headers),queryString:Sp(n.query)},response:{status:a.status,statusText:a.statusText,headers:Ou(a.headers),content:{size:Op(n.headers.get("content-length"))}}}]}}},d=Au[t.apiKey];if(!d){let p=t.apiKey;d=new K("readme-metering-inbound-policy",10,async m=>{try{let h=t.url??"https://metrics.readme.io/request",I=await $.fetch(h,{method:"POST",body:JSON.stringify(m),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});I.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${I.status}: '${await I.text()}'`)}catch(h){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${h.message}'`),h}}),Au[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}i(Ap,"ReadmeMetricsInboundPolicy");var kp=i(async(n,e,t,r)=>{f("policy.inbound.remove-headers");let o=t?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new g(`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 ee(n,{headers:s})},"RemoveHeadersInboundPolicy");var Lp=i(async(n,e,t,r,o)=>{f("policy.outbound.remove-headers");let s=r?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new g(`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 _p=i(async(n,e,t,r)=>{f("policy.inbound.remove-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length===0)throw new g(`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 ee(s.toString(),n)},"RemoveQueryParamsInboundPolicy");var Np=i(async(n,e,t,r)=>{f("policy.outbound.replace-string");let o=await n.text(),s=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(s,r.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var ku=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Dp=i(async(n,e,t)=>{f("policy.inbound.request-size-limit");let r=t.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(n.method))return n;let o=n.headers.get("content-length"),s=o!==null?parseInt(o):void 0;return s&&!isNaN(s)&&s>t.maxSizeInBytes?ku():s&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?ku():n},"RequestSizeLimitInboundPolicy");var _t=i(n=>{let e=n.route.raw();return e.parameters?e.parameters:[]},"getParametersForOperation"),Nt=i((n,e,t,r,o)=>{let s=[],a=!0,u=[];return n.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,s.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=cr(t,r,o,c.name),p=ge.instance.schemaValidator[d],m=p(e[c.name]),h=Bi(p.errors);m||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${h.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),Le=i((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),_e=i(n=>n==="log-only"||n==="reject-and-log","shouldLog"),Ne=i(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),Bi=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 Lu(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(h){let I=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,b=T.badRequest(e,n,{detail:`${I}, see errors property for more details`,errors:`${h}`});if(_e(t.validateBody)&&Le(n,t.logLevel??"info",I,[r],h),Ne(t.validateBody))return b}if(!e.headers.get("Content-Type")){let h=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,I=T.badRequest(e,n,{detail:h});return _e(t.validateBody)&&Le(n,t.logLevel??"info",h,[r],[h]),Ne(t.validateBody)?I:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=lr(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")}`,I=T.badRequest(e,n,{detail:h});return _e(t.validateBody)&&Le(n,t.logLevel??"info",h,[r],[h]),Ne(t.validateBody)?I:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Bi(l),m=T.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(_e(t.validateBody)&&Le(n,t.logLevel??"info",d,[r],p),Ne(t.validateBody))return m}i(Lu,"handleBodyValidation");function _u(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=_t(n),s=Nt(o.filter(a=>a.in==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=T.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:s.errors});if(_e(t.validateHeaders)&&Le(n,t.logLevel??"info",a,s.invalidValues,s.errors),Ne(t.validateHeaders))return u}}i(_u,"handleHeadersValidation");function Nu(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=_t(n),o=Nt(r.filter(s=>s.in==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let s="Path parameters validation failed",a=T.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(_e(t.validatePathParameters)&&Le(n,t.logLevel??"info",s,o.invalidValues,o.errors),Ne(t.validatePathParameters))return a}}i(Nu,"handlePathParameterValidation");function Du(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=_t(n),o=Nt(r.filter(s=>s.in==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let s="Query parameters validation failed",a=T.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(_e(t.validateQueryParameters)&&Le(n,t.logLevel??"info",s,o.invalidValues,o.errors),Ne(t.validateQueryParameters))return a}}i(Du,"handleQueryParameterValidation");var Mu=i(async(n,e,t)=>{f("policy.inbound.request-validation");let r=Du(e,n,t);if(r!==void 0||(r=Nu(e,n,t),r!==void 0)||(r=_u(e,n,t),r!==void 0))return r;let o=await Lu(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),Mp=Mu;var qp=i(async(n,e,t,r)=>{if(f("policy.inbound.require-origin"),t.origins===void 0||t.origins.length===0)throw new g(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof t.origins=="string"?t.origins.split(","):t.origins;o=o.map(a=>a.trim());let s=n.headers.get("origin");if(!s||!o.includes(s)){let a=t.failureDetail??"Forbidden";return T.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var Up=i(async(n,e,t)=>(f("policy.inbound.set-body"),new ee(n,{body:t.body})),"SetBodyInboundPolicy");var Hp=i(async(n,e,t,r)=>{f("policy.inbound.set-headers");let o=t.headers;if(!o||!Array.isArray(o)||o.length==0)throw new g(`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 g(`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 ee(n,{headers:s})},"SetHeadersInboundPolicy");var $p=i(async(n,e,t,r,o)=>{f("policy.outbound.set-headers");let s=r.headers;if(!s||!Array.isArray(s)||s.length==0)throw new g(`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 g(`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 Zp=i(async(n,e,t,r)=>{f("policy.inbound.set-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length==0)throw new g(`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 g(`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 ee(s.toString(),n)},"SetQueryParamsInboundPolicy");var Fp=i(async(n,e,t,r,o)=>{if(f("policy.outbound.set-status"),!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new g(`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 jp=i(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),zp=i(async(n,e,t,r)=>{if(f("policy.inbound.sleep"),!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new g(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await jp(t.sleepInMs),n},"SleepInboundPolicy");var Bp=i(async(n,e,t,r)=>{f("policy.inbound.supabase-jwt-auth"),W(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},s=await Ee(n,e,o,r);if(s instanceof Response)return s;if(!(s instanceof ee))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 k(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?T.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var Gp=i(async(n,e,t,r)=>{f("policy.inbound.upstream-azure-ad-service-auth"),W(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await ie(r,void 0,t),s=new re(o,e),a=await s.get(r);if(!a){let u=await Vp(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 Vp(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await we({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 k("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new k("Response returned from Azure AD is not in the expected format.")}i(Vp,"getAccessToken");var qu="https://accounts.google.com/o/oauth2/token",Gi,Wp=i(async(n,e,t,r)=>{f("policy.inbound.upstream-firebase-admin-auth"),W(t,r).required("serviceAccountJson","string"),Gi||(Gi=await Ie.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 ie(r,void 0,t),a=new re(s,e),u=await a.get(r);if(!u){let c=await Ae({serviceAccount:Gi,audience:qu,payload:o}),l=await yt(qu,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new k("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var Jp="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Kp=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Vi,Qp=i(async(n,e,t,r)=>{if(f("policy.inbound.upstream-firebase-user-auth"),W(t,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!t.userId&&!t.userIdPropertyPath)throw new g(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof t.developerClaims<"u"){for(let p in t.developerClaims)if(Object.prototype.hasOwnProperty.call(t.developerClaims,p)){if(Kp.indexOf(p)!==-1)throw new g(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}Vi||(Vi=await Ie.init(t.serviceAccountJson));let s=t.userId;if(!s&&!t.userIdPropertyPath){if(!n.user)throw new k("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new k(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=Fe(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new k(`Unable to determine user from for the policy ${r}`);let a=await ie(r,void 0,t),u=new re(a,e),c={uid:s,claims:o},l=await ct(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await Ae({serviceAccount:Vi,audience:Jp,payload:c}),m=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,h=await fa(m,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!h.idToken)throw new k("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 dn=class{static{i(this,"ZuploServices")}static async getIDToken(e,t){let r=new re("0c13603a-a19f-4f03-a04a-50aa393f7ffa-zuplo-tokens",e),o=await ie("zuplo-token",void 0,t),s=await r.get(o);if(s)return s;let{authClientId:a,authClientSecret:u,developerApiUrl:c,zuploClientAuthBucketId:l}=y.instance;if(!a||!u)throw new k("Zuplo service authentication is not enabled for this deployment. Contact support assistance.");let d=await or({tokenEndpointUrl:`${c}/v1/client-auth/${l}/oauth/token`,clientId:a,clientSecret:u,audience:t?.audience},e);return r.put(o,d.access_token,d.expires_in-300),d.access_token}};var Uu="service-account-id-token",Wi=class extends ae{static{i(this,"UpstreamGcpFederatedAuthInboundPolicy")}cacheName;normalizedWorkloadIdentityProvider;constructor(e,t){super(e,t),f("policy.inbound.upstream-gcp-federated-auth"),W(e,t).required("audience","string").required("serviceAccountEmail","string").required("workloadIdentityProvider","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number").optional("useMemoryCacheOnly","boolean").optional("tokenLifetime","number"),e.workloadIdentityProvider.startsWith("https://iam.googleapis.com/")?this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider.replace("https://iam.googleapis.com/",""):this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider}async handler(e,t){this.cacheName||(this.cacheName=await ie(this.policyName,void 0,this.options));let r;this.options.useMemoryCacheOnly?r=new Me(this.cacheName):r=new re(this.cacheName,t);let o=await r.get(Uu);if(!o){let s=`https://iam.googleapis.com/${this.normalizedWorkloadIdentityProvider}`,a=await dn.getIDToken(t,{audience:s}),u=await ma(this.normalizedWorkloadIdentityProvider,a,{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!u.access_token||!u.expires_in)throw new k("Invalid token response from GCP");let c=u.access_token,l=await ga({serviceAccountEmailOrIdentifier:this.options.serviceAccountEmail,audience:this.options.audience,accessToken:c},{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!l.token)throw new k("Invalid token response from GCP");o=l.token,r.put(Uu,c,3600-(this.options.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${o}`),e}};var Ji,Yp=i(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-jwt"),W(t,r).required("audience","string").required("serviceAccountJson","string"),Ji||(Ji=await Ie.init(t.serviceAccountJson));let o=await Ae({serviceAccount:Ji,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var Hu="https://www.googleapis.com/oauth2/v4/token",Ki,$u=i(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-service-auth"),W(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Ki||(Ki=await Ie.init(t.serviceAccountJson));let o={};if(t.scopes&&t.audience)throw new g("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let c=je(t.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof g?new g(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}t.audience&&(o.target_audience=`${t.audience}`);let s=await ie(r,void 0,t),a;t.useMemoryCacheOnly?a=new Me(s):a=new re(s,e);let u=await a.get(r);if(!u){let c=await Ae({serviceAccount:Ki,audience:Hu,payload:o}),l=await yt(Hu,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new k("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new k("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicyV1");var Zu="https://www.googleapis.com/oauth2/v4/token",Qi,Fu=i(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-service-auth"),W(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=t.expirationOffsetSeconds??300;if(t.scopes&&t.audience)throw new g("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");let s=await ie(r,"v2",t),a;t.useMemoryCacheOnly?a=new Me(s):a=new re(s,e),Re.getContextExtensions(e).addHandlerResponseHook(async(d,p,m)=>{if(d.status===403){let I=`UpstreamGcpServiceAuthInboundPolicy - Handler returned a 403 response. Error: ${d.headers.get("www-authenticate")??"unknown"}. Refreshing GCP token.`;J.getLogger(m).error(I),m.log.error(I),await a.delete(r)}});let c=await a.get(r);return c&&c.expirationTime-o<new Date().getTime()&&(J.getLogger(e).error(`UpstreamGcpServiceAuthInboundPolicy - Expired token returned from cache for policy ${r}`),c=void 0),c&&c.audience!==t.audience&&(J.getLogger(e).error(`UpstreamGcpServiceAuthInboundPolicy - Token with audience ${c.audience} returned from cache for policy ${r} does not match the current audience ${t.audience}`),c=void 0),c||(c=await l()),n.headers.set("Authorization",`Bearer ${c.token}`),n;async function l(){Qi||(Qi=await Ie.init(t.serviceAccountJson));let d={};if(t.scopes)try{let E=je(t.scopes);d.scope=E.join(" ")}catch(E){throw E instanceof g?new g(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${E.message}`):E}t.audience&&(d.target_audience=`${t.audience}`);let p=await Ae({serviceAccount:Qi,audience:Zu,payload:d}),m=await yt(Zu,p,{retries:t.tokenRetries??3,retryDelayMs:10}),h=m.expires_in??3600,I=new Date().getTime()+h*1e3;if(t.audience){if(!m.id_token)throw new k("Invalid token response from GCP");c={token:m.id_token,expirationTime:I,audience:t.audience}}else{if(!m.access_token)throw new k("Invalid token response from GCP");c={token:m.access_token,expirationTime:I,audience:void 0}}let b=h-o;if(b<=0)throw new k(`UpstreamGcpServiceAuthInboundPolicy - Token TTL is less than the expiration offset. TTL: ${b}, expiration offset: ${o}`);return a.put(r,c,b),c}i(l,"retrieveGcpServiceToken")},"UpstreamGcpServiceAuthInboundPolicyV2");var Xp=i(async(n,e,t,r)=>t.version===2?await Fu(n,e,t,r):await $u(n,e,t,r),"UpstreamGcpServiceAuthInboundPolicy");var em=i(async(n,e,t)=>{f("policy.inbound.validate-json-schema");let r=n.clone(),o;try{o=await r.json()}catch{return T.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator.default(o))return n;let{errors:a}=t.validator.default;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 T.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var ju=i(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=i((b,E)=>e(b,"name",{value:E,configurable:!0}),"__name"),o=i((b,E)=>i(function(){return E||(0,b[t(b)[0]])((E={exports:{}}).exports,E),E.exports},"__require"),"__commonJS"),s=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(b){var E={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:i(function(O,Z){return Z},"tagValueProcessor"),attributeValueProcessor:i(function(O,Z){return Z},"attributeValueProcessor"),stopNodes:[],alwaysCreateTextNode:!1,isArray:i(()=>!1,"isArray"),commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:i(function(O,Z,M){return O},"updateTag")},L=r(function(O){return Object.assign({},E,O)},"buildOptions");b.buildOptions=L,b.defaultOptions=E}}),a=o({"node_modules/fast-xml-parser/src/util.js"(b){"use strict";var E=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",L=E+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",O="["+E+"]["+L+"]*",Z=new RegExp("^"+O+"$"),M=r(function(S,H){let V=[],j=H.exec(S);for(;j;){let v=[];v.startIndex=H.lastIndex-j[0].length;let x=j.length;for(let q=0;q<x;q++)v.push(j[q]);V.push(v),j=H.exec(S)}return V},"getAllMatches"),F=r(function(S){let H=Z.exec(S);return!(H===null||typeof H>"u")},"isName");b.isExist=function(S){return typeof S<"u"},b.isEmptyObject=function(S){return Object.keys(S).length===0},b.merge=function(S,H,V){if(H){let j=Object.keys(H),v=j.length;for(let x=0;x<v;x++)V==="strict"?S[j[x]]=[H[j[x]]]:S[j[x]]=H[j[x]]}},b.getValue=function(S){return b.isExist(S)?S:""},b.isName=F,b.getAllMatches=M,b.nameRegexp=O}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(b,E){"use strict";var L=class{static{i(this,"XmlNode")}static{r(this,"XmlNode")}constructor(O){this.tagname=O,this.child=[],this[":@"]={}}add(O,Z){O==="__proto__"&&(O="#__proto__"),this.child.push({[O]:Z})}addChild(O){O.tagname==="__proto__"&&(O.tagname="#__proto__"),O[":@"]&&Object.keys(O[":@"]).length>0?this.child.push({[O.tagname]:O.child,":@":O[":@"]}):this.child.push({[O.tagname]:O.child})}};E.exports=L}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(b,E){var L=a();function O(v,x){let q={};if(v[x+3]==="O"&&v[x+4]==="C"&&v[x+5]==="T"&&v[x+6]==="Y"&&v[x+7]==="P"&&v[x+8]==="E"){x=x+9;let ce=1,X=!1,te=!1,Se="";for(;x<v.length;x++)if(v[x]==="<"&&!te){if(X&&F(v,x))x+=7,[entityName,val,x]=Z(v,x+1),val.indexOf("&")===-1&&(q[j(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(X&&S(v,x))x+=8;else if(X&&H(v,x))x+=8;else if(X&&V(v,x))x+=9;else if(M)te=!0;else throw new Error("Invalid DOCTYPE");ce++,Se=""}else if(v[x]===">"){if(te?v[x-1]==="-"&&v[x-2]==="-"&&(te=!1,ce--):ce--,ce===0)break}else v[x]==="["?X=!0:Se+=v[x];if(ce!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:q,i:x}}i(O,"readDocType"),r(O,"readDocType");function Z(v,x){let q="";for(;x<v.length&&v[x]!=="'"&&v[x]!=='"';x++)q+=v[x];if(q=q.trim(),q.indexOf(" ")!==-1)throw new Error("External entites are not supported");let ce=v[x++],X="";for(;x<v.length&&v[x]!==ce;x++)X+=v[x];return[q,X,x]}i(Z,"readEntityExp"),r(Z,"readEntityExp");function M(v,x){return v[x+1]==="!"&&v[x+2]==="-"&&v[x+3]==="-"}i(M,"isComment"),r(M,"isComment");function F(v,x){return v[x+1]==="!"&&v[x+2]==="E"&&v[x+3]==="N"&&v[x+4]==="T"&&v[x+5]==="I"&&v[x+6]==="T"&&v[x+7]==="Y"}i(F,"isEntity"),r(F,"isEntity");function S(v,x){return v[x+1]==="!"&&v[x+2]==="E"&&v[x+3]==="L"&&v[x+4]==="E"&&v[x+5]==="M"&&v[x+6]==="E"&&v[x+7]==="N"&&v[x+8]==="T"}i(S,"isElement"),r(S,"isElement");function H(v,x){return v[x+1]==="!"&&v[x+2]==="A"&&v[x+3]==="T"&&v[x+4]==="T"&&v[x+5]==="L"&&v[x+6]==="I"&&v[x+7]==="S"&&v[x+8]==="T"}i(H,"isAttlist"),r(H,"isAttlist");function V(v,x){return v[x+1]==="!"&&v[x+2]==="N"&&v[x+3]==="O"&&v[x+4]==="T"&&v[x+5]==="A"&&v[x+6]==="T"&&v[x+7]==="I"&&v[x+8]==="O"&&v[x+9]==="N"}i(V,"isNotation"),r(V,"isNotation");function j(v){if(L.isName(v))return v;throw new Error(`Invalid entity name ${v}`)}i(j,"validateEntityName"),r(j,"validateEntityName"),E.exports=O}}),l=o({"../../node_modules/strnum/strnum.js"(b,E){var L=/^[-+]?0x[a-fA-F0-9]+$/,O=/^([\-\+])?(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 Z={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function M(S,H={}){if(H=Object.assign({},Z,H),!S||typeof S!="string")return S;let V=S.trim();if(H.skipLike!==void 0&&H.skipLike.test(V))return S;if(H.hex&&L.test(V))return Number.parseInt(V,16);{let j=O.exec(V);if(j){let v=j[1],x=j[2],q=F(j[3]),ce=j[4]||j[6];if(!H.leadingZeros&&x.length>0&&v&&V[2]!==".")return S;if(!H.leadingZeros&&x.length>0&&!v&&V[1]!==".")return S;{let X=Number(V),te=""+X;return te.search(/[eE]/)!==-1||ce?H.eNotation?X:S:V.indexOf(".")!==-1?te==="0"&&q===""||te===q||v&&te==="-"+q?X:S:x?q===te||v+q===te?X:S:V===te||V===v+te?X:S}}else return S}}i(M,"toNumber"),r(M,"toNumber");function F(S){return S&&S.indexOf(".")!==-1&&(S=S.replace(/0+$/,""),S==="."?S="0":S[0]==="."?S="0"+S:S[S.length-1]==="."&&(S=S.substr(0,S.length-1))),S}i(F,"trimZeros"),r(F,"trimZeros"),E.exports=M}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(b,E){"use strict";var L=a(),O=u(),Z=c(),M=l(),F=class{static{i(this,"OrderedObjParser")}static{r(this,"OrderedObjParser")}constructor(P){this.options=P,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:i((C,_)=>String.fromCharCode(Number.parseInt(_,10)),"val")},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:i((C,_)=>String.fromCharCode(Number.parseInt(_,16)),"val")}},this.addExternalEntities=S,this.parseXml=x,this.parseTextData=H,this.resolveNameSpace=V,this.buildAttributesMap=v,this.isItStopNode=te,this.replaceEntitiesValue=ce,this.readStopNodeData=G,this.saveTextToParentTag=X,this.addChild=q}};function S(P){let C=Object.keys(P);for(let _=0;_<C.length;_++){let B=C[_];this.lastEntities[B]={regex:new RegExp("&"+B+";","g"),val:P[B]}}}i(S,"addExternalEntities"),r(S,"addExternalEntities");function H(P,C,_,B,N,D,ne){if(P!==void 0&&(this.options.trimValues&&!B&&(P=P.trim()),P.length>0)){ne||(P=this.replaceEntitiesValue(P));let z=this.options.tagValueProcessor(C,P,_,N,D);return z==null?P:typeof z!=typeof P||z!==P?z:this.options.trimValues?me(P,this.options.parseTagValue,this.options.numberParseOptions):P.trim()===P?me(P,this.options.parseTagValue,this.options.numberParseOptions):P}}i(H,"parseTextData"),r(H,"parseTextData");function V(P){if(this.options.removeNSPrefix){let C=P.split(":"),_=P.charAt(0)==="/"?"/":"";if(C[0]==="xmlns")return"";C.length===2&&(P=_+C[1])}return P}i(V,"resolveNameSpace"),r(V,"resolveNameSpace");var j=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function v(P,C,_){if(!this.options.ignoreAttributes&&typeof P=="string"){let B=L.getAllMatches(P,j),N=B.length,D={};for(let ne=0;ne<N;ne++){let z=this.resolveNameSpace(B[ne][1]),U=B[ne][4],de=this.options.attributeNamePrefix+z;if(z.length)if(this.options.transformAttributeName&&(de=this.options.transformAttributeName(de)),de==="__proto__"&&(de="#__proto__"),U!==void 0){this.options.trimValues&&(U=U.trim()),U=this.replaceEntitiesValue(U);let se=this.options.attributeValueProcessor(z,U,C);se==null?D[de]=U:typeof se!=typeof U||se!==U?D[de]=se:D[de]=me(U,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(D[de]=!0)}if(!Object.keys(D).length)return;if(this.options.attributesGroupName){let ne={};return ne[this.options.attributesGroupName]=D,ne}return D}}i(v,"buildAttributesMap"),r(v,"buildAttributesMap");var x=r(function(P){P=P.replace(/\r\n?/g,`
89
+ ${await l.text()}`;if(r)throw new Error(p);return t.log.error(p),e}let d=await l.json();if(o&&t.log.debug(`${this.policyType} '${this.policyName}' - PDP response`,d),d.decision!==!0)return this.#r(e,t,d.reason)}catch(o){if(r)throw o;t.log.error(`${this.policyType} '${this.policyName}' - Error in policy: ${o}`)}return e}#n(e,t,r){if(t){let o=`${this.policyType} '${this.policyName}' - ${r}`;if(this.options.throwOnError)throw new g(o);e.log.warn(o)}}async#r(e,t,r){return T.forbidden(e,t,{detail:r})}async#o(e){if(!this.#t){let t=await ie(this.policyName,void 0,this.options);this.#t=new re(t,e)}}static setAuthorizationPayload(e,t){oe.set(e,cu,t)}static getAuthorizationPayload(e){return oe.get(e,cu)}};var Xn=class{constructor(e){this.options=e;this.authHeader=`Basic ${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 $.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 xi=class n extends ae{static{i(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static#e;static setAuthAttributes(e,t){n.#e||(n.#e=new WeakMap),n.#e.set(e,{Request:t})}constructor(e,t){super(e,t),f("policy.inbound.axiomatics-authz"),W(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new Xn(e)}async handler(e,t){let r=i(a=>this.options.allowUnauthorizedRequests?e:T.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=new URL(e.url),s=n.#e?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1&&e.user){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(s,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(s,"Action",a)}if(this.options.includeDefaultResourceAttributes!==!1){let a=[];a.push({AttributeId:"request.protocol",Value:o.protocol.substring(0,o.protocol.length-1)}),a.push({AttributeId:"request.host",Value:o.host}),a.push({AttributeId:"request.pathname",Value:o.pathname}),Object.entries(e.params).forEach(([u,c])=>{a.push({AttributeId:`request.params.${u}`,Value:c})}),o.searchParams.forEach((u,c)=>{a.push({AttributeId:`request.query.${c}`,Value:u})}),this.addAttributesToCategory(s,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:s,context:t});try{t.log.debug("PDP Request",s);let a=await this.pdpService.makePdpRequest(s);return t.log.debug("PDP Response",a),a.Response.every(u=>u.Decision==="Permit")?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling PDP service`,a),T.internalServerError(e,t)}}populateOptionAttributes({optionName:e,authzRequestCategory:t,authzRequest:r,context:o}){let s=this.options[e];if(s){let a=[];s.forEach(u=>{u.value?a.push({AttributeId:u.attributeId,Value:u.value}):o.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${u.attributeId} has no value. If using a selector, check that the selector is correct.`)}),this.addAttributesToCategory(r,t,a)}}addAttributesToCategory(e,t,r){e.Request[t]||(e.Request[t]=[]),e.Request[t].length===0?e.Request[t].push({Attribute:[]}):e.Request[t][0].Attribute=e.Request[t][0].Attribute??[],e.Request[t][0].Attribute.push(...r)}};var Md=i(async(n,e,t)=>{f("policy.inbound.basic-auth");let r=n.headers.get("Authorization"),o="basic ",s=i(l=>T.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!r)return await s("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await s("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let m=d.substring(0,p),h=d.substring(p+1),I=t.accounts.find(b=>b.username===m&&b.password===h);return I||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 er(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}i(er,"extractDateElements");function lu(n,e){return new Date(n,e+1,0).getDate()}i(lu,"getDaysInMonth");function Ti(n,e){return n<=e?e-n:6-n+e+1}i(Ti,"getDaysBetweenWeekdays");var tr=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=lu(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(m=>m>=d)??this.weekdays[0]:this.reversed.weekdays.find(m=>m<=d)??this.reversed.weekdays[0];if(p!==void 0){let m=e==="next"?Ti(d,p):Ti(p,d);l=e==="next"?o+m:o-m,(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=er(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 m=this.findAllowedTime("next",t);if(m!==void 0)return new Date(u,c,d,m.hour,m.minute,m.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=er(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 m=this.findAllowedTime("prev",t);if(m!==void 0)return new Date(u,c,d,m.hour,m.minute,m.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}=er(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 qd={min:0,max:59},Ud={min:0,max:59},Hd={min:0,max:23},$d={min:1,max:31},Zd={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"}},Fd={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},jd={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 1 *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@hourly":"0 * * * *","@minutely":"* * * * *"};function lt(n,e){let t=new Set;if(n==="*"){for(let d=e.min;d<=e.max;d=d+1)t.add(d);return t}let r=n.split(",");if(r.length>1)return r.forEach(d=>{lt(d,e).forEach(m=>t.add(m))}),t;let o=i(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${n}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${n}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),s=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(s===null)return t.add(o(n)),t;let a=s[1]==="*"?e.min:o(s[3]),u=s[1]==="*"?e.max:o(s[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=s[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}i(lt,"parseElement");function vi(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=jd[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 tr({seconds:lt(t,qd),minutes:lt(r,Ud),hours:lt(o,Hd),days:lt(s,$d),months:new Set(Array.from(lt(a,Zd)).map(c=>c-1)),weekdays:new Set(Array.from(lt(u,Fd)).map(c=>c%7))})}i(vi,"parseCronExpression");var Ci=class extends ae{static{i(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),f("policy.inbound.brownout"),W(e,t).optional("problem","object"),e.problem&&W(e.problem,t,"policy","problem").optional("detail","string").optional("status","string").optional("title","string"),typeof e.cronSchedule!="string"&&!(typeof e.cronSchedule=="object"&&Array.isArray(e.cronSchedule)&&!e.cronSchedule.some(r=>typeof r!="string")))throw new g(`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=[vi(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>vi(r))}async handler(e,t){let r=new Date;if(r.setSeconds(0),r.setMilliseconds(0),this.crons.some(s=>s.matchDate(r))){let s=T.getProblemFromStatus(this.options.problem?.status??400,{detail:"This API is performing a scheduled brownout in advance of its pending deprecation. Please upgrade to a later version.",...this.options.problem});return T.format(s,e,t)}return e}};var zd=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Bd(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(Bd,"digestMessage");var Gd=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 Bd(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 Vd(n,e,t,r){f("policy.inbound.caching");let o=await ie(r,t.cacheId,t),s=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Gd(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 m=t?.expirationSecondsTtl??60,h=new Response(p.body,p);zd.forEach(I=>h.headers.delete(I)),h.headers.set("cache-control",`s-maxage=${m}`),e.waitUntil(s.put(u,h))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}i(Vd,"CachingInboundPolicy");var Wd=i(async(n,e,t,r)=>{if(f("policy.inbound.change-method"),!t.method)throw new g(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new ee(n,{method:t.method})},"ChangeMethodInboundPolicy");var Jd=i(async(n,e,t)=>{f("policy.inbound.clear-headers");let r=[...t.exclude??[]],o=new Headers;return r.forEach(a=>{let u=n.headers.get(a);u&&o.set(a,u)}),new ee(n,{headers:o})},"ClearHeadersInboundPolicy");var Kd=i(async(n,e,t,r)=>{f("policy.outbound.clear-headers");let o=[...r.exclude??[]],s=new Headers;return o.forEach(u=>{let c=n.headers.get(u);c&&s.set(u,c)}),new Response(n.body,{headers:s,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var Qd=i(async(n,e,t,r)=>{f("policy.inbound.clerk-jwt-auth");let o=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),s=new URL(o);return s.pathname="/.well-known/jwks.json",Ee(n,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var Yd=i(async(n,e,t,r)=>{if(f("policy.inbound.cognito-jwt-auth"),!t.userPoolId)throw new g("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new g("region must be set in the options for CognitoJwtInboundPolicy");return Ee(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 nr=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},Si=class extends nr{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Oi=class extends nr{static{i(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function Xd(n,e){if(Ws(n))throw new Si(e)}i(Xd,"throwIfUndefinedOrNull");function du(n,e){if(Xd(n,e),!Te(n))throw new Oi(e,"string")}i(du,"throwIfNotString");var Ai=class{static{i(this,"InMemoryRateLimitClient")}keyValueStore;constructor(){this.keyValueStore=new Map}getCountAndUpdateExpiry(e,t){let o=Math.floor(t*60),s=Date.now()+o*1e3,a=this.keyValueStore.get(e);a?Date.now()>a.expiresAt?this.keyValueStore.set(e,{value:1,expiresAt:s}):this.keyValueStore.set(e,{value:a.value+1,expiresAt:a.expiresAt}):this.keyValueStore.set(e,{value:1,expiresAt:s});let u=this.keyValueStore.get(e);return Promise.resolve({count:u.value,ttlSeconds:Math.round((u.expiresAt-Date.now())/1e3)})}multiIncrement(e,t){throw new Error("In memory complex rate limits are not currently supported.")}multiCount(e,t){throw new Error("In memory complex rate limits are not currently supported.")}setQuota(e,t,r){throw new Error("In memory quotas are not currently supported.")}getQuota(e,t){throw new Error("In memory quotas are not currently supported.")}},ep=500,ki=class{constructor(e){this.clientUrl=e}static{i(this,"RemoteRateLimitClient")}static instance;async fetch({url:e,body:t,method:r,requestId:o}){du(e,"url");let s=new AbortController;setTimeout(()=>{s.abort()},ep);let a,u=new Headers({"content-type":"application/json"});De(u,o);try{a=await $.fetch(`${this.clientUrl}${e}`,{method:r,body:t,signal:s.signal,headers:u})}catch(l){throw console.error("Rate limit service timed out",l),new Y("Rate limiting service failed.",{cause:l})}let c=a.headers.get("Content-Type")?.includes("application/json")?await a.json():await a.text();if(a.ok)return c;throw a.status===401?new Y("Rate limiting service failed with 401: Unauthorized"):new Y(`Rate limiting service failed with (${a.status})`)}async multiCount(e,t){return(await this.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async multiIncrement(e,t){return(await this.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async getCountAndUpdateExpiry(e,t,r){let o=Math.floor(t*60);return await this.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:o,key:e}),requestId:r})}async getQuota(e,t){let r=await ct(e);return await this.fetch({url:`/quota/${r}`,method:"GET",requestId:t})}async setQuota(e,t,r){let o=await ct(e);await this.fetch({url:`/quota/${o}`,method:"POST",body:JSON.stringify(t),requestId:r})}},Tt;function nt(n,e){let{redisURL:t,authApiJWT:r}=y.instance;if(Tt)return Tt;if(!r)return e.info("Using in-memory rate limit client for local development."),Tt=new Ai,Tt;if(!Te(t))throw new Y(`RateLimitClient used in policy '${n}' - rate limit service not configured`);if(!Te(r))throw new Y(`RateLimitClient used in policy '${n}' - rate limit service not configured`);return Tt=new ki(t),Tt}i(nt,"getRateLimitClient");var tp=i(n=>{let e=n.headers.get("x-real-ip")??n.headers.get("true-client-ip")??n.headers.get("cf-connecting-ip");if(e)return e;let t=n.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP");function vt(n,e){return{function:ip(e,"RateLimitInboundPolicy",n),user:rp,ip:np,all:op}[e.rateLimitBy??"ip"]}i(vt,"getRateLimitByFunctions");var np=i(async n=>({key:`ip-${tp(n)}`}),"getIP"),rp=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),op=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll");function ip(n,e,t){let r;if(n.rateLimitBy==="function"){if(!n.identifier)throw new g(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new g(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new g(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=n.identifier.module[n.identifier.export],!r||typeof r!="function")throw new g(`${e} '${t}' - Custom rate limit function must be a valid function`)}return i(async(s,a,u)=>{let c=await r(s,a,u);if(!c||typeof c!="object"){let l=`${e} '${u}' - Custom rate limit function must return a valid object.`;throw a.log.error(l),new k(l)}if(!("key"in c)){let l=`${e} '${u}' - Custom rate limit function must return a valid key property.`;throw a.log.error(l,c),new k(l)}if(typeof c.key!="string"){let l=`${e} '${u}' - Custom rate limit function must return a valid key property of type string. Received type '${typeof c.key}'`;throw a.log.error(l),new k(l)}return c},"outerFunction")}i(ip,"wrapUserFunction");var Ct="Retry-After";var pu=be("zuplo:policies:ComplexRateLimitInboundPolicy"),Li=Symbol("complex-rate-limit-counters"),_i=class n extends ae{static{i(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let r=oe.get(e,Li)??{};Object.assign(r,t),oe.set(e,Li,t)}static getIncrements(e){return oe.get(e,Li)??{}}constructor(e,t){super(e,t),f("policy.inbound.complex-rate-limit-inbound"),W(e,t).required("rateLimitBy","string").required("timeWindowMinutes","number").required("limits","object").optional("headerMode","string").optional("throwOnFailure","boolean").optional("mode","string").optional("identifier","object"),e.identifier&&W(e.identifier,t,"policy","identifier").required("export","string").required("module","object");for(let[r,o]of Object.entries(e.limits))if(typeof o!="number")throw new g(`ComplexRateLimitInboundPolicy '${this.policyName}' - The value of the limits must be numbers. The limit ${r} is set to type '${typeof e}'.`)}async handler(e,t){let r=Date.now(),o=J.getLogger(t),s=nt(this.policyName,o),a=i((c,l)=>{if(this.options.throwOnFailure)throw new Y(c,{cause:l});o.error(c,l)},"throwOrLog"),u=i((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[Ct]=l.toString()),T.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l=await vt(this.policyName,this.options)(e,t,this.policyName),d=y.instance.isTestMode||y.instance.isWorkingCopy?y.instance.build.BUILD_ID:"",p=Object.assign({},this.options.limits,l.limits),m=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;t.addResponseSendingFinalHook(async()=>{try{let E=n.getIncrements(t);pu(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(E)}`);let L=Object.entries(p).map(([Z])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${Z}`,ttlSeconds:m,increment:E[Z]??0})),O=s.multiIncrement(L,t.requestId);t.waitUntil(O),await O}catch(E){a(E.message,E)}});let h=Object.entries(p).map(([E,L])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${E}`,ttlSeconds:m,limit:L})),I=await s.multiCount(h,t.requestId);return sp(I,h).length>0?u(this.options.headerMode??"retry-after",m):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-r;pu(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function sp(n,e){let t=[];for(let r of n){let o=e.find(s=>s.key===r.key)?.limit||0;r.count>=o&&t.push(r)}return t}i(sp,"findOverLimits");var ap=i(async(n,e,t,r)=>{if(f("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new g(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=ge.instance,s=Wt(t.policies,o?.routeData.policies);return no(s)(n,e)},"CompositeInboundPolicy");var up=i(async(n,e,t,r,o)=>{if(f("policy.outbound.composite"),!r.policies||r.policies.length===0)throw new g(`CompositeOutboundPolicy '${o}' must have valid policies defined`);let s=ge.instance,a=Jt(r.policies,s?.routeData.policies);return ro(a)(n,e,t)},"CompositeOutboundPolicy");var cp=i(async(n,e,t,r)=>{f("policy.inbound.curity-phantom-token-auth");let o=n.headers.get("Authorization");if(!o)return T.unauthorized(n,e,{detail:"No authorization header"});let s=lp(o);if(!s)return T.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await ie(r,void 0,t),u=new re(a,e),c=await u.get(s);if(!c){let l=await $.fetch(t.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${t.clientId}:${t.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(s,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),T.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):T.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function lp(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(lp,"getToken");var dp=i(async(n,e,t,r)=>(f("policy.inbound.firebase-jwt-auth"),W(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),Ee(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 pp=i(async(n,e,t)=>{f("policy.inbound.form-data-to-json");let r="application/x-www-form-urlencoded",o="multipart/form-data",s=n.headers.get("content-type")?.toLowerCase();if(!s||![o,r].includes(s))return t&&t.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):n;let a=await n.formData();if(t&&t.optionalHoneypotName&&a.get(t.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(n.headers);return c.set("content-type","application/json"),c.delete("content-length"),new ee(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var St="__unknown__",mp=i(async(n,e,t,r)=>{f("policy.inbound.geo-filter");let o={allow:{countries:At(t.allow?.countries,"allow.countries",r),regionCodes:At(t.allow?.regionCodes,"allow.regionCode",r),asns:At(t.allow?.asns,"allow.asOrganization",r)},block:{countries:At(t.block?.countries,"block.countries",r),regionCodes:At(t.block?.regionCodes,"block.regionCode",r),asns:At(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??St,a=e.incomingRequestProperties.regionCode?.toLowerCase()??St,u=e.incomingRequestProperties.asn?.toString()??St,c=o.ignoreUnknown&&s===St,l=o.ignoreUnknown&&a===St,d=o.ignoreUnknown&&u===St,p=o.allow.countries,m=o.allow.regionCodes,h=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||m.length>0&&!m.includes(a)&&!l||h.length>0&&!h.includes(u)&&!d)return Ot(n,e,r,s,a,u);let I=o.block.countries,b=o.block.regionCodes,E=o.block.asns;return I.length>0&&I.includes(s)&&!c||b.length>0&&b.includes(a)&&!l||E.length>0&&E.includes(u)&&!d?Ot(n,e,r,s,a,u):n},"GeoFilterInboundPolicy");function Ot(n,e,t,r,o,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${s}')`),T.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:s}})}i(Ot,"blockedResponse");function At(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 g(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}i(At,"toLowerStringArray");var gp=i(async(n,e,t)=>{f("policy.inbound.jwt-scope-validation");let r=n.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(r,t.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var fp=i(async(n,e,t,r)=>{f("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return Ni(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 Ni(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(m=>{a.push({responseName:u,contentName:l,exampleName:m,exampleValue:d[m]})})})}),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 mu(a[u])}else return a.length>0?mu(a[0]):Ni(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 mu(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(mu,"generateResponse");var Ni=i((n,e,t,r)=>{let o=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${r}`;return T.internalServerError(e,t,{detail:o})},"getProblemDetailResponse");var hp="Incoming",yp={logRequestBody:!0,logResponseBody:!0};function gu(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}i(gu,"headersToObject");function fu(){return new Date().toISOString()}i(fu,"timestamp");var Di=new WeakMap,bp={};function wp(n,e){let t=Di.get(n);t||(t=bp);let r=Object.assign({...t},e);Di.set(n,r)}i(wp,"setMoesifContext");async function hu(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(hu,"readBody");var Rp={},Mi;function yu(){if(!Mi)throw new k("Invalid State - no _lastLogger");return Mi}i(yu,"getLastLogger");function Pp(n){let e=Rp[n];return e||(e=new K("moesif-inbound",100,async t=>{let r=JSON.stringify(t);yu().debug("posting",r);let o=await $.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||yu().error({status:o.status,body:await o.text()})})),e}i(Pp,"getDispatcher");async function Ip(n,e,t,r){f("policy.inbound.moesif-analytics"),Mi=e.log;let o=fu(),s=Object.assign(yp,t);if(!s.applicationId)throw new g(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await hu(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Pp(s.applicationId),d=n.headers.get("true-client-ip"),p=Di.get(e)??{},m={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:gu(n.headers)},h=s.logResponseBody?await hu(u,e):void 0,I={time:fu(),status:u.status,headers:gu(u.headers),body:h},b={request:m,response:I,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:hp};l.enqueue(b),e.waitUntil(l.waitUntilFlushed())}),n}i(Ip,"MoesifInboundPolicy");async function bu(n,e,t,r){let o=J.getLogger(n),{authApiJWT:s,meteringServiceUrl:a}=y.instance,u;try{let l=await $.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(bu,"loadSubscription");async function wu(n,e,t,r,o){let{authApiJWT:s,meteringServiceUrl:a}=y.instance,u=J.getLogger(n);try{let c=await $.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(wu,"consumeSubcriptionQuotas");var Ep=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function rr(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 g(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 g?new g(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}i(rr,"validateMeters");function Ru(n,e){if(n)try{if(n.length===0)throw new g("Must set valid subscription statuses");let t=je(n),r=[];for(let o of t)Ep.has(o)||r.push(o);if(r.length>0)throw new g(`Found the following invalid statuses: ${r.join(", ")}`);return n}catch(t){throw t instanceof g?new g(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}i(Ru,"parseAllowedSubscriptionStatuses");function Pu(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(Pu,"compareMeters");var qi=class extends ae{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return oe.get(e,Zt)}static setMeters(e,t){rr(t,"setMeters");let r=oe.get(e,Ft)??{};Object.assign(r,t),oe.set(e,Ft,r)}constructor(e,t){super(e,t),f("policy.inbound.monetization")}async handler(e,t){W(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let r=this.options.allowRequestsOverQuota??!1,o=We(this.options.meterOnStatusCodes),s=oe.get(t,Ft),a={...this.options.meters,...s};rr(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=Ru(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(b,E,L)=>{let O=oe.get(L,Zt);if((this.options.allowRequestsWithoutSubscription??!1)&&!O){L.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(ye.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=ye.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let M=oe.get(L,Ft),F={...this.options.meters,...M};if(rr(F,this.policyName),o.includes(b.status)&&O&&F){L.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${O.id}' with meters '${JSON.stringify(F)} on response status '${b.status}'`);let{metersInSubscription:S,metersNotInSubscription:H}=Pu(O.meters,F);if(H&&Object.keys(H).length>0){let V=Object.keys(H);L.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${V}'`)}await wu(L,O.id,this.policyName,this.options.bucketId,S)}});let l=e.user;if(!l)return u?e:T.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(ye.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=ye.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await bu(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:T.unauthorized(e,t,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return t.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),T.unauthorized(e,t,{detail:"No valid subscription found"});c.includes(p.status)&&(t.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),oe.set(t,Zt,p));let m=oe.get(t,Zt);if(!m)return u?e:(t.log.warn("Subscription is not available for user"),T.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(m&&Object.keys(m.meters).length===0)return t.log.error(`Quota is not set up for subscription '${m.id}'`),T.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let I=Object.keys(a).filter(b=>!Object.keys(m.meters).includes(b));if(I.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${I.join(", ")}`),T.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${I.join(", ")}`,title:"Quota Exceeded"});for(let b of Object.keys(a))if(m.meters[b].available<=0&&!r)return T.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${b}'`,title:"Quota Exceeded"});return e}};async function or(n,e){let t=new URLSearchParams({client_id:n.clientId,client_secret:n.clientSecret,grant_type:"client_credentials"});n.scope&&t.append("scope",n.scope),n.audience&&t.append("audience",n.audience);let r=await we({retries:n.retries?.maxRetries??3,retryDelayMs:n.retries?.delayMs??10},n.tokenEndpointUrl,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let s=await r.text();e.log.error(`Error getting token from identity provider. Status: ${r.status}`,s)}catch{}throw new k("Error getting token from identity provider.")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new k("Response returned from identity provider is not in the expected format.")}i(or,"getClientCredentialsAccessToken");var kt=class extends Error{constructor(t,r,o){super(r,o);this.code=t}static{i(this,"OpenFGAError")}},ir=class{static{i(this,"BaseOpenFGAClient")}apiUrl;storeId;authorizationModelId;constructor(e){this.apiUrl=e.apiUrl,this.storeId=e.storeId,this.authorizationModelId=e.authorizationModelId}getStoreId(e={},t=!1){let r=e?.storeId||this.storeId;if(!t&&!r)throw new g("storeId is required");return r}getAuthorizationModelId(e={}){return e?.authorizationModelId||this.authorizationModelId}async get(e,t){return this.fetch(e,"GET",t)}async put(e,t,r){return this.fetch(e,"PUT",r,t)}post(e,t,r){return this.fetch(e,"POST",r,t)}async fetch(e,t,r,o){let s=new Headers(r.headers||{});s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.set("User-Agent",y.instance.systemUserAgent);let a=`${this.apiUrl}${e}`,u=new Request(a,{method:t,headers:s,body:o?JSON.stringify(o):void 0}),c=await $.fetch(u);if(c.status!==200){let l;try{l=await c.json()}catch{}throw!l||!l.code||!l.message?new kt("unknown",`Unknown error. Status: ${c.status}`):new kt(l.code,l.message)}return c.json()}};function cn(n,e,t){!n[e]&&t&&(n[e]=t)}i(cn,"setHeaderIfNotSet");var Iu="X-OpenFGA-Client-Method",Eu="X-OpenFGA-Client-Bulk-Request-Id",ln=class extends ir{static{i(this,"OpenFGAClient")}async check(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/check`,{tuple_key:{user:e.user,relation:e.relation,object:e.object},context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]},authorization_model_id:this.getAuthorizationModelId(t)},t)}async batchCheck(e,t={}){let{headers:r={}}=t;return cn(r,Iu,"BatchCheck"),cn(r,Eu,crypto.randomUUID()),{responses:await Promise.all(e.map(async s=>this.check(s,Object.assign({},t,r)).then(a=>(a._request=s,a)).catch(a=>{if(a instanceof kt)throw a;return{allowed:void 0,error:a,_request:s}})))}}async expand(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/expand`,{authorization_model_id:this.getAuthorizationModelId(t),tuple_key:e},t)}async listObjects(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-objects`,{authorization_model_id:this.getAuthorizationModelId(t),user:e.user,relation:e.relation,type:e.type,context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]}},t)}async listRelations(e,t={}){let{user:r,object:o,relations:s,contextualTuples:a,context:u}=e,{headers:c={}}=t;if(cn(c,Iu,"ListRelations"),cn(c,Eu,crypto.randomUUID()),!s?.length)throw new Error("When calling listRelations, at least one relation must be passed in the relations field");let l=await this.batchCheck(s.map(p=>({user:r,relation:p,object:o,contextualTuples:a,context:u})),Object.assign({},t,c)),d=l.responses.find(p=>p.error);if(d)throw d.error;return{relations:l.responses.filter(p=>p.allowed).map(p=>p._request.relation)}}async listUsers(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-users`,{authorization_model_id:this.getAuthorizationModelId(t),relation:e.relation,object:e.object,user_filters:e.user_filters,context:e.context,contextual_tuples:e.contextualTuples||[]},t)}};var xu=Symbol("openfga-authz-context-data"),Lt=class extends ae{static{i(this,"BaseOpenFGAAuthZInboundPolicy")}client;authorizer;cache;static setContextChecks(e,t){let r=Array.isArray(t)?t:[t];oe.set(e,xu,r)}constructor(e,t){if(super(e,t),W(e,t).required("apiUrl","string").optional("storeId","string").optional("authorizationModelId","string"),!e.credentials)throw new g(`${this.policyType} '${this.policyName}' - The 'credentials' option is required.`);if(e.credentials.method==="client-credentials")W(e.credentials,t).required("clientId","string").required("clientSecret","string").required("oauthTokenEndpointUrl","string").optional("apiAudience","string");else if(e.credentials.method==="api-token")W(e.credentials,t).required("token","string").optional("headerName","string").optional("headerValuePrefix","string");else if(e.credentials.method==="header")W(e.credentials,t).optional("headerName","string");else if(e.credentials.method!=="none")throw new g(`${this.policyType} '${this.policyName}' - The 'credentials.method' option is invalid. It must be set to either 'none', 'api-token', 'client-credentials', or 'header'.`);this.authorizer=this.getAuthorizer(e.credentials),this.client=new ln({apiUrl:e.apiUrl,storeId:e.storeId,authorizationModelId:e.authorizationModelId})}async handler(e,t){if(!this.cache){let a=await ie(this.policyName,void 0,this.options);this.cache=new re(a,t)}let r=i(a=>this.options.allowUnauthorizedRequests?e:T.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=oe.get(t,xu);if(!o||o.length===0)throw new k(`${this.policyType} '${this.policyName}' - No checks found in the context.`);let s=await this.authorizer(e,t);try{t.log.debug("OpenFGA checks",o);let a=await this.client.batchCheck(o,{headers:s});return t.log.debug("OpenFGA Response",a),a.responses.every(u=>u.allowed)?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling OpenFGA service`,a),T.internalServerError(e,t)}}getAuthorizer(e){if(e.method==="none")return async()=>({});if(e.method==="header")return async t=>{let r=e.headerName??"Authorization",o=t.headers.get(r);if(!o)throw new Y(`${this.policyType} '${this.policyName}' - The header '${r}' is missing.`);return{[r]:o}};if(e.method==="api-token")return async()=>({[e.headerName??"Authorization"]:`${e.headerValuePrefix??"Bearer "} ${e.token}`});if(e.method==="client-credentials")return async(t,r)=>{let o=await this.cache?.get("client_credentials_token");if(o)return{Authorization:`Bearer ${o}`};let s=await or({tokenEndpointUrl:e.oauthTokenEndpointUrl,clientId:e.clientId,clientSecret:e.clientSecret,audience:e.apiAudience},r);return this.cache?.put("client_credentials_token",s.access_token,s.expires_in),{Authorization:`Bearer ${s.access_token}`}};throw new k("Invalid state for credentials method is not valid. This should not happen.")}};var Tu=["us1","eu1","au1"],Ui=class extends Lt{static{i(this,"OktaFGAAuthZInboundPolicy")}constructor(e,t){if(!Tu.includes(e.region))throw new g(`OktaFGAAuthZInboundPolicy '${t}' - The 'region' option is invalid. Must be one of ${Tu.join(", ")}.`);let r={...e,apiUrl:`https://api.${e.region}.fga.dev`,credentials:{method:"client-credentials",oauthTokenEndpointUrl:"https://fga.us.auth0.com/oauth/token",clientId:e.credentials.clientId,clientSecret:e.credentials.clientSecret,apiAudience:`https://api.${e.region}.fga.dev/`}};super(r,t),f("policy.inbound.oktafga-authz")}};var xp=i(async(n,e,t,r)=>(f("policy.inbound.okta-jwt-auth"),Ee(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"OktaJwtInboundPolicy");var Hi=class extends Lt{static{i(this,"OpenFGAAuthZInboundPolicy")}constructor(e,t){super(e,t),f("policy.inbound.openfga-authz")}};import{importSPKI as Tp}from"jose";var $i,vp=i(async(n,e,t,r)=>{if(f("policy.inbound.propel-auth-jwt-auth"),!$i)try{$i=await Tp(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return Ee(n,e,{issuer:t.authUrl,secret:$i,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Zi="quota-inbound-policy-f307056c-8c00-4f2c-b4ac-c0ac7d04eca0",vu="quota-usage-2017e968-4de8-4a63-8951-1e423df0d64b";var Fi=class n extends ae{static{i(this,"QuotaInboundPolicy")}constructor(e,t){super(e,t),f("policy.inbound.quota")}async handler(e,t){let r=this.options.debug??!1;t.log.debug({debug:r}),W(this.options,this.policyName).required("period","string").required("quotaBy","string").optional("quotaAnchorMode","string").optional("allowances","object"),n.setMeters(t,{requests:1});let o=J.getLogger(t);try{let s=Cp(this.options,this.policyName),a=s.functions.getAnchorDate(e,t,this.policyName),u=s.functions.getQuotaDetail(e,t,this.policyName),[c,l]=await Promise.all([a,u]),d=Sp(l.key,this.policyName);r&&t.log.debug(`QuotaInboundPolicy: key - '${d}'`);let p=nt(this.policyName,o),m=await p.getQuota(d,t.requestId);n.#e(t,this.policyName,m),r&&t.log.debug("QuotaInboundPolicy: quotaResult",m),c&&new Date(m.anchorDate).getTime()!==c.getTime()&&t.log.warn(`QuotaInboundPolicy '${this.policyName}' provided anchorDate ('${c}') did not match the stored, immutable anchorDate ('${m.anchorDate}')`);let h=Object.assign({},s.defaultAllowances);Object.assign(h,l.allowances);let I=[],b="";if(Object.entries(h).forEach(([E,L])=>{r&&(b+=`${E} - allowed: ${L} value: ${m.meters[E]??0}
90
+ `),(m.meters[E]??0)>=L&&I.push(E)}),r&&t.log.debug("QuotaInboundPolicy: debugTable",b),I.length>0)return T.tooManyRequests(e,t,{detail:`Quota exceeded for meters '${I.join(", ")}'`});t.addResponseSendingFinalHook(async(E,L,O)=>{if(r&&O.log.debug(`QuotaInboundPolicy: backend response - ${E.status}: ${E.statusText}`),!s.quotaOnStatusCodes.includes(E.status))return;let Z=oe.get(O,Zi),M={config:{period:s.period,anchorDate:c?.toISOString()??""},increments:Z};r&&O.log.debug("QuotaInboundPolicy: setQuotaDetails",M);let F=p.setQuota(d,M,O.requestId);O.waitUntil(F)})}catch(s){o.error(s),t.log.error(s)}return e}static setMeters(e,t){let r=oe.get(e,Zi)??{};Object.assign(r,t),oe.set(e,Zi,r)}static getUsage(e,t){let r=oe.get(e,`${vu}-${t}`);if(r===void 0)throw new k(`QuotaInboundPolicy.getUsage was called for policy named '${t}' but the policy itself has not yet executed.`);return r}static#e(e,t,r){oe.set(e,`${vu}-${t}`,r)}};function Cp(n,e){let t=i(async s=>({key:`user-1385b4e8-800f-488e-b089-c197544e5801-${s.user?.sub}`,allowances:n.allowances??{}}),"getQuotaDetail"),r=i(async()=>{},"getAnchorDate");if(n.quotaBy==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getQuotaDetailExport===void 0)throw new g(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getQuotaDetailExport' is required when 'quotaBy' is 'function'`);t=n.identifier.module[n.identifier.getQuotaDetailExport]}if(n.quotaAnchorMode==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getAnchorDateExport===void 0)throw new g(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getAnchorDateExport' is required when 'quotaAnchorMode' is 'function'`);r=n.identifier.module[n.identifier.getAnchorDateExport]}return{period:n.period,quotaBy:n.quotaBy??"user",quotaAnchorMode:n.quotaAnchorMode??"first-api-call",quotaOnStatusCodes:We(n.quotaOnStatusCodes??"200-299"),defaultAllowances:Object.assign({},n.allowances),functions:{getQuotaDetail:t,getAnchorDate:r}}}i(Cp,"validateAndParseOptions");function Sp(n,e){return encodeURIComponent(`${e}-${n}`)}i(Sp,"processKey");var Cu=be("zuplo:policies:RateLimitInboundPolicy"),Su=i(async(n,e,t,r)=>{let o=J.getLogger(e),s=i((F,S)=>{let H={};return(!F||F==="retry-after")&&(H[Ct]=S.toString()),T.tooManyRequests(n,e,void 0,H)},"rateLimited"),u=await vt(r,t)(n,e,r),c=u.key,l=u.requestsAllowed??t.requestsAllowed,d=u.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",m=nt(r,o),I=`rate-limit${y.instance.isTestMode?y.instance.build.BUILD_ID:""}/${r}/${c}`,b=await ie(r,void 0,t),E=new re(b,e),L=m.getCountAndUpdateExpiry(I,d,e.requestId),O;i(async()=>{let F=await L;if(F.count>l){let S=Date.now()+F.ttlSeconds*1e3;E.put(I,S,F.ttlSeconds),Cu(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${I}' (async mode)`),O=s(p,F.ttlSeconds)}},"asyncCheck")();let M=await E.get(I);if(M!==void 0&&M>Date.now()){Cu(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${I}' (async mode)`);let F=Math.round((M-Date.now())/1e3);return s(p,F)}return e.addResponseSendingHook(async F=>O??F),n},"AsyncRateLimitInboundPolicyImpl");function ji(n,e){if(n===null)throw new Error(`RateLimitInboundPolicy - Invalid ${e} value: null`);if(n==="")throw new Error(`RateLimitInboundPolicy - Invalid ${e} value: empty string`);if(typeof n=="number")return n;if(typeof n!="number"){let t=Number(n);if(isNaN(t)||!Number.isInteger(t))throw new Error(`RateLimitInboundPolicy - Invalid ${e} value not of type integer: ${n}`);return t}throw new Error(`RateLimitInboundPolicy - Invalid ${e} value: ${n}`)}i(ji,"convertToNumber");var Ou=be("zuplo:policies:RateLimitInboundPolicy"),Op="strict",Au=i(async(n,e,t,r)=>{if(f("policy.inbound.rate-limit"),(t.mode??Op)==="async")return Su(n,e,t,r);let s=Date.now(),a=J.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[Ct]=d.toString()),T.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await vt(r,t)(n,e,r),p=d.key,m=ji(d.requestsAllowed??t.requestsAllowed,"requestsAllowed"),h=ji(d.timeWindowMinutes??t.timeWindowMinutes,"timeWindowMinutes"),I=t.headerMode??"retry-after",b=nt(r,a),L=`rate-limit${y.instance.isTestMode||y.instance.isWorkingCopy?y.instance.build.BUILD_ID:""}/${r}/${p}`,O=await b.getCountAndUpdateExpiry(L,h,e.requestId);return O.count>m?(Ou(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${L}' (strict mode)`),c(I,O.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-s;Ou(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var zi;function ku(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}i(ku,"headersToNameValuePairs");function Ap(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}i(Ap,"queryToNameValueParis");function kp(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}i(kp,"parseIntOrUndefined");var Lu={};async function Lp(n,e,t,r){f("policy.inbound.readme-metrics");let o=new Date,s=Date.now();return zi||(zi={name:"zuplo",version:y.instance.build.ZUPLO_VERSION,comment:`zuplo/${y.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?Fe(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?Fe(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:y.instance.isWorkingCopy||y.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:zi,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:ku(n.headers),queryString:Ap(n.query)},response:{status:a.status,statusText:a.statusText,headers:ku(a.headers),content:{size:kp(n.headers.get("content-length"))}}}]}}},d=Lu[t.apiKey];if(!d){let p=t.apiKey;d=new K("readme-metering-inbound-policy",10,async m=>{try{let h=t.url??"https://metrics.readme.io/request",I=await $.fetch(h,{method:"POST",body:JSON.stringify(m),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});I.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${I.status}: '${await I.text()}'`)}catch(h){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${h.message}'`),h}}),Lu[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}i(Lp,"ReadmeMetricsInboundPolicy");var _p=i(async(n,e,t,r)=>{f("policy.inbound.remove-headers");let o=t?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new g(`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 ee(n,{headers:s})},"RemoveHeadersInboundPolicy");var Np=i(async(n,e,t,r,o)=>{f("policy.outbound.remove-headers");let s=r?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new g(`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 Dp=i(async(n,e,t,r)=>{f("policy.inbound.remove-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length===0)throw new g(`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 ee(s.toString(),n)},"RemoveQueryParamsInboundPolicy");var Mp=i(async(n,e,t,r)=>{f("policy.outbound.replace-string");let o=await n.text(),s=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(s,r.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var _u=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),qp=i(async(n,e,t)=>{f("policy.inbound.request-size-limit");let r=t.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(n.method))return n;let o=n.headers.get("content-length"),s=o!==null?parseInt(o):void 0;return s&&!isNaN(s)&&s>t.maxSizeInBytes?_u():s&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?_u():n},"RequestSizeLimitInboundPolicy");var _t=i(n=>{let e=n.route.raw();return e.parameters?e.parameters:[]},"getParametersForOperation"),Nt=i((n,e,t,r,o)=>{let s=[],a=!0,u=[];return n.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,s.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=cr(t,r,o,c.name),p=ge.instance.schemaValidator[d],m=p(e[c.name]),h=Bi(p.errors);m||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${h.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),Le=i((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),_e=i(n=>n==="log-only"||n==="reject-and-log","shouldLog"),Ne=i(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),Bi=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 Nu(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(h){let I=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,b=T.badRequest(e,n,{detail:`${I}, see errors property for more details`,errors:`${h}`});if(_e(t.validateBody)&&Le(n,t.logLevel??"info",I,[r],h),Ne(t.validateBody))return b}if(!e.headers.get("Content-Type")){let h=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,I=T.badRequest(e,n,{detail:h});return _e(t.validateBody)&&Le(n,t.logLevel??"info",h,[r],[h]),Ne(t.validateBody)?I:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=lr(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")}`,I=T.badRequest(e,n,{detail:h});return _e(t.validateBody)&&Le(n,t.logLevel??"info",h,[r],[h]),Ne(t.validateBody)?I:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Bi(l),m=T.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(_e(t.validateBody)&&Le(n,t.logLevel??"info",d,[r],p),Ne(t.validateBody))return m}i(Nu,"handleBodyValidation");function Du(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=_t(n),s=Nt(o.filter(a=>a.in==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=T.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:s.errors});if(_e(t.validateHeaders)&&Le(n,t.logLevel??"info",a,s.invalidValues,s.errors),Ne(t.validateHeaders))return u}}i(Du,"handleHeadersValidation");function Mu(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=_t(n),o=Nt(r.filter(s=>s.in==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let s="Path parameters validation failed",a=T.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(_e(t.validatePathParameters)&&Le(n,t.logLevel??"info",s,o.invalidValues,o.errors),Ne(t.validatePathParameters))return a}}i(Mu,"handlePathParameterValidation");function qu(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=_t(n),o=Nt(r.filter(s=>s.in==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let s="Query parameters validation failed",a=T.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(_e(t.validateQueryParameters)&&Le(n,t.logLevel??"info",s,o.invalidValues,o.errors),Ne(t.validateQueryParameters))return a}}i(qu,"handleQueryParameterValidation");var Uu=i(async(n,e,t)=>{f("policy.inbound.request-validation");let r=qu(e,n,t);if(r!==void 0||(r=Mu(e,n,t),r!==void 0)||(r=Du(e,n,t),r!==void 0))return r;let o=await Nu(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),Up=Uu;var Hp=i(async(n,e,t,r)=>{if(f("policy.inbound.require-origin"),t.origins===void 0||t.origins.length===0)throw new g(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof t.origins=="string"?t.origins.split(","):t.origins;o=o.map(a=>a.trim());let s=n.headers.get("origin");if(!s||!o.includes(s)){let a=t.failureDetail??"Forbidden";return T.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var $p=i(async(n,e,t)=>(f("policy.inbound.set-body"),new ee(n,{body:t.body})),"SetBodyInboundPolicy");var Zp=i(async(n,e,t,r)=>{f("policy.inbound.set-headers");let o=t.headers;if(!o||!Array.isArray(o)||o.length==0)throw new g(`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 g(`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 ee(n,{headers:s})},"SetHeadersInboundPolicy");var Fp=i(async(n,e,t,r,o)=>{f("policy.outbound.set-headers");let s=r.headers;if(!s||!Array.isArray(s)||s.length==0)throw new g(`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 g(`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 jp=i(async(n,e,t,r)=>{f("policy.inbound.set-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length==0)throw new g(`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 g(`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 ee(s.toString(),n)},"SetQueryParamsInboundPolicy");var zp=i(async(n,e,t,r,o)=>{if(f("policy.outbound.set-status"),!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new g(`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 Bp=i(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),Gp=i(async(n,e,t,r)=>{if(f("policy.inbound.sleep"),!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new g(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await Bp(t.sleepInMs),n},"SleepInboundPolicy");var Vp=i(async(n,e,t,r)=>{f("policy.inbound.supabase-jwt-auth"),W(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},s=await Ee(n,e,o,r);if(s instanceof Response)return s;if(!(s instanceof ee))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 k(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?T.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var Wp=i(async(n,e,t,r)=>{f("policy.inbound.upstream-azure-ad-service-auth"),W(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await ie(r,void 0,t),s=new re(o,e),a=await s.get(r);if(!a){let u=await Jp(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 Jp(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await we({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 k("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new k("Response returned from Azure AD is not in the expected format.")}i(Jp,"getAccessToken");var Hu="https://accounts.google.com/o/oauth2/token",Gi,Kp=i(async(n,e,t,r)=>{f("policy.inbound.upstream-firebase-admin-auth"),W(t,r).required("serviceAccountJson","string"),Gi||(Gi=await Ie.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 ie(r,void 0,t),a=new re(s,e),u=await a.get(r);if(!u){let c=await Ae({serviceAccount:Gi,audience:Hu,payload:o}),l=await yt(Hu,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new k("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var Qp="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Yp=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Vi,Xp=i(async(n,e,t,r)=>{if(f("policy.inbound.upstream-firebase-user-auth"),W(t,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!t.userId&&!t.userIdPropertyPath)throw new g(`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(Yp.indexOf(p)!==-1)throw new g(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}Vi||(Vi=await Ie.init(t.serviceAccountJson));let s=t.userId;if(!s&&!t.userIdPropertyPath){if(!n.user)throw new k("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new k(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=Fe(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new k(`Unable to determine user from for the policy ${r}`);let a=await ie(r,void 0,t),u=new re(a,e),c={uid:s,claims:o},l=await ct(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await Ae({serviceAccount:Vi,audience:Qp,payload:c}),m=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,h=await ya(m,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!h.idToken)throw new k("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 dn=class{static{i(this,"ZuploServices")}static async getIDToken(e,t){let r=new re("0c13603a-a19f-4f03-a04a-50aa393f7ffa-zuplo-tokens",e),o=await ie("zuplo-token",void 0,t),s=await r.get(o);if(s)return s;let{authClientId:a,authClientSecret:u,developerApiUrl:c,zuploClientAuthBucketId:l}=y.instance;if(!a||!u)throw new k("Zuplo service authentication is not enabled for this deployment. Contact support assistance.");let d=await or({tokenEndpointUrl:`${c}/v1/client-auth/${l}/oauth/token`,clientId:a,clientSecret:u,audience:t?.audience},e);return r.put(o,d.access_token,d.expires_in-300),d.access_token}};var $u="service-account-id-token",Wi=class extends ae{static{i(this,"UpstreamGcpFederatedAuthInboundPolicy")}cacheName;normalizedWorkloadIdentityProvider;constructor(e,t){super(e,t),f("policy.inbound.upstream-gcp-federated-auth"),W(e,t).required("audience","string").required("serviceAccountEmail","string").required("workloadIdentityProvider","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number").optional("useMemoryCacheOnly","boolean").optional("tokenLifetime","number"),e.workloadIdentityProvider.startsWith("https://iam.googleapis.com/")?this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider.replace("https://iam.googleapis.com/",""):this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider}async handler(e,t){this.cacheName||(this.cacheName=await ie(this.policyName,void 0,this.options));let r;this.options.useMemoryCacheOnly?r=new Me(this.cacheName):r=new re(this.cacheName,t);let o=await r.get($u);if(!o){let s=`https://iam.googleapis.com/${this.normalizedWorkloadIdentityProvider}`,a=await dn.getIDToken(t,{audience:s}),u=await fa(this.normalizedWorkloadIdentityProvider,a,{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!u.access_token||!u.expires_in)throw new k("Invalid token response from GCP");let c=u.access_token,l=await ha({serviceAccountEmailOrIdentifier:this.options.serviceAccountEmail,audience:this.options.audience,accessToken:c},{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!l.token)throw new k("Invalid token response from GCP");o=l.token,r.put($u,c,3600-(this.options.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${o}`),e}};var Ji,em=i(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-jwt"),W(t,r).required("audience","string").required("serviceAccountJson","string"),Ji||(Ji=await Ie.init(t.serviceAccountJson));let o=await Ae({serviceAccount:Ji,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var Zu="https://www.googleapis.com/oauth2/v4/token",Ki,Fu=i(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-service-auth"),W(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Ki||(Ki=await Ie.init(t.serviceAccountJson));let o={};if(t.scopes&&t.audience)throw new g("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let c=je(t.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof g?new g(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}t.audience&&(o.target_audience=`${t.audience}`);let s=await ie(r,void 0,t),a;t.useMemoryCacheOnly?a=new Me(s):a=new re(s,e);let u=await a.get(r);if(!u){let c=await Ae({serviceAccount:Ki,audience:Zu,payload:o}),l=await yt(Zu,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new k("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new k("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicyV1");var ju="https://www.googleapis.com/oauth2/v4/token",Qi,zu=i(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-service-auth"),W(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=t.expirationOffsetSeconds??300;if(t.scopes&&t.audience)throw new g("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");let s=await ie(r,"v2",t),a;t.useMemoryCacheOnly?a=new Me(s):a=new re(s,e),Re.getContextExtensions(e).addHandlerResponseHook(async(d,p,m)=>{if(d.status===403){let I=`UpstreamGcpServiceAuthInboundPolicy - Handler returned a 403 response. Error: ${d.headers.get("www-authenticate")??"unknown"}. Refreshing GCP token.`;J.getLogger(m).error(I),m.log.error(I),await a.delete(r)}});let c=await a.get(r);return c&&c.expirationTime-o<new Date().getTime()&&(J.getLogger(e).error(`UpstreamGcpServiceAuthInboundPolicy - Expired token returned from cache for policy ${r}`),c=void 0),c&&c.audience!==t.audience&&(J.getLogger(e).error(`UpstreamGcpServiceAuthInboundPolicy - Token with audience ${c.audience} returned from cache for policy ${r} does not match the current audience ${t.audience}`),c=void 0),c||(c=await l()),n.headers.set("Authorization",`Bearer ${c.token}`),n;async function l(){Qi||(Qi=await Ie.init(t.serviceAccountJson));let d={};if(t.scopes)try{let E=je(t.scopes);d.scope=E.join(" ")}catch(E){throw E instanceof g?new g(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${E.message}`):E}t.audience&&(d.target_audience=`${t.audience}`);let p=await Ae({serviceAccount:Qi,audience:ju,payload:d}),m=await yt(ju,p,{retries:t.tokenRetries??3,retryDelayMs:10}),h=m.expires_in??3600,I=new Date().getTime()+h*1e3;if(t.audience){if(!m.id_token)throw new k("Invalid token response from GCP");c={token:m.id_token,expirationTime:I,audience:t.audience}}else{if(!m.access_token)throw new k("Invalid token response from GCP");c={token:m.access_token,expirationTime:I,audience:void 0}}let b=h-o;if(b<=0)throw new k(`UpstreamGcpServiceAuthInboundPolicy - Token TTL is less than the expiration offset. TTL: ${b}, expiration offset: ${o}`);return a.put(r,c,b),c}i(l,"retrieveGcpServiceToken")},"UpstreamGcpServiceAuthInboundPolicyV2");var tm=i(async(n,e,t,r)=>t.version===2?await zu(n,e,t,r):await Fu(n,e,t,r),"UpstreamGcpServiceAuthInboundPolicy");var nm=i(async(n,e,t)=>{f("policy.inbound.validate-json-schema");let r=n.clone(),o;try{o=await r.json()}catch{return T.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator.default(o))return n;let{errors:a}=t.validator.default;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 T.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var Bu=i(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=i((b,E)=>e(b,"name",{value:E,configurable:!0}),"__name"),o=i((b,E)=>i(function(){return E||(0,b[t(b)[0]])((E={exports:{}}).exports,E),E.exports},"__require"),"__commonJS"),s=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(b){var E={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:i(function(O,Z){return Z},"tagValueProcessor"),attributeValueProcessor:i(function(O,Z){return Z},"attributeValueProcessor"),stopNodes:[],alwaysCreateTextNode:!1,isArray:i(()=>!1,"isArray"),commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:i(function(O,Z,M){return O},"updateTag")},L=r(function(O){return Object.assign({},E,O)},"buildOptions");b.buildOptions=L,b.defaultOptions=E}}),a=o({"node_modules/fast-xml-parser/src/util.js"(b){"use strict";var E=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",L=E+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",O="["+E+"]["+L+"]*",Z=new RegExp("^"+O+"$"),M=r(function(S,H){let V=[],j=H.exec(S);for(;j;){let v=[];v.startIndex=H.lastIndex-j[0].length;let x=j.length;for(let q=0;q<x;q++)v.push(j[q]);V.push(v),j=H.exec(S)}return V},"getAllMatches"),F=r(function(S){let H=Z.exec(S);return!(H===null||typeof H>"u")},"isName");b.isExist=function(S){return typeof S<"u"},b.isEmptyObject=function(S){return Object.keys(S).length===0},b.merge=function(S,H,V){if(H){let j=Object.keys(H),v=j.length;for(let x=0;x<v;x++)V==="strict"?S[j[x]]=[H[j[x]]]:S[j[x]]=H[j[x]]}},b.getValue=function(S){return b.isExist(S)?S:""},b.isName=F,b.getAllMatches=M,b.nameRegexp=O}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(b,E){"use strict";var L=class{static{i(this,"XmlNode")}static{r(this,"XmlNode")}constructor(O){this.tagname=O,this.child=[],this[":@"]={}}add(O,Z){O==="__proto__"&&(O="#__proto__"),this.child.push({[O]:Z})}addChild(O){O.tagname==="__proto__"&&(O.tagname="#__proto__"),O[":@"]&&Object.keys(O[":@"]).length>0?this.child.push({[O.tagname]:O.child,":@":O[":@"]}):this.child.push({[O.tagname]:O.child})}};E.exports=L}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(b,E){var L=a();function O(v,x){let q={};if(v[x+3]==="O"&&v[x+4]==="C"&&v[x+5]==="T"&&v[x+6]==="Y"&&v[x+7]==="P"&&v[x+8]==="E"){x=x+9;let ce=1,X=!1,te=!1,Se="";for(;x<v.length;x++)if(v[x]==="<"&&!te){if(X&&F(v,x))x+=7,[entityName,val,x]=Z(v,x+1),val.indexOf("&")===-1&&(q[j(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(X&&S(v,x))x+=8;else if(X&&H(v,x))x+=8;else if(X&&V(v,x))x+=9;else if(M)te=!0;else throw new Error("Invalid DOCTYPE");ce++,Se=""}else if(v[x]===">"){if(te?v[x-1]==="-"&&v[x-2]==="-"&&(te=!1,ce--):ce--,ce===0)break}else v[x]==="["?X=!0:Se+=v[x];if(ce!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:q,i:x}}i(O,"readDocType"),r(O,"readDocType");function Z(v,x){let q="";for(;x<v.length&&v[x]!=="'"&&v[x]!=='"';x++)q+=v[x];if(q=q.trim(),q.indexOf(" ")!==-1)throw new Error("External entites are not supported");let ce=v[x++],X="";for(;x<v.length&&v[x]!==ce;x++)X+=v[x];return[q,X,x]}i(Z,"readEntityExp"),r(Z,"readEntityExp");function M(v,x){return v[x+1]==="!"&&v[x+2]==="-"&&v[x+3]==="-"}i(M,"isComment"),r(M,"isComment");function F(v,x){return v[x+1]==="!"&&v[x+2]==="E"&&v[x+3]==="N"&&v[x+4]==="T"&&v[x+5]==="I"&&v[x+6]==="T"&&v[x+7]==="Y"}i(F,"isEntity"),r(F,"isEntity");function S(v,x){return v[x+1]==="!"&&v[x+2]==="E"&&v[x+3]==="L"&&v[x+4]==="E"&&v[x+5]==="M"&&v[x+6]==="E"&&v[x+7]==="N"&&v[x+8]==="T"}i(S,"isElement"),r(S,"isElement");function H(v,x){return v[x+1]==="!"&&v[x+2]==="A"&&v[x+3]==="T"&&v[x+4]==="T"&&v[x+5]==="L"&&v[x+6]==="I"&&v[x+7]==="S"&&v[x+8]==="T"}i(H,"isAttlist"),r(H,"isAttlist");function V(v,x){return v[x+1]==="!"&&v[x+2]==="N"&&v[x+3]==="O"&&v[x+4]==="T"&&v[x+5]==="A"&&v[x+6]==="T"&&v[x+7]==="I"&&v[x+8]==="O"&&v[x+9]==="N"}i(V,"isNotation"),r(V,"isNotation");function j(v){if(L.isName(v))return v;throw new Error(`Invalid entity name ${v}`)}i(j,"validateEntityName"),r(j,"validateEntityName"),E.exports=O}}),l=o({"../../node_modules/strnum/strnum.js"(b,E){var L=/^[-+]?0x[a-fA-F0-9]+$/,O=/^([\-\+])?(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 Z={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function M(S,H={}){if(H=Object.assign({},Z,H),!S||typeof S!="string")return S;let V=S.trim();if(H.skipLike!==void 0&&H.skipLike.test(V))return S;if(H.hex&&L.test(V))return Number.parseInt(V,16);{let j=O.exec(V);if(j){let v=j[1],x=j[2],q=F(j[3]),ce=j[4]||j[6];if(!H.leadingZeros&&x.length>0&&v&&V[2]!==".")return S;if(!H.leadingZeros&&x.length>0&&!v&&V[1]!==".")return S;{let X=Number(V),te=""+X;return te.search(/[eE]/)!==-1||ce?H.eNotation?X:S:V.indexOf(".")!==-1?te==="0"&&q===""||te===q||v&&te==="-"+q?X:S:x?q===te||v+q===te?X:S:V===te||V===v+te?X:S}}else return S}}i(M,"toNumber"),r(M,"toNumber");function F(S){return S&&S.indexOf(".")!==-1&&(S=S.replace(/0+$/,""),S==="."?S="0":S[0]==="."?S="0"+S:S[S.length-1]==="."&&(S=S.substr(0,S.length-1))),S}i(F,"trimZeros"),r(F,"trimZeros"),E.exports=M}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(b,E){"use strict";var L=a(),O=u(),Z=c(),M=l(),F=class{static{i(this,"OrderedObjParser")}static{r(this,"OrderedObjParser")}constructor(P){this.options=P,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:i((C,_)=>String.fromCharCode(Number.parseInt(_,10)),"val")},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:i((C,_)=>String.fromCharCode(Number.parseInt(_,16)),"val")}},this.addExternalEntities=S,this.parseXml=x,this.parseTextData=H,this.resolveNameSpace=V,this.buildAttributesMap=v,this.isItStopNode=te,this.replaceEntitiesValue=ce,this.readStopNodeData=G,this.saveTextToParentTag=X,this.addChild=q}};function S(P){let C=Object.keys(P);for(let _=0;_<C.length;_++){let B=C[_];this.lastEntities[B]={regex:new RegExp("&"+B+";","g"),val:P[B]}}}i(S,"addExternalEntities"),r(S,"addExternalEntities");function H(P,C,_,B,N,D,ne){if(P!==void 0&&(this.options.trimValues&&!B&&(P=P.trim()),P.length>0)){ne||(P=this.replaceEntitiesValue(P));let z=this.options.tagValueProcessor(C,P,_,N,D);return z==null?P:typeof z!=typeof P||z!==P?z:this.options.trimValues?me(P,this.options.parseTagValue,this.options.numberParseOptions):P.trim()===P?me(P,this.options.parseTagValue,this.options.numberParseOptions):P}}i(H,"parseTextData"),r(H,"parseTextData");function V(P){if(this.options.removeNSPrefix){let C=P.split(":"),_=P.charAt(0)==="/"?"/":"";if(C[0]==="xmlns")return"";C.length===2&&(P=_+C[1])}return P}i(V,"resolveNameSpace"),r(V,"resolveNameSpace");var j=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function v(P,C,_){if(!this.options.ignoreAttributes&&typeof P=="string"){let B=L.getAllMatches(P,j),N=B.length,D={};for(let ne=0;ne<N;ne++){let z=this.resolveNameSpace(B[ne][1]),U=B[ne][4],de=this.options.attributeNamePrefix+z;if(z.length)if(this.options.transformAttributeName&&(de=this.options.transformAttributeName(de)),de==="__proto__"&&(de="#__proto__"),U!==void 0){this.options.trimValues&&(U=U.trim()),U=this.replaceEntitiesValue(U);let se=this.options.attributeValueProcessor(z,U,C);se==null?D[de]=U:typeof se!=typeof U||se!==U?D[de]=se:D[de]=me(U,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(D[de]=!0)}if(!Object.keys(D).length)return;if(this.options.attributesGroupName){let ne={};return ne[this.options.attributesGroupName]=D,ne}return D}}i(v,"buildAttributesMap"),r(v,"buildAttributesMap");var x=r(function(P){P=P.replace(/\r\n?/g,`
91
91
  `);let C=new O("!xml"),_=C,B="",N="";for(let D=0;D<P.length;D++)if(P[D]==="<")if(P[D+1]==="/"){let z=w(P,">",D,"Closing Tag is not closed."),U=P.substring(D+2,z).trim();if(this.options.removeNSPrefix){let ke=U.indexOf(":");ke!==-1&&(U=U.substr(ke+1))}this.options.transformTagName&&(U=this.options.transformTagName(U)),_&&(B=this.saveTextToParentTag(B,_,N));let de=N.substring(N.lastIndexOf(".")+1);if(U&&this.options.unpairedTags.indexOf(U)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${U}>`);let se=0;de&&this.options.unpairedTags.indexOf(de)!==-1?(se=N.lastIndexOf(".",N.lastIndexOf(".")-1),this.tagsNodeStack.pop()):se=N.lastIndexOf("."),N=N.substring(0,se),_=this.tagsNodeStack.pop(),B="",D=z}else if(P[D+1]==="?"){let z=A(P,D,!1,"?>");if(!z)throw new Error("Pi Tag is not closed.");if(B=this.saveTextToParentTag(B,_,N),!(this.options.ignoreDeclaration&&z.tagName==="?xml"||this.options.ignorePiTags)){let U=new O(z.tagName);U.add(this.options.textNodeName,""),z.tagName!==z.tagExp&&z.attrExpPresent&&(U[":@"]=this.buildAttributesMap(z.tagExp,N,z.tagName)),this.addChild(_,U,N)}D=z.closeIndex+1}else if(P.substr(D+1,3)==="!--"){let z=w(P,"-->",D+4,"Comment is not closed.");if(this.options.commentPropName){let U=P.substring(D+4,z-2);B=this.saveTextToParentTag(B,_,N),_.add(this.options.commentPropName,[{[this.options.textNodeName]:U}])}D=z}else if(P.substr(D+1,2)==="!D"){let z=Z(P,D);this.docTypeEntities=z.entities,D=z.i}else if(P.substr(D+1,2)==="!["){let z=w(P,"]]>",D,"CDATA is not closed.")-2,U=P.substring(D+9,z);B=this.saveTextToParentTag(B,_,N);let de=this.parseTextData(U,_.tagname,N,!0,!1,!0,!0);de==null&&(de=""),this.options.cdataPropName?_.add(this.options.cdataPropName,[{[this.options.textNodeName]:U}]):_.add(this.options.textNodeName,de),D=z+2}else{let z=A(P,D,this.options.removeNSPrefix),U=z.tagName,de=z.rawTagName,se=z.tagExp,ke=z.attrExpPresent,ns=z.closeIndex;this.options.transformTagName&&(U=this.options.transformTagName(U)),_&&B&&_.tagname!=="!xml"&&(B=this.saveTextToParentTag(B,_,N,!1));let rs=_;if(rs&&this.options.unpairedTags.indexOf(rs.tagname)!==-1&&(_=this.tagsNodeStack.pop(),N=N.substring(0,N.lastIndexOf("."))),U!==C.tagname&&(N+=N?"."+U:U),this.isItStopNode(this.options.stopNodes,N,U)){let Oe="";if(se.length>0&&se.lastIndexOf("/")===se.length-1)D=z.closeIndex;else if(this.options.unpairedTags.indexOf(U)!==-1)D=z.closeIndex;else{let ur=this.readStopNodeData(P,de,ns+1);if(!ur)throw new Error(`Unexpected end of ${de}`);D=ur.i,Oe=ur.tagContent}let ar=new O(U);U!==se&&ke&&(ar[":@"]=this.buildAttributesMap(se,N,U)),Oe&&(Oe=this.parseTextData(Oe,U,N,!0,ke,!0,!0)),N=N.substr(0,N.lastIndexOf(".")),ar.add(this.options.textNodeName,Oe),this.addChild(_,ar,N)}else{if(se.length>0&&se.lastIndexOf("/")===se.length-1){U[U.length-1]==="/"?(U=U.substr(0,U.length-1),N=N.substr(0,N.length-1),se=U):se=se.substr(0,se.length-1),this.options.transformTagName&&(U=this.options.transformTagName(U));let Oe=new O(U);U!==se&&ke&&(Oe[":@"]=this.buildAttributesMap(se,N,U)),this.addChild(_,Oe,N),N=N.substr(0,N.lastIndexOf("."))}else{let Oe=new O(U);this.tagsNodeStack.push(_),U!==se&&ke&&(Oe[":@"]=this.buildAttributesMap(se,N,U)),this.addChild(_,Oe,N),_=Oe}B="",D=ns}}else B+=P[D];return C.child},"parseXml");function q(P,C,_){let B=this.options.updateTag(C.tagname,_,C[":@"]);B===!1||(typeof B=="string"&&(C.tagname=B),P.addChild(C))}i(q,"addChild"),r(q,"addChild");var ce=r(function(P){if(this.options.processEntities){for(let C in this.docTypeEntities){let _=this.docTypeEntities[C];P=P.replace(_.regx,_.val)}for(let C in this.lastEntities){let _=this.lastEntities[C];P=P.replace(_.regex,_.val)}if(this.options.htmlEntities)for(let C in this.htmlEntities){let _=this.htmlEntities[C];P=P.replace(_.regex,_.val)}P=P.replace(this.ampEntity.regex,this.ampEntity.val)}return P},"replaceEntitiesValue");function X(P,C,_,B){return P&&(B===void 0&&(B=Object.keys(C.child).length===0),P=this.parseTextData(P,C.tagname,_,!1,C[":@"]?Object.keys(C[":@"]).length!==0:!1,B),P!==void 0&&P!==""&&C.add(this.options.textNodeName,P),P=""),P}i(X,"saveTextToParentTag"),r(X,"saveTextToParentTag");function te(P,C,_){let B="*."+_;for(let N in P){let D=P[N];if(B===D||C===D)return!0}return!1}i(te,"isItStopNode"),r(te,"isItStopNode");function Se(P,C,_=">"){let B,N="";for(let D=C;D<P.length;D++){let ne=P[D];if(B)ne===B&&(B="");else if(ne==='"'||ne==="'")B=ne;else if(ne===_[0])if(_[1]){if(P[D+1]===_[1])return{data:N,index:D}}else return{data:N,index:D};else ne===" "&&(ne=" ");N+=ne}}i(Se,"tagExpWithClosingIndex"),r(Se,"tagExpWithClosingIndex");function w(P,C,_,B){let N=P.indexOf(C,_);if(N===-1)throw new Error(B);return N+C.length-1}i(w,"findClosingIndex"),r(w,"findClosingIndex");function A(P,C,_,B=">"){let N=Se(P,C+1,B);if(!N)return;let D=N.data,ne=N.index,z=D.search(/\s/),U=D,de=!0;z!==-1&&(U=D.substring(0,z),D=D.substring(z+1).trimStart());let se=U;if(_){let ke=U.indexOf(":");ke!==-1&&(U=U.substr(ke+1),de=U!==N.data.substr(ke+1))}return{tagName:U,tagExp:D,closeIndex:ne,attrExpPresent:de,rawTagName:se}}i(A,"readTagExp"),r(A,"readTagExp");function G(P,C,_){let B=_,N=1;for(;_<P.length;_++)if(P[_]==="<")if(P[_+1]==="/"){let D=w(P,">",_,`${C} is not closed`);if(P.substring(_+2,D).trim()===C&&(N--,N===0))return{tagContent:P.substring(B,_),i:D};_=D}else if(P[_+1]==="?")_=w(P,"?>",_+1,"StopNode is not closed.");else if(P.substr(_+1,3)==="!--")_=w(P,"-->",_+3,"StopNode is not closed.");else if(P.substr(_+1,2)==="![")_=w(P,"]]>",_,"StopNode is not closed.")-2;else{let D=A(P,_,">");D&&((D&&D.tagName)===C&&D.tagExp[D.tagExp.length-1]!=="/"&&N++,_=D.closeIndex)}}i(G,"readStopNodeData"),r(G,"readStopNodeData");function me(P,C,_){if(C&&typeof P=="string"){let B=P.trim();return B==="true"?!0:B==="false"?!1:M(P,_)}else return L.isExist(P)?P:""}i(me,"parseValue"),r(me,"parseValue"),E.exports=F}}),p=o({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(b){"use strict";function E(F,S){return L(F,S)}i(E,"prettify"),r(E,"prettify");function L(F,S,H){let V,j={};for(let v=0;v<F.length;v++){let x=F[v],q=O(x),ce="";if(H===void 0?ce=q:ce=H+"."+q,q===S.textNodeName)V===void 0?V=x[q]:V+=""+x[q];else{if(q===void 0)continue;if(x[q]){let X=L(x[q],S,ce),te=M(X,S);x[":@"]?Z(X,x[":@"],ce,S):Object.keys(X).length===1&&X[S.textNodeName]!==void 0&&!S.alwaysCreateTextNode?X=X[S.textNodeName]:Object.keys(X).length===0&&(S.alwaysCreateTextNode?X[S.textNodeName]="":X=""),j[q]!==void 0&&j.hasOwnProperty(q)?(Array.isArray(j[q])||(j[q]=[j[q]]),j[q].push(X)):S.isArray(q,ce,te)?j[q]=[X]:j[q]=X}}}return typeof V=="string"?V.length>0&&(j[S.textNodeName]=V):V!==void 0&&(j[S.textNodeName]=V),j}i(L,"compress"),r(L,"compress");function O(F){let S=Object.keys(F);for(let H=0;H<S.length;H++){let V=S[H];if(V!==":@")return V}}i(O,"propName"),r(O,"propName");function Z(F,S,H,V){if(S){let j=Object.keys(S),v=j.length;for(let x=0;x<v;x++){let q=j[x];V.isArray(q,H+"."+q,!0,!0)?F[q]=[S[q]]:F[q]=S[q]}}}i(Z,"assignAttributes"),r(Z,"assignAttributes");function M(F,S){let{textNodeName:H}=S,V=Object.keys(F).length;return!!(V===0||V===1&&(F[H]||typeof F[H]=="boolean"||F[H]===0))}i(M,"isLeafTag"),r(M,"isLeafTag"),b.prettify=E}}),m=o({"node_modules/fast-xml-parser/src/validator.js"(b){"use strict";var E=a(),L={allowBooleanAttributes:!1,unpairedTags:[]};b.validate=function(w,A){A=Object.assign({},L,A);let G=[],me=!1,P=!1;w[0]==="\uFEFF"&&(w=w.substr(1));for(let C=0;C<w.length;C++)if(w[C]==="<"&&w[C+1]==="?"){if(C+=2,C=Z(w,C),C.err)return C}else if(w[C]==="<"){let _=C;if(C++,w[C]==="!"){C=M(w,C);continue}else{let B=!1;w[C]==="/"&&(B=!0,C++);let N="";for(;C<w.length&&w[C]!==">"&&w[C]!==" "&&w[C]!==" "&&w[C]!==`
92
92
  `&&w[C]!=="\r";C++)N+=w[C];if(N=N.trim(),N[N.length-1]==="/"&&(N=N.substring(0,N.length-1),C--),!X(N)){let z;return N.trim().length===0?z="Invalid space after '<'.":z="Tag '"+N+"' is an invalid name.",q("InvalidTag",z,te(w,C))}let D=H(w,C);if(D===!1)return q("InvalidAttr","Attributes for '"+N+"' have open quote.",te(w,C));let ne=D.value;if(C=D.index,ne[ne.length-1]==="/"){let z=C-ne.length;ne=ne.substring(0,ne.length-1);let U=j(ne,A);if(U===!0)me=!0;else return q(U.err.code,U.err.msg,te(w,z+U.err.line))}else if(B)if(D.tagClosed){if(ne.trim().length>0)return q("InvalidTag","Closing tag '"+N+"' can't have attributes or invalid starting.",te(w,_));{let z=G.pop();if(N!==z.tagName){let U=te(w,z.tagStartPos);return q("InvalidTag","Expected closing tag '"+z.tagName+"' (opened in line "+U.line+", col "+U.col+") instead of closing tag '"+N+"'.",te(w,_))}G.length==0&&(P=!0)}}else return q("InvalidTag","Closing tag '"+N+"' doesn't have proper closing.",te(w,C));else{let z=j(ne,A);if(z!==!0)return q(z.err.code,z.err.msg,te(w,C-ne.length+z.err.line));if(P===!0)return q("InvalidXml","Multiple possible root nodes found.",te(w,C));A.unpairedTags.indexOf(N)!==-1||G.push({tagName:N,tagStartPos:_}),me=!0}for(C++;C<w.length;C++)if(w[C]==="<")if(w[C+1]==="!"){C++,C=M(w,C);continue}else if(w[C+1]==="?"){if(C=Z(w,++C),C.err)return C}else break;else if(w[C]==="&"){let z=x(w,C);if(z==-1)return q("InvalidChar","char '&' is not expected.",te(w,C));C=z}else if(P===!0&&!O(w[C]))return q("InvalidXml","Extra text at the end",te(w,C));w[C]==="<"&&C--}}else{if(O(w[C]))continue;return q("InvalidChar","char '"+w[C]+"' is not expected.",te(w,C))}if(me){if(G.length==1)return q("InvalidTag","Unclosed tag '"+G[0].tagName+"'.",te(w,G[0].tagStartPos));if(G.length>0)return q("InvalidXml","Invalid '"+JSON.stringify(G.map(C=>C.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return q("InvalidXml","Start tag expected.",1);return!0};function O(w){return w===" "||w===" "||w===`
93
- `||w==="\r"}i(O,"isWhiteSpace"),r(O,"isWhiteSpace");function Z(w,A){let G=A;for(;A<w.length;A++)if(w[A]=="?"||w[A]==" "){let me=w.substr(G,A-G);if(A>5&&me==="xml")return q("InvalidXml","XML declaration allowed only at the start of the document.",te(w,A));if(w[A]=="?"&&w[A+1]==">"){A++;break}else continue}return A}i(Z,"readPI"),r(Z,"readPI");function M(w,A){if(w.length>A+5&&w[A+1]==="-"&&w[A+2]==="-"){for(A+=3;A<w.length;A++)if(w[A]==="-"&&w[A+1]==="-"&&w[A+2]===">"){A+=2;break}}else if(w.length>A+8&&w[A+1]==="D"&&w[A+2]==="O"&&w[A+3]==="C"&&w[A+4]==="T"&&w[A+5]==="Y"&&w[A+6]==="P"&&w[A+7]==="E"){let G=1;for(A+=8;A<w.length;A++)if(w[A]==="<")G++;else if(w[A]===">"&&(G--,G===0))break}else if(w.length>A+9&&w[A+1]==="["&&w[A+2]==="C"&&w[A+3]==="D"&&w[A+4]==="A"&&w[A+5]==="T"&&w[A+6]==="A"&&w[A+7]==="["){for(A+=8;A<w.length;A++)if(w[A]==="]"&&w[A+1]==="]"&&w[A+2]===">"){A+=2;break}}return A}i(M,"readCommentAndCDATA"),r(M,"readCommentAndCDATA");var F='"',S="'";function H(w,A){let G="",me="",P=!1;for(;A<w.length;A++){if(w[A]===F||w[A]===S)me===""?me=w[A]:me!==w[A]||(me="");else if(w[A]===">"&&me===""){P=!0;break}G+=w[A]}return me!==""?!1:{value:G,index:A,tagClosed:P}}i(H,"readAttributeStr"),r(H,"readAttributeStr");var V=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function j(w,A){let G=E.getAllMatches(w,V),me={};for(let P=0;P<G.length;P++){if(G[P][1].length===0)return q("InvalidAttr","Attribute '"+G[P][2]+"' has no space in starting.",Se(G[P]));if(G[P][3]!==void 0&&G[P][4]===void 0)return q("InvalidAttr","Attribute '"+G[P][2]+"' is without value.",Se(G[P]));if(G[P][3]===void 0&&!A.allowBooleanAttributes)return q("InvalidAttr","boolean attribute '"+G[P][2]+"' is not allowed.",Se(G[P]));let C=G[P][2];if(!ce(C))return q("InvalidAttr","Attribute '"+C+"' is an invalid name.",Se(G[P]));if(!me.hasOwnProperty(C))me[C]=1;else return q("InvalidAttr","Attribute '"+C+"' is repeated.",Se(G[P]))}return!0}i(j,"validateAttributeString"),r(j,"validateAttributeString");function v(w,A){let G=/\d/;for(w[A]==="x"&&(A++,G=/[\da-fA-F]/);A<w.length;A++){if(w[A]===";")return A;if(!w[A].match(G))break}return-1}i(v,"validateNumberAmpersand"),r(v,"validateNumberAmpersand");function x(w,A){if(A++,w[A]===";")return-1;if(w[A]==="#")return A++,v(w,A);let G=0;for(;A<w.length;A++,G++)if(!(w[A].match(/\w/)&&G<20)){if(w[A]===";")break;return-1}return A}i(x,"validateAmpersand"),r(x,"validateAmpersand");function q(w,A,G){return{err:{code:w,msg:A,line:G.line||G,col:G.col}}}i(q,"getErrorObject"),r(q,"getErrorObject");function ce(w){return E.isName(w)}i(ce,"validateAttrName"),r(ce,"validateAttrName");function X(w){return E.isName(w)}i(X,"validateTagName"),r(X,"validateTagName");function te(w,A){let G=w.substring(0,A).split(/\r?\n/);return{line:G.length,col:G[G.length-1].length+1}}i(te,"getLineNumberForPosition"),r(te,"getLineNumberForPosition");function Se(w){return w.startIndex+w[1].length}i(Se,"getPositionFromMatch"),r(Se,"getPositionFromMatch")}}),h=o({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(b,E){var{buildOptions:L}=s(),O=d(),{prettify:Z}=p(),M=m(),F=class{static{i(this,"XMLParser")}static{r(this,"XMLParser")}constructor(S){this.externalEntities={},this.options=L(S)}parse(S,H){if(typeof S!="string")if(S.toString)S=S.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(H){H===!0&&(H={});let v=M.validate(S,H);if(v!==!0)throw Error(`${v.err.msg}:${v.err.line}:${v.err.col}`)}let V=new O(this.options);V.addExternalEntities(this.externalEntities);let j=V.parseXml(S);return this.options.preserveOrder||j===void 0?j:Z(j,this.options)}addEntity(S,H){if(H.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(S.indexOf("&")!==-1||S.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(H==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[S]=H}};E.exports=F}});let I=h();return new I(n)},"getXmlParser");var Yi=class extends Ke{static{i(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),f("policy.outbound.xml-to-json"),W(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=e.parseOnStatusCodes?We(e.parseOnStatusCodes):void 0,this.parser=ju({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,t,r){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let o;try{let u=await e.text();o=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw r.log.error(c,u),new k(c)}let 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 Xi=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 zu=10,Bu=3e4,sn=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=Bu,this.#r=zu}else{let r=t;this.#n=r.ttlSeconds*1e3,this.#o=r.loaderTimeoutSeconds?r.loaderTimeoutSeconds*1e3:Bu,this.#r=zu}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.#c(e),t;if(this.#a(e))try{await tm(()=>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.#l(e)}#c(e){if(!this.#a(e)){let t=this.#l(e);Qe().waitUntil(t)}}async#l(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 g(`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 tm(n,e,t){let r=Date.now();for(;!n();){let o=Date.now()-r;if(o>e)throw new g(`BackgroundLoader: Timeout waiting for an on-going loader after ${o} ms.`);await scheduler.wait(t)}}i(tm,"waitUntilTrue");var es=["sha-1","sha-256","sha-384","sha-512"],sr=class{static{i(this,"BaseCryptoBeta")}};var ts=class extends sr{static{i(this,"WorkerCryptoBeta")}async digest(e,t){if(f("runtime.crypto-beta"),!es.includes(e.toLowerCase()))throw new k(`Algorithm ${e} is not supported. Try using ${es.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("")}};export{Ho as AWSLoggingPlugin,oi as AkamaiApiSecurityPlugin,xd as AmberfloMeteringInboundPolicy,yi as AmberfloMeteringPolicy,Cd as ApiAuthKeyInboundPolicy,bi as ApiKeyInboundPolicy,wi as AsertoAuthZInboundPolicy,Yo as AuditLogDataStaxProvider,Xo as AuditLogPlugin,Ld as Auth0JwtInboundPolicy,Ei as AuthZenInboundPolicy,Tl as AwsLambdaHandlerExtensions,xi as AxiomaticsAuthZInboundPolicy,ai as AzureBlobPlugin,ui as AzureEventHubsRequestLoggerPlugin,an as BackgroundDispatcher,sn as BackgroundLoader,Nd as BasicAuthInboundPolicy,Su as BasicRateLimitInboundPolicy,K as BatchDispatch,Ci as BrownoutInboundPolicy,Bd as CachingInboundPolicy,Gd as ChangeMethodInboundPolicy,Vd as ClearHeadersInboundPolicy,Wd as ClearHeadersOutboundPolicy,Jd as ClerkJwtInboundPolicy,Kd as CognitoJwtInboundPolicy,_i as ComplexRateLimitInboundPolicy,ip as CompositeInboundPolicy,sp as CompositeOutboundPolicy,g as ConfigurationError,Zr as ContentTypes,oe as ContextData,ts as CryptoBeta,ap as CurityPhantomTokenInboundPolicy,fo as DataDogLoggingPlugin,zo as DataDogMetricsPlugin,So as DynaTraceLoggingPlugin,Vo as DynatraceMetricsPlugin,cp as FirebaseJwtInboundPolicy,lp as FormDataToJsonInboundPolicy,dp as GeoFilterInboundPolicy,co as GoogleCloudLoggingPlugin,wo as Handler,T as HttpProblems,On as HttpStatusCode,ci as HydrolixRequestLoggerPlugin,ae as InboundPolicy,pp as JWTScopeValidationInboundPolicy,Lo as LokiLoggingPlugin,bt as LookupResult,re as MemoryZoneReadThroughCache,mp as MockApiInboundPolicy,Rp as MoesifInboundPolicy,qi as MonetizationInboundPolicy,Ao as NewRelicLoggingPlugin,Ko as NewRelicMetricsPlugin,Ui as OktaFGAAuthZInboundPolicy,Ip as OktaJwtInboundPolicy,Hi as OpenFGAAuthZInboundPolicy,Ee as OpenIdJwtInboundPolicy,Ke as OutboundPolicy,it as ProblemResponseFormatter,xp as PropelAuthJwtInboundPolicy,Fi as QuotaInboundPolicy,Su as RateLimitInboundPolicy,Ap as ReadmeMetricsInboundPolicy,kp as RemoveHeadersInboundPolicy,Lp as RemoveHeadersOutboundPolicy,_p as RemoveQueryParamsInboundPolicy,Np as ReplaceStringOutboundPolicy,li as RequestLoggerPlugin,Dp as RequestSizeLimitInboundPolicy,Mu as RequestValidationInboundPolicy,qp as RequireOriginInboundPolicy,Bt as ResponseSendingEvent,Gt as ResponseSentEvent,k as RuntimeError,In as SYSTEM_LOGGER,Mp as SchemaBasedRequestValidation,ze as SemanticAttributes,Xi as ServiceProviderImpl,Up as SetBodyInboundPolicy,Hp as SetHeadersInboundPolicy,$p as SetHeadersOutboundPolicy,Zp as SetQueryParamsInboundPolicy,Fp as SetStatusOutboundPolicy,zp as SleepInboundPolicy,Zo as SplunkLoggingPlugin,Tr as StreamingZoneCache,Ya as StripeMonetizationPlugin,un as StripeWebhookVerificationInboundPolicy,Do as SumoLogicLoggingPlugin,Bp as SupabaseJwtInboundPolicy,Be as SystemRouteName,jt as TelemetryPlugin,Gp as UpstreamAzureAdServiceAuthInboundPolicy,Wp as UpstreamFirebaseAdminAuthInboundPolicy,Qp as UpstreamFirebaseUserAuthInboundPolicy,Wi as UpstreamGcpFederatedAuthInboundPolicy,Yp as UpstreamGcpJwtInboundPolicy,Xp as UpstreamGcpServiceAuthInboundPolicy,qo as VMWareLogInsightLoggingPlugin,em as ValidateJsonSchemaInbound,Yi as XmlToJsonOutboundPolicy,Dt as ZoneCache,ee as ZuploRequest,dn as ZuploServices,bc as apiServices,vl as awsLambdaHandler,dd as defaultGenerateHydrolixEntry,ye as environment,cr as getIdForParameterSchema,Ju as getIdForRefSchema,lr as getIdForRequestBodySchema,Wu as getRawOperationDataIdentifierName,zr as httpStatuses,Nl as openApiSpecHandler,Ml as redirectHandler,Ku as sanitizedIdentifierName,Fr as serialize,yp as setMoesifContext,f as trackFeature,Hl as urlForwardHandler,Zl as urlRewriteHandler,Fl as webSocketHandler,jl as webSocketPipelineHandler,ql as zuploServiceProxy};
93
+ `||w==="\r"}i(O,"isWhiteSpace"),r(O,"isWhiteSpace");function Z(w,A){let G=A;for(;A<w.length;A++)if(w[A]=="?"||w[A]==" "){let me=w.substr(G,A-G);if(A>5&&me==="xml")return q("InvalidXml","XML declaration allowed only at the start of the document.",te(w,A));if(w[A]=="?"&&w[A+1]==">"){A++;break}else continue}return A}i(Z,"readPI"),r(Z,"readPI");function M(w,A){if(w.length>A+5&&w[A+1]==="-"&&w[A+2]==="-"){for(A+=3;A<w.length;A++)if(w[A]==="-"&&w[A+1]==="-"&&w[A+2]===">"){A+=2;break}}else if(w.length>A+8&&w[A+1]==="D"&&w[A+2]==="O"&&w[A+3]==="C"&&w[A+4]==="T"&&w[A+5]==="Y"&&w[A+6]==="P"&&w[A+7]==="E"){let G=1;for(A+=8;A<w.length;A++)if(w[A]==="<")G++;else if(w[A]===">"&&(G--,G===0))break}else if(w.length>A+9&&w[A+1]==="["&&w[A+2]==="C"&&w[A+3]==="D"&&w[A+4]==="A"&&w[A+5]==="T"&&w[A+6]==="A"&&w[A+7]==="["){for(A+=8;A<w.length;A++)if(w[A]==="]"&&w[A+1]==="]"&&w[A+2]===">"){A+=2;break}}return A}i(M,"readCommentAndCDATA"),r(M,"readCommentAndCDATA");var F='"',S="'";function H(w,A){let G="",me="",P=!1;for(;A<w.length;A++){if(w[A]===F||w[A]===S)me===""?me=w[A]:me!==w[A]||(me="");else if(w[A]===">"&&me===""){P=!0;break}G+=w[A]}return me!==""?!1:{value:G,index:A,tagClosed:P}}i(H,"readAttributeStr"),r(H,"readAttributeStr");var V=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function j(w,A){let G=E.getAllMatches(w,V),me={};for(let P=0;P<G.length;P++){if(G[P][1].length===0)return q("InvalidAttr","Attribute '"+G[P][2]+"' has no space in starting.",Se(G[P]));if(G[P][3]!==void 0&&G[P][4]===void 0)return q("InvalidAttr","Attribute '"+G[P][2]+"' is without value.",Se(G[P]));if(G[P][3]===void 0&&!A.allowBooleanAttributes)return q("InvalidAttr","boolean attribute '"+G[P][2]+"' is not allowed.",Se(G[P]));let C=G[P][2];if(!ce(C))return q("InvalidAttr","Attribute '"+C+"' is an invalid name.",Se(G[P]));if(!me.hasOwnProperty(C))me[C]=1;else return q("InvalidAttr","Attribute '"+C+"' is repeated.",Se(G[P]))}return!0}i(j,"validateAttributeString"),r(j,"validateAttributeString");function v(w,A){let G=/\d/;for(w[A]==="x"&&(A++,G=/[\da-fA-F]/);A<w.length;A++){if(w[A]===";")return A;if(!w[A].match(G))break}return-1}i(v,"validateNumberAmpersand"),r(v,"validateNumberAmpersand");function x(w,A){if(A++,w[A]===";")return-1;if(w[A]==="#")return A++,v(w,A);let G=0;for(;A<w.length;A++,G++)if(!(w[A].match(/\w/)&&G<20)){if(w[A]===";")break;return-1}return A}i(x,"validateAmpersand"),r(x,"validateAmpersand");function q(w,A,G){return{err:{code:w,msg:A,line:G.line||G,col:G.col}}}i(q,"getErrorObject"),r(q,"getErrorObject");function ce(w){return E.isName(w)}i(ce,"validateAttrName"),r(ce,"validateAttrName");function X(w){return E.isName(w)}i(X,"validateTagName"),r(X,"validateTagName");function te(w,A){let G=w.substring(0,A).split(/\r?\n/);return{line:G.length,col:G[G.length-1].length+1}}i(te,"getLineNumberForPosition"),r(te,"getLineNumberForPosition");function Se(w){return w.startIndex+w[1].length}i(Se,"getPositionFromMatch"),r(Se,"getPositionFromMatch")}}),h=o({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(b,E){var{buildOptions:L}=s(),O=d(),{prettify:Z}=p(),M=m(),F=class{static{i(this,"XMLParser")}static{r(this,"XMLParser")}constructor(S){this.externalEntities={},this.options=L(S)}parse(S,H){if(typeof S!="string")if(S.toString)S=S.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(H){H===!0&&(H={});let v=M.validate(S,H);if(v!==!0)throw Error(`${v.err.msg}:${v.err.line}:${v.err.col}`)}let V=new O(this.options);V.addExternalEntities(this.externalEntities);let j=V.parseXml(S);return this.options.preserveOrder||j===void 0?j:Z(j,this.options)}addEntity(S,H){if(H.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(S.indexOf("&")!==-1||S.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(H==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[S]=H}};E.exports=F}});let I=h();return new I(n)},"getXmlParser");var Yi=class extends Ke{static{i(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),f("policy.outbound.xml-to-json"),W(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=e.parseOnStatusCodes?We(e.parseOnStatusCodes):void 0,this.parser=Bu({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,t,r){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let o;try{let u=await e.text();o=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw r.log.error(c,u),new k(c)}let 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 Xi=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 Gu=10,Vu=3e4,sn=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=Vu,this.#r=Gu}else{let r=t;this.#n=r.ttlSeconds*1e3,this.#o=r.loaderTimeoutSeconds?r.loaderTimeoutSeconds*1e3:Vu,this.#r=Gu}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.#c(e),t;if(this.#a(e))try{await rm(()=>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.#l(e)}#c(e){if(!this.#a(e)){let t=this.#l(e);Qe().waitUntil(t)}}async#l(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 g(`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 rm(n,e,t){let r=Date.now();for(;!n();){let o=Date.now()-r;if(o>e)throw new g(`BackgroundLoader: Timeout waiting for an on-going loader after ${o} ms.`);await scheduler.wait(t)}}i(rm,"waitUntilTrue");var es=["sha-1","sha-256","sha-384","sha-512"],sr=class{static{i(this,"BaseCryptoBeta")}};var ts=class extends sr{static{i(this,"WorkerCryptoBeta")}async digest(e,t){if(f("runtime.crypto-beta"),!es.includes(e.toLowerCase()))throw new k(`Algorithm ${e} is not supported. Try using ${es.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("")}};export{Ho as AWSLoggingPlugin,oi as AkamaiApiSecurityPlugin,vd as AmberfloMeteringInboundPolicy,yi as AmberfloMeteringPolicy,Od as ApiAuthKeyInboundPolicy,bi as ApiKeyInboundPolicy,wi as AsertoAuthZInboundPolicy,Yo as AuditLogDataStaxProvider,Xo as AuditLogPlugin,Nd as Auth0JwtInboundPolicy,Ei as AuthZenInboundPolicy,Cl as AwsLambdaHandlerExtensions,xi as AxiomaticsAuthZInboundPolicy,ai as AzureBlobPlugin,ui as AzureEventHubsRequestLoggerPlugin,an as BackgroundDispatcher,sn as BackgroundLoader,Md as BasicAuthInboundPolicy,Au as BasicRateLimitInboundPolicy,K as BatchDispatch,Ci as BrownoutInboundPolicy,Vd as CachingInboundPolicy,Wd as ChangeMethodInboundPolicy,Jd as ClearHeadersInboundPolicy,Kd as ClearHeadersOutboundPolicy,Qd as ClerkJwtInboundPolicy,Yd as CognitoJwtInboundPolicy,_i as ComplexRateLimitInboundPolicy,ap as CompositeInboundPolicy,up as CompositeOutboundPolicy,g as ConfigurationError,Zr as ContentTypes,oe as ContextData,ts as CryptoBeta,cp as CurityPhantomTokenInboundPolicy,fo as DataDogLoggingPlugin,zo as DataDogMetricsPlugin,So as DynaTraceLoggingPlugin,Vo as DynatraceMetricsPlugin,dp as FirebaseJwtInboundPolicy,pp as FormDataToJsonInboundPolicy,mp as GeoFilterInboundPolicy,co as GoogleCloudLoggingPlugin,wo as Handler,T as HttpProblems,On as HttpStatusCode,ci as HydrolixRequestLoggerPlugin,ae as InboundPolicy,gp as JWTScopeValidationInboundPolicy,Lo as LokiLoggingPlugin,bt as LookupResult,re as MemoryZoneReadThroughCache,fp as MockApiInboundPolicy,Ip as MoesifInboundPolicy,qi as MonetizationInboundPolicy,Ao as NewRelicLoggingPlugin,Ko as NewRelicMetricsPlugin,Ui as OktaFGAAuthZInboundPolicy,xp as OktaJwtInboundPolicy,Hi as OpenFGAAuthZInboundPolicy,Ee as OpenIdJwtInboundPolicy,Ke as OutboundPolicy,it as ProblemResponseFormatter,vp as PropelAuthJwtInboundPolicy,Fi as QuotaInboundPolicy,Au as RateLimitInboundPolicy,Lp as ReadmeMetricsInboundPolicy,_p as RemoveHeadersInboundPolicy,Np as RemoveHeadersOutboundPolicy,Dp as RemoveQueryParamsInboundPolicy,Mp as ReplaceStringOutboundPolicy,li as RequestLoggerPlugin,qp as RequestSizeLimitInboundPolicy,Uu as RequestValidationInboundPolicy,Hp as RequireOriginInboundPolicy,Bt as ResponseSendingEvent,Gt as ResponseSentEvent,k as RuntimeError,In as SYSTEM_LOGGER,Up as SchemaBasedRequestValidation,ze as SemanticAttributes,Xi as ServiceProviderImpl,$p as SetBodyInboundPolicy,Zp as SetHeadersInboundPolicy,Fp as SetHeadersOutboundPolicy,jp as SetQueryParamsInboundPolicy,zp as SetStatusOutboundPolicy,Gp as SleepInboundPolicy,Zo as SplunkLoggingPlugin,Tr as StreamingZoneCache,eu as StripeMonetizationPlugin,un as StripeWebhookVerificationInboundPolicy,Do as SumoLogicLoggingPlugin,Vp as SupabaseJwtInboundPolicy,Be as SystemRouteName,jt as TelemetryPlugin,Wp as UpstreamAzureAdServiceAuthInboundPolicy,Kp as UpstreamFirebaseAdminAuthInboundPolicy,Xp as UpstreamFirebaseUserAuthInboundPolicy,Wi as UpstreamGcpFederatedAuthInboundPolicy,em as UpstreamGcpJwtInboundPolicy,tm as UpstreamGcpServiceAuthInboundPolicy,qo as VMWareLogInsightLoggingPlugin,nm as ValidateJsonSchemaInbound,Yi as XmlToJsonOutboundPolicy,Dt as ZoneCache,ee as ZuploRequest,dn as ZuploServices,Rc as apiServices,Sl as awsLambdaHandler,md as defaultGenerateHydrolixEntry,ye as environment,cr as getIdForParameterSchema,Qu as getIdForRefSchema,lr as getIdForRequestBodySchema,Ku as getRawOperationDataIdentifierName,zr as httpStatuses,Ml as openApiSpecHandler,Ul as redirectHandler,Yu as sanitizedIdentifierName,Fr as serialize,wp as setMoesifContext,f as trackFeature,Zl as urlForwardHandler,jl as urlRewriteHandler,zl as webSocketHandler,Bl as webSocketPipelineHandler,Hl as zuploServiceProxy};
94
94
  /*! For license information please see index.js.LEGAL.txt */