@zuplo/runtime 5.2362.0 → 5.2364.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/out/cjs/index.js CHANGED
@@ -22,17 +22,17 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- "use strict";var Ac=Object.create;var $t=Object.defineProperty;var _c=Object.getOwnPropertyDescriptor;var Lc=Object.getOwnPropertyNames;var kc=Object.getPrototypeOf,Nc=Object.prototype.hasOwnProperty;var i=(n,e)=>$t(n,"name",{value:e,configurable:!0});var jt=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Mc=(n,e)=>{for(var t in e)$t(n,t,{get:e[t],enumerable:!0})},Fi=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Lc(e))!Nc.call(n,o)&&o!==t&&$t(n,o,{get:()=>e[o],enumerable:!(r=_c(e,o))||r.enumerable});return n};var Be=(n,e,t)=>(t=n!=null?Ac(kc(n)):{},Fi(e||!n||!n.__esModule?$t(t,"default",{value:n,enumerable:!0}):t,n)),Dc=n=>Fi($t({},"__esModule",{value:!0}),n);var Ji=jt(v=>{"use strict";Object.defineProperty(v,"__esModule",{value:!0});v.generateColor=v.colorFunctions=v.stripColor=v.bgRgb24=v.rgb24=v.bgRgb8=v.rgb8=v.bgBrightWhite=v.bgBrightCyan=v.bgBrightMagenta=v.bgBrightBlue=v.bgBrightYellow=v.bgBrightGreen=v.bgBrightRed=v.bgBrightBlack=v.bgWhite=v.bgCyan=v.bgMagenta=v.bgBlue=v.bgYellow=v.bgGreen=v.bgRed=v.bgBlack=v.brightWhite=v.brightCyan=v.brightMagenta=v.brightBlue=v.brightYellow=v.brightGreen=v.brightRed=v.brightBlack=v.gray=v.white=v.cyan=v.magenta=v.blue=v.yellow=v.green=v.red=v.black=v.strikethrough=v.hidden=v.inverse=v.underline=v.italic=v.dim=v.bold=v.reset=v.getColorEnabled=v.setColorEnabled=void 0;var $i=!0,jr=!$i;function Uc(n){$i||(jr=n)}i(Uc,"setColorEnabled");v.setColorEnabled=Uc;function Hc(){return jr}i(Hc,"getColorEnabled");v.getColorEnabled=Hc;function K(n,e){return{open:`\x1B[${n.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}i(K,"code");function J(n,e){return jr?`${e.open}${n.replace(e.regexp,e.open)}${e.close}`:n}i(J,"run");function Zc(n){return J(n,K([0],0))}i(Zc,"reset");v.reset=Zc;function qc(n){return J(n,K([1],22))}i(qc,"bold");v.bold=qc;function Fc(n){return J(n,K([2],22))}i(Fc,"dim");v.dim=Fc;function $c(n){return J(n,K([3],23))}i($c,"italic");v.italic=$c;function jc(n){return J(n,K([4],24))}i(jc,"underline");v.underline=jc;function zc(n){return J(n,K([7],27))}i(zc,"inverse");v.inverse=zc;function Bc(n){return J(n,K([8],28))}i(Bc,"hidden");v.hidden=Bc;function Gc(n){return J(n,K([9],29))}i(Gc,"strikethrough");v.strikethrough=Gc;function Vc(n){return J(n,K([30],39))}i(Vc,"black");v.black=Vc;function ji(n){return J(n,K([31],39))}i(ji,"red");v.red=ji;function zi(n){return J(n,K([32],39))}i(zi,"green");v.green=zi;function Bi(n){return J(n,K([33],39))}i(Bi,"yellow");v.yellow=Bi;function Gi(n){return J(n,K([34],39))}i(Gi,"blue");v.blue=Gi;function Vi(n){return J(n,K([35],39))}i(Vi,"magenta");v.magenta=Vi;function Wi(n){return J(n,K([36],39))}i(Wi,"cyan");v.cyan=Wi;function Wc(n){return J(n,K([37],39))}i(Wc,"white");v.white=Wc;function Kc(n){return Ki(n)}i(Kc,"gray");v.gray=Kc;function Ki(n){return J(n,K([90],39))}i(Ki,"brightBlack");v.brightBlack=Ki;function Jc(n){return J(n,K([91],39))}i(Jc,"brightRed");v.brightRed=Jc;function Yc(n){return J(n,K([92],39))}i(Yc,"brightGreen");v.brightGreen=Yc;function Xc(n){return J(n,K([93],39))}i(Xc,"brightYellow");v.brightYellow=Xc;function Qc(n){return J(n,K([94],39))}i(Qc,"brightBlue");v.brightBlue=Qc;function el(n){return J(n,K([95],39))}i(el,"brightMagenta");v.brightMagenta=el;function tl(n){return J(n,K([96],39))}i(tl,"brightCyan");v.brightCyan=tl;function nl(n){return J(n,K([97],39))}i(nl,"brightWhite");v.brightWhite=nl;function rl(n){return J(n,K([40],49))}i(rl,"bgBlack");v.bgBlack=rl;function ol(n){return J(n,K([41],49))}i(ol,"bgRed");v.bgRed=ol;function il(n){return J(n,K([42],49))}i(il,"bgGreen");v.bgGreen=il;function sl(n){return J(n,K([43],49))}i(sl,"bgYellow");v.bgYellow=sl;function al(n){return J(n,K([44],49))}i(al,"bgBlue");v.bgBlue=al;function ul(n){return J(n,K([45],49))}i(ul,"bgMagenta");v.bgMagenta=ul;function cl(n){return J(n,K([46],49))}i(cl,"bgCyan");v.bgCyan=cl;function ll(n){return J(n,K([47],49))}i(ll,"bgWhite");v.bgWhite=ll;function dl(n){return J(n,K([100],49))}i(dl,"bgBrightBlack");v.bgBrightBlack=dl;function pl(n){return J(n,K([101],49))}i(pl,"bgBrightRed");v.bgBrightRed=pl;function ml(n){return J(n,K([102],49))}i(ml,"bgBrightGreen");v.bgBrightGreen=ml;function gl(n){return J(n,K([103],49))}i(gl,"bgBrightYellow");v.bgBrightYellow=gl;function fl(n){return J(n,K([104],49))}i(fl,"bgBrightBlue");v.bgBrightBlue=fl;function hl(n){return J(n,K([105],49))}i(hl,"bgBrightMagenta");v.bgBrightMagenta=hl;function yl(n){return J(n,K([106],49))}i(yl,"bgBrightCyan");v.bgBrightCyan=yl;function bl(n){return J(n,K([107],49))}i(bl,"bgBrightWhite");v.bgBrightWhite=bl;function Ge(n,e=255,t=0){return Math.trunc(Math.max(Math.min(n,e),t))}i(Ge,"clampAndTruncate");function wl(n,e){return J(n,K([38,5,Ge(e)],39))}i(wl,"rgb8");v.rgb8=wl;function Rl(n,e){return J(n,K([48,5,Ge(e)],49))}i(Rl,"bgRgb8");v.bgRgb8=Rl;function Pl(n,e){return typeof e=="number"?J(n,K([38,2,e>>16&255,e>>8&255,e&255],39)):J(n,K([38,2,Ge(e.r),Ge(e.g),Ge(e.b)],39))}i(Pl,"rgb24");v.rgb24=Pl;function Il(n,e){return typeof e=="number"?J(n,K([48,2,e>>16&255,e>>8&255,e&255],49)):J(n,K([48,2,Ge(e.r),Ge(e.g),Ge(e.b)],49))}i(Il,"bgRgb24");v.bgRgb24=Il;var El=new RegExp(["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|"),"g");function Tl(n){return n.replace(El,"")}i(Tl,"stripColor");v.stripColor=Tl;v.colorFunctions=[ji,zi,Bi,Gi,Vi,Wi];function xl(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(xl,"hashCode");function vl(n){let e=Math.abs(xl(n));return v.colorFunctions[e%v.colorFunctions.length]}i(vl,"generateColor");v.generateColor=vl});var Yi=jt(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.format=void 0;function Ol(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(Ol,"format");dn.format=Ol});var rs=jt(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.inspect=void 0;function rt(n,e,t,r){let o={seen:[],stylize:Cl,showHidden:e??!1,depth:t??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=Al),pn(o,n,o.depth)}i(rt,"inspect");mn.inspect=rt;rt.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]};rt.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function Cl(n,e){return n}i(Cl,"stylizeNoColor");function Sl(n){return typeof n=="boolean"}i(Sl,"isBoolean");function Qi(n){return n===void 0}i(Qi,"isUndefined");function Al(n,e){let t=rt.styles[e];return t?"\x1B["+rt.colors[t][0]+"m"+n+"\x1B["+rt.colors[t][1]+"m":n}i(Al,"stylizeWithColor");function zr(n){return typeof n=="function"}i(zr,"isFunction");function es(n){return typeof n=="string"}i(es,"isString");function _l(n){return typeof n=="number"}i(_l,"isNumber");function ts(n){return n===null}i(ts,"isNull");function ns(n,e){return Object.prototype.hasOwnProperty.call(n,e)}i(ns,"hasOwn");function Br(n){return Kr(n)&&Jr(n)==="[object RegExp]"}i(Br,"isRegExp");function Kr(n){return typeof n=="object"&&n!==null}i(Kr,"isObject");function Gr(n){return Kr(n)&&(Jr(n)==="[object Error]"||n instanceof Error)}i(Gr,"isError");function Xi(n){return Kr(n)&&Jr(n)==="[object Date]"}i(Xi,"isDate");function Jr(n){return Object.prototype.toString.call(n)}i(Jr,"objectToString");function Ll(n){let e={};return n.forEach(function(t,r){e[t]=!0}),e}i(Ll,"arrayToHash");function kl(n,e,t,r,o){let s=[];for(let a=0,u=e.length;a<u;++a)ns(e,String(a))?s.push(Wr(n,e,t,r,String(a),!0)):s.push("");return o.forEach(function(a){a.match(/^\d+$/)||s.push(Wr(n,e,t,r,a,!0))}),s}i(kl,"formatArray");function Vr(n){return"["+Error.prototype.toString.call(n)+"]"}i(Vr,"formatError");function pn(n,e,t){if(n.customInspect&&e&&zr(e.inspect)&&e.inspect!==rt&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(t,n);return es(d)||(d=pn(n,d,t)),d}let r=Nl(n,e);if(r)return r;let o=Object.keys(e),s=Ll(o);try{n.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(Gr(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return Vr(e);if(o.length===0){if(zr(e)){let d=e.name?": "+e.name:"";return n.stylize("[Function"+d+"]","special")}if(Br(e))return n.stylize(RegExp.prototype.toString.call(e),"regexp");if(Xi(e))return n.stylize(Date.prototype.toString.call(e),"date");if(Gr(e))return Vr(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),zr(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),Br(e)&&(a=" "+RegExp.prototype.toString.call(e)),Xi(e)&&(a=" "+Date.prototype.toUTCString.call(e)),Gr(e)&&(a=" "+Vr(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(t<0)return Br(e)?n.stylize(RegExp.prototype.toString.call(e),"regexp"):n.stylize("[Object]","special");n.seen.push(e);let l;return u?l=kl(n,e,t,s,o):l=o.map(function(d){return Wr(n,e,t,s,d,u)}),n.seen.pop(),Ml(l,a,c)}i(pn,"formatValue");function Wr(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")),ns(r,o)||(a="["+o+"]"),u||(n.seen.indexOf(c.value)<0?(ts(t)?u=pn(n,c.value,null):u=pn(n,c.value,t-1),u.indexOf(`
25
+ "use strict";var Sc=Object.create;var Bt=Object.defineProperty;var Ac=Object.getOwnPropertyDescriptor;var _c=Object.getOwnPropertyNames;var Lc=Object.getPrototypeOf,kc=Object.prototype.hasOwnProperty;var i=(n,e)=>Bt(n,"name",{value:e,configurable:!0});var zt=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Nc=(n,e)=>{for(var t in e)Bt(n,t,{get:e[t],enumerable:!0})},Fi=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of _c(e))!kc.call(n,o)&&o!==t&&Bt(n,o,{get:()=>e[o],enumerable:!(r=Ac(e,o))||r.enumerable});return n};var ze=(n,e,t)=>(t=n!=null?Sc(Lc(n)):{},Fi(e||!n||!n.__esModule?Bt(t,"default",{value:n,enumerable:!0}):t,n)),Dc=n=>Fi(Bt({},"__esModule",{value:!0}),n);var Ji=zt(v=>{"use strict";Object.defineProperty(v,"__esModule",{value:!0});v.generateColor=v.colorFunctions=v.stripColor=v.bgRgb24=v.rgb24=v.bgRgb8=v.rgb8=v.bgBrightWhite=v.bgBrightCyan=v.bgBrightMagenta=v.bgBrightBlue=v.bgBrightYellow=v.bgBrightGreen=v.bgBrightRed=v.bgBrightBlack=v.bgWhite=v.bgCyan=v.bgMagenta=v.bgBlue=v.bgYellow=v.bgGreen=v.bgRed=v.bgBlack=v.brightWhite=v.brightCyan=v.brightMagenta=v.brightBlue=v.brightYellow=v.brightGreen=v.brightRed=v.brightBlack=v.gray=v.white=v.cyan=v.magenta=v.blue=v.yellow=v.green=v.red=v.black=v.strikethrough=v.hidden=v.inverse=v.underline=v.italic=v.dim=v.bold=v.reset=v.getColorEnabled=v.setColorEnabled=void 0;var $i=!0,Hr=!$i;function Mc(n){$i||(Hr=n)}i(Mc,"setColorEnabled");v.setColorEnabled=Mc;function Uc(){return Hr}i(Uc,"getColorEnabled");v.getColorEnabled=Uc;function K(n,e){return{open:`\x1B[${n.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}i(K,"code");function J(n,e){return Hr?`${e.open}${n.replace(e.regexp,e.open)}${e.close}`:n}i(J,"run");function qc(n){return J(n,K([0],0))}i(qc,"reset");v.reset=qc;function Zc(n){return J(n,K([1],22))}i(Zc,"bold");v.bold=Zc;function Hc(n){return J(n,K([2],22))}i(Hc,"dim");v.dim=Hc;function Fc(n){return J(n,K([3],23))}i(Fc,"italic");v.italic=Fc;function $c(n){return J(n,K([4],24))}i($c,"underline");v.underline=$c;function jc(n){return J(n,K([7],27))}i(jc,"inverse");v.inverse=jc;function Bc(n){return J(n,K([8],28))}i(Bc,"hidden");v.hidden=Bc;function zc(n){return J(n,K([9],29))}i(zc,"strikethrough");v.strikethrough=zc;function Gc(n){return J(n,K([30],39))}i(Gc,"black");v.black=Gc;function ji(n){return J(n,K([31],39))}i(ji,"red");v.red=ji;function Bi(n){return J(n,K([32],39))}i(Bi,"green");v.green=Bi;function zi(n){return J(n,K([33],39))}i(zi,"yellow");v.yellow=zi;function Gi(n){return J(n,K([34],39))}i(Gi,"blue");v.blue=Gi;function Vi(n){return J(n,K([35],39))}i(Vi,"magenta");v.magenta=Vi;function Wi(n){return J(n,K([36],39))}i(Wi,"cyan");v.cyan=Wi;function Vc(n){return J(n,K([37],39))}i(Vc,"white");v.white=Vc;function Wc(n){return Ki(n)}i(Wc,"gray");v.gray=Wc;function Ki(n){return J(n,K([90],39))}i(Ki,"brightBlack");v.brightBlack=Ki;function Kc(n){return J(n,K([91],39))}i(Kc,"brightRed");v.brightRed=Kc;function Jc(n){return J(n,K([92],39))}i(Jc,"brightGreen");v.brightGreen=Jc;function Qc(n){return J(n,K([93],39))}i(Qc,"brightYellow");v.brightYellow=Qc;function Yc(n){return J(n,K([94],39))}i(Yc,"brightBlue");v.brightBlue=Yc;function Xc(n){return J(n,K([95],39))}i(Xc,"brightMagenta");v.brightMagenta=Xc;function el(n){return J(n,K([96],39))}i(el,"brightCyan");v.brightCyan=el;function tl(n){return J(n,K([97],39))}i(tl,"brightWhite");v.brightWhite=tl;function nl(n){return J(n,K([40],49))}i(nl,"bgBlack");v.bgBlack=nl;function rl(n){return J(n,K([41],49))}i(rl,"bgRed");v.bgRed=rl;function ol(n){return J(n,K([42],49))}i(ol,"bgGreen");v.bgGreen=ol;function il(n){return J(n,K([43],49))}i(il,"bgYellow");v.bgYellow=il;function sl(n){return J(n,K([44],49))}i(sl,"bgBlue");v.bgBlue=sl;function al(n){return J(n,K([45],49))}i(al,"bgMagenta");v.bgMagenta=al;function ul(n){return J(n,K([46],49))}i(ul,"bgCyan");v.bgCyan=ul;function cl(n){return J(n,K([47],49))}i(cl,"bgWhite");v.bgWhite=cl;function ll(n){return J(n,K([100],49))}i(ll,"bgBrightBlack");v.bgBrightBlack=ll;function dl(n){return J(n,K([101],49))}i(dl,"bgBrightRed");v.bgBrightRed=dl;function pl(n){return J(n,K([102],49))}i(pl,"bgBrightGreen");v.bgBrightGreen=pl;function ml(n){return J(n,K([103],49))}i(ml,"bgBrightYellow");v.bgBrightYellow=ml;function gl(n){return J(n,K([104],49))}i(gl,"bgBrightBlue");v.bgBrightBlue=gl;function fl(n){return J(n,K([105],49))}i(fl,"bgBrightMagenta");v.bgBrightMagenta=fl;function hl(n){return J(n,K([106],49))}i(hl,"bgBrightCyan");v.bgBrightCyan=hl;function yl(n){return J(n,K([107],49))}i(yl,"bgBrightWhite");v.bgBrightWhite=yl;function Ge(n,e=255,t=0){return Math.trunc(Math.max(Math.min(n,e),t))}i(Ge,"clampAndTruncate");function bl(n,e){return J(n,K([38,5,Ge(e)],39))}i(bl,"rgb8");v.rgb8=bl;function wl(n,e){return J(n,K([48,5,Ge(e)],49))}i(wl,"bgRgb8");v.bgRgb8=wl;function Rl(n,e){return typeof e=="number"?J(n,K([38,2,e>>16&255,e>>8&255,e&255],39)):J(n,K([38,2,Ge(e.r),Ge(e.g),Ge(e.b)],39))}i(Rl,"rgb24");v.rgb24=Rl;function Pl(n,e){return typeof e=="number"?J(n,K([48,2,e>>16&255,e>>8&255,e&255],49)):J(n,K([48,2,Ge(e.r),Ge(e.g),Ge(e.b)],49))}i(Pl,"bgRgb24");v.bgRgb24=Pl;var Il=new RegExp(["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|"),"g");function El(n){return n.replace(Il,"")}i(El,"stripColor");v.stripColor=El;v.colorFunctions=[ji,Bi,zi,Gi,Vi,Wi];function Tl(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(Tl,"hashCode");function xl(n){let e=Math.abs(Tl(n));return v.colorFunctions[e%v.colorFunctions.length]}i(xl,"generateColor");v.generateColor=xl});var Qi=zt(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.format=void 0;function Ol(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(Ol,"format");mn.format=Ol});var rs=zt(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.inspect=void 0;function st(n,e,t,r){let o={seen:[],stylize:vl,showHidden:e??!1,depth:t??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=Sl),gn(o,n,o.depth)}i(st,"inspect");fn.inspect=st;st.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]};st.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function vl(n,e){return n}i(vl,"stylizeNoColor");function Cl(n){return typeof n=="boolean"}i(Cl,"isBoolean");function Xi(n){return n===void 0}i(Xi,"isUndefined");function Sl(n,e){let t=st.styles[e];return t?"\x1B["+st.colors[t][0]+"m"+n+"\x1B["+st.colors[t][1]+"m":n}i(Sl,"stylizeWithColor");function Fr(n){return typeof n=="function"}i(Fr,"isFunction");function es(n){return typeof n=="string"}i(es,"isString");function Al(n){return typeof n=="number"}i(Al,"isNumber");function ts(n){return n===null}i(ts,"isNull");function ns(n,e){return Object.prototype.hasOwnProperty.call(n,e)}i(ns,"hasOwn");function $r(n){return Gr(n)&&Vr(n)==="[object RegExp]"}i($r,"isRegExp");function Gr(n){return typeof n=="object"&&n!==null}i(Gr,"isObject");function jr(n){return Gr(n)&&(Vr(n)==="[object Error]"||n instanceof Error)}i(jr,"isError");function Yi(n){return Gr(n)&&Vr(n)==="[object Date]"}i(Yi,"isDate");function Vr(n){return Object.prototype.toString.call(n)}i(Vr,"objectToString");function _l(n){let e={};return n.forEach(function(t,r){e[t]=!0}),e}i(_l,"arrayToHash");function Ll(n,e,t,r,o){let s=[];for(let a=0,u=e.length;a<u;++a)ns(e,String(a))?s.push(zr(n,e,t,r,String(a),!0)):s.push("");return o.forEach(function(a){a.match(/^\d+$/)||s.push(zr(n,e,t,r,a,!0))}),s}i(Ll,"formatArray");function Br(n){return"["+Error.prototype.toString.call(n)+"]"}i(Br,"formatError");function gn(n,e,t){if(n.customInspect&&e&&Fr(e.inspect)&&e.inspect!==st&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(t,n);return es(d)||(d=gn(n,d,t)),d}let r=kl(n,e);if(r)return r;let o=Object.keys(e),s=_l(o);try{n.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(jr(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return Br(e);if(o.length===0){if(Fr(e)){let d=e.name?": "+e.name:"";return n.stylize("[Function"+d+"]","special")}if($r(e))return n.stylize(RegExp.prototype.toString.call(e),"regexp");if(Yi(e))return n.stylize(Date.prototype.toString.call(e),"date");if(jr(e))return Br(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),Fr(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),$r(e)&&(a=" "+RegExp.prototype.toString.call(e)),Yi(e)&&(a=" "+Date.prototype.toUTCString.call(e)),jr(e)&&(a=" "+Br(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(t<0)return $r(e)?n.stylize(RegExp.prototype.toString.call(e),"regexp"):n.stylize("[Object]","special");n.seen.push(e);let l;return u?l=Ll(n,e,t,s,o):l=o.map(function(d){return zr(n,e,t,s,d,u)}),n.seen.pop(),Nl(l,a,c)}i(gn,"formatValue");function zr(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")),ns(r,o)||(a="["+o+"]"),u||(n.seen.indexOf(c.value)<0?(ts(t)?u=gn(n,c.value,null):u=gn(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")),Qi(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(Wr,"formatProperty");function Nl(n,e){if(Qi(e))return n.stylize("undefined","undefined");if(es(e)){let t="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return n.stylize(t,"string")}if(_l(e))return n.stylize(""+e,"number");if(Sl(e))return n.stylize(""+e,"boolean");if(ts(e))return n.stylize("null","null")}i(Nl,"formatPrimitive");function Ml(n,e,t){let r=0;return n.reduce(function(s,a){return r++,a.indexOf(`
32
+ `))):u=n.stylize("[Circular]","special")),Xi(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(zr,"formatProperty");function kl(n,e){if(Xi(e))return n.stylize("undefined","undefined");if(es(e)){let t="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return n.stylize(t,"string")}if(Al(e))return n.stylize(""+e,"number");if(Cl(e))return n.stylize(""+e,"boolean");if(ts(e))return n.stylize("null","null")}i(kl,"formatPrimitive");function Nl(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(Ml,"reduceToSingleString")});var os=jt(gn=>{"use strict";Object.defineProperty(gn,"__esModule",{value:!0});gn.format=void 0;var Dl=Yi(),Ul=rs(),Hl=i((n,...e)=>(0,Dl.format)(Ul.inspect,n,e),"format");gn.format=Hl});var qe=jt(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.debug=Ve.withoutEnv=Ve.Debugger=void 0;var Zl=Ji(),ql=os(),fn=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=(0,Zl.generateColor)(t),this.last=0,this.enabled=e.enabled.some(r=>r.test(t))}log(...e){if(!this.enabled)return;let t,r=e[0];typeof r=="function"?t=r():t=String(r);let o=Date.now()-(this.last||Date.now());t=(0,ql.format)(t,...e);let s=`${this.color(this.ns)} ${t} ${this.color(`+${o}ms`)}`;console.log(s),this.last=Date.now()}};Ve.Debugger=fn;var hn=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function is(n){return!n||n.length===0?[]:(n=n.replace(/\s/g,"").replace(/\*/g,".+"),n.split(",").map(e=>new RegExp(`^${e}$`)))}i(is,"extract");var zt;function Fl(n){n||(n=[]),typeof n=="string"&&(n=is(n)),zt=new hn(n)}i(Fl,"withoutEnv");Ve.withoutEnv=Fl;function $l(n){let e=globalThis.DEBUG;zt||(zt=new hn(is(e)));let t=new fn(zt,n);return zt.debuggers.set(n,t),Object.assign(t.log.bind(t),{self:t})}i($l,"debug");Ve.debug=$l});var em={};Mc(em,{AWSLoggingPlugin:()=>nr,AmberfloMeteringInboundPolicy:()=>Xa,AmberfloMeteringPolicy:()=>cr,ApiAuthKeyInboundPolicy:()=>tu,ApiKeyInboundPolicy:()=>dr,AuditLogDataStaxProvider:()=>ir,AuditLogPlugin:()=>sr,Auth0JwtInboundPolicy:()=>ou,AwsLambdaHandlerExtensions:()=>La,AxiomaticsAuthZInboundPolicy:()=>gr,BackgroundDispatcher:()=>Mr,BackgroundLoader:()=>Dr,BasicAuthInboundPolicy:()=>iu,BasicRateLimitInboundPolicy:()=>Ai,BatchDispatch:()=>Q,BrownoutInboundPolicy:()=>yr,CachingInboundPolicy:()=>au,ChangeMethodInboundPolicy:()=>uu,ClearHeadersInboundPolicy:()=>cu,ClearHeadersOutboundPolicy:()=>lu,ClerkJwtInboundPolicy:()=>du,CognitoJwtInboundPolicy:()=>pu,ComplexRateLimitInboundPolicy:()=>Er,CompositeInboundPolicy:()=>yu,ConfigurationError:()=>g,ContentTypes:()=>Tn,ContextData:()=>he,CryptoBeta:()=>Hr,CurityPhantomTokenInboundPolicy:()=>bu,DataDogLoggingPlugin:()=>jn,DataDogMetricsPlugin:()=>rr,DynaTraceLoggingPlugin:()=>Xn,DynatraceMetricsPlugin:()=>or,FirebaseJwtInboundPolicy:()=>wu,FormDataToJsonInboundPolicy:()=>Ru,GeoFilterInboundPolicy:()=>Pu,GoogleCloudLoggingPlugin:()=>qn,Handler:()=>Jn,HttpProblems:()=>T,HttpStatusCode:()=>Kt,InboundPolicy:()=>de,JWTScopeValidationInboundPolicy:()=>Iu,KeyValueStore:()=>qr,LokiLoggingPlugin:()=>Qn,LookupResult:()=>It,MemoryZoneReadThroughCache:()=>se,MockApiInboundPolicy:()=>Tu,MoesifInboundPolicy:()=>Au,MonetizationInboundPolicy:()=>xr,OktaFGAAuthZInboundPolicy:()=>Cr,OktaJwtInboundPolicy:()=>Zu,OpenFGAAuthZInboundPolicy:()=>Sr,OpenIdJwtInboundPolicy:()=>we,OutboundPolicy:()=>je,ProblemResponseFormatter:()=>Je,PropelAuthJwtInboundPolicy:()=>Fu,RateLimitInboundPolicy:()=>Ai,ReadmeMetricsInboundPolicy:()=>Ku,RemoveHeadersInboundPolicy:()=>Ju,RemoveHeadersOutboundPolicy:()=>Yu,RemoveQueryParamsInboundPolicy:()=>Xu,ReplaceStringOutboundPolicy:()=>Qu,RequestSizeLimitInboundPolicy:()=>tc,RequestValidationInboundPolicy:()=>ki,RequireOriginInboundPolicy:()=>cc,ResponseSendingEvent:()=>ht,ResponseSentEvent:()=>yt,Router:()=>Et,RuntimeError:()=>A,SYSTEM_LOGGER:()=>Gt,SchemaBasedRequestValidation:()=>uc,SemanticAttributes:()=>Le,ServiceProviderImpl:()=>Nr,SetBodyInboundPolicy:()=>lc,SetHeadersInboundPolicy:()=>dc,SetHeadersOutboundPolicy:()=>pc,SetQueryParamsInboundPolicy:()=>mc,SetStatusOutboundPolicy:()=>gc,SleepInboundPolicy:()=>fc,StripeMonetizationPlugin:()=>yi,StripeWebhookVerificationInboundPolicy:()=>Ot,SumoLogicLoggingPlugin:()=>er,SupabaseJwtInboundPolicy:()=>hc,SystemRouteName:()=>De,TelemetryPlugin:()=>gt,UpstreamAzureAdServiceAuthInboundPolicy:()=>yc,UpstreamFirebaseAdminAuthInboundPolicy:()=>wc,UpstreamFirebaseUserAuthInboundPolicy:()=>Rc,UpstreamGcpFederatedAuthInboundPolicy:()=>Lr,UpstreamGcpJwtInboundPolicy:()=>Ec,UpstreamGcpServiceAuthInboundPolicy:()=>xc,VMWareLogInsightLoggingPlugin:()=>tr,ValidateJsonSchemaInbound:()=>vc,XmlToJsonOutboundPolicy:()=>kr,ZoneCache:()=>mt,ZuploRequest:()=>oe,ZuploServices:()=>Ft,awsLambdaHandler:()=>ka,environment:()=>Ee,getIdForParameterSchema:()=>Ar,getIdForRefSchema:()=>rc,getIdForRequestBodySchema:()=>_r,getRawOperationDataIdentifierName:()=>nc,httpStatuses:()=>On,openApiSpecHandler:()=>Na,redirectHandler:()=>Ma,sanitizedIdentifierName:()=>nt,serialize:()=>xn,setMoesifContext:()=>Su,trackFeature:()=>f,urlForwardHandler:()=>Da,urlRewriteHandler:()=>Ua,webSocketHandler:()=>Ha,webSocketPipelineHandler:()=>Fa});module.exports=Dc(em);var cs=Be(qe());var Y=class extends Error{static{i(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},A=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 A{static{i(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}},yn=class extends A{static{i(this,"FeatureNotEnabledError")}constructor(e,t){super(e,t),this.name="FeatureNotEnabledError"}};var Yr="2024-03-14",ss=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0}});function as(){return new m({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),IS_PRODUCTION:!1,BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:Yr,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,IS_LOCAL_DEVELOPMENT:!1,COMPATIBILITY_FLAGS:ss[Yr]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}i(as,"getMockEnvironment");var m=class n{static{i(this,"Environment")}config;static#e;static#t=!1;static initialize(e){this.#e||(this.#e=new n(e),this.#t=!0)}static get instance(){return this.#t||(console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=as()),this.#e}constructor({build:e,runtime:t}){let r;try{if(t.__ZUPLO_CONFIG){let o=atob(t.__ZUPLO_CONFIG);r=JSON.parse(o)}}catch{console.warn("Failed to parse runtime configuration")}this.config=r??{},this.build=e,this.runtime=t,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get zuploClientAuthBucketId(){return this.config.zuplo_auth_client_bucket_id??"auth_o8PUdhKxSTOiB794GWPwLQCD"}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get developerApiUrl(){return this.config.developer_api_url??"https://dev.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get authClientId(){return this.runtime.__ZUPLO_AUTH_CLIENT_ID}get authClientSecret(){return this.runtime.__ZUPLO_AUTH_CLIENT_SECRET}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.IS_LOCAL_DEVELOPMENT}get isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var ot=(0,cs.debug)("zuplo:runtime:external-service");function jl(){let n,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=m.instance.runtime;if(e&&e!=="undefined")try{let t=atob(e);n=JSON.parse(t)}catch{}return n}i(jl,"getServiceAuth");async function ls(n,e){let t=jl();if(t)if(ot(`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(m.instance.useLegacyServiceRouting)u=`https://${o}.zuptunnel.com`;else{ot("Using sha256 service routing");let d=m.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await zl(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw ot("Cannot use sha256 service routing, missing build variables"),new A("Failed to generate fully qualified tunnel url.")}let c=new URL(`${u}${r.pathname}${r.search}`);ot(`Calling external service: ${c.toString()}`);let l=await F.fetch(c.toString(),s);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:t.clientId,tunnelHost:u}),new A("Could not connect to secure tunnel.");return l}else throw ot("Cannot call external service with Request object"),new A("Currently, we only support fetch(<some_string>, ...).");else throw ot("There is no external service auth configured for this zup."),new A("There are no external services configured for this zup.")}i(ls,"externalServiceHandler");async function zl(n,e,t,r){let o=n.toLowerCase(),s=e.toLowerCase(),a=t.toLowerCase(),u=Bl(r);ot(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await us(`${s}-${o}`),l=await us(`${s}-${a}-${u}`);return`${c}.${l}`}i(zl,"hashServiceName");async function us(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(us,"hashSegment");function Bl(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(Bl,"sanitizeEnvironmentType");var ps=new Map;ps.set("service:",ls);var ds=globalThis.fetch;function Xr(n,e){let t=Gl(e);if(typeof n=="string"){let r=new URL(n),o=ps.get(r.protocol);return o?o(n,t):ds(n,t)}else return ds(n,t)}i(Xr,"internalFetch");globalThis.fetch=Xr;var Gl=i(n=>{if(!n||n instanceof Request)return n;let e=n;if(!e.zuplo)return n;let t=n;return t.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete n.zuplo,n},"transformInit");var Vl={fetch:Xr},F=Vl;Function.prototype.toString=function(){return"[native code]"};var bn=globalThis,ms=bn.caches;if(ms){let n=ms.open;bn.caches.open=function(e){let t=m.instance.deploymentName??m.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete bn.caches.default,Object.freeze(bn.caches)}var gs=new Map,Qr=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)})}},We=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=gs.get(e);r||(r=new Qr(t),gs.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 eo="__zuplo-expiry-header",mt=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(eo);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(eo,`${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(eo,`${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 se=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new We(r),this.#n=new mt(r,t),this.#r=t}#e;#t;#n;#r;async get(e){let t=this.#t.get(e);if(t)return t;let r=await this.#n.get(e);if(r){let o=Math.floor((r.expires-Date.now())/1e3);if(o>0)return this.#t.put(e,r.data,o),r.data}}put(e,t,r){this.#t.put(e,t,r);let o={data:t,expires:Date.now()+r*1e3},s=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(s)}};var fs="zuplo-request-id",it="zp-rid",to="zp-body-removed",st="cf-ray",hs="x-real-ip",no="cf-ipcity",ro="cf-ipcontinent",oo="cf-ipcountry",io="cf-iplongitude",so="cf-iplatitude",ys="cf-region",bs="cf-region-code",ws="cf-metro-code",Rs="cf-postal-code",Ps="cf-timezone",Is="zp-ipcity",Es="zp-ipcontinent",Ts="zp-ipcountry",xs="zp-iplongitude",vs="zp-iplatitude",Os="true-client-ip",ao="zp-asn",uo="zp-asorg",co="zp-colo",lo="zp-postalcode",po="zp-metrocode",mo="zp-region",go="zp-regioncode",fo="zp-timezone",Cs=[no,ro,oo,io,so,ao,uo,co,lo,po,mo,go,fo],Ss=["zp-","cf-"],As=[it,st,to];var Bt=Symbol("zuplo_meters"),wn=Symbol("zuplo_dynamic_meters"),Gt="system-logger";var ya=require("@opentelemetry/api"),ba=Be(qe());var vn=require("@opentelemetry/api");var Ye=require("@opentelemetry/api");var _s=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function Ls(n){_s=n}i(Ls,"setTelemetryInitFunction");var ks=i(n=>_s(n),"proxyHandler");var Ke=class{static{i(this,"RuntimePlugin")}},Fe=class extends Ke{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},Rn=class extends Fe{static{i(this,"MeteringPlugin")}},gt=class extends Ke{static{i(this,"TelemetryPlugin")}};var Pn=new Set,Ns=new Set;function f(n){Ns.has(n)||(Ns.add(n),Pn.add(n))}i(f,"trackFeature");function Ms(){let n=[...Pn];return Pn.clear(),n}i(Ms,"getUnsentFeatures");function Ds(n){for(let e of n)Pn.add(e)}i(Ds,"restoreFeatures");var Vt=class n{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let t=e.problem,r=JSON.stringify(t,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(f("runtime.problem-response-formatter"),n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(s){throw new A("Error in custom 'problemResponseFormat'",{cause:s})}})}},Je=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,r){return await Vt.problemResponseFormat(e,t,r)}};function In(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&In(t)}return Object.freeze(n)}i(In,"deepFreeze");var oe=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 In(this.#e)}get params(){return In(this.#t)}user};var Wt={},$e=[],ho=[],yo=[],bo=[];var En={addPlugin(n){$e.push(n)},addRequestHook(n){ho.push(n)},addResponseSendingHook(n){yo.push(n)},addResponseSendingFinalHook(n){bo.push(n)}},Hs=i(async(n,e)=>{if(ho.length===0)return n;let t=Ye.trace.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let s of ho){let a=await t.startActiveSpan(s.name,async u=>{let c=await s(o,e);if(c instanceof oe||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:Ye.SpanStatusCode.ERROR}),l}});if(a instanceof oe)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),Zs=i(async(n,e,t)=>{if(yo.length===0)return n;let r=Ye.trace.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let s=n;for(let a of yo)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:Ye.SpanStatusCode.ERROR}),u.end(),l}});return s}finally{o.end()}})},"invokeOnResponseSendingExtensions"),qs=i(async(n,e,t)=>{if(bo.length===0)return;let r=Ye.trace.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let s of bo)await r.startActiveSpan(s.name,async a=>{try{await s(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:Ye.SpanStatusCode.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),Us=!1;async function Fs(n){if(!Us){n&&(f("runtime.extensions"),await n(En)),Wt.value=En;for(let e of $e)if(e instanceof gt){let{requestHandlerProxy:t}=e.instrument({accountName:m.instance.build.ACCOUNT_NAME,projectName:m.instance.build.PROJECT_NAME,buildId:m.instance.build.BUILD_ID,zuploVersion:m.instance.build.ZUPLO_VERSION,compatibilityDate:m.instance.build.COMPATIBILITY_DATE,instanceId:m.instance.instanceId,environmentType:m.instance.loggingEnvironmentType,environmentStage:m.instance.loggingEnvironmentStage,deploymentName:m.instance.deploymentName});Ls(t)}for(let e of $e)e instanceof Fe&&await e.initialize(En);Vt.setProblemResponseFormat(En.problemResponseFormat),Us=!0}}i(Fs,"initializeRuntime");var Tn={Json:"application/json",Form:"application/x-www-form-urlencoded"};function xn(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(Tn.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(Tn.Json)||!e?JSON.stringify(n):n}i(xn,"serialize");function ft(n){return Re.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(Re.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}i(ft,"isSystemRoute");var fe=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,t)=>async(r,o)=>vn.trace.getTracer("pipeline").startActiveSpan(`handler:${o.route.handler.export}`,async a=>{try{return await e(r,o)}catch(u){o.log.error("Error executing request handler.",u);let c=t.errorHandler(r,o,u);return a.setStatus({code:vn.SpanStatusCode.ERROR}),c}finally{a.end()}});#t=({processors:e,gateway:t,handler:r})=>async(o,s)=>{let a=[...e],u=i(async P=>{let C=a.pop();return C?C(o,s,t,u):await this.#e(async z=>{let q=await r(z,s);return Wl(q)},t)(P,s)},"nextPipe"),l=await u(o),d=new URL(o.url);if(ft(d)&&m.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new ht(o,l);s.dispatchEvent(p);let h=Pe.getContextExtensions(s),y=h.latestRequest,_;try{_=await p.mutableResponse}catch(P){return s.log.error(P),t.errorHandler(o,s,P)}try{_=await h.onResponseSending(_,y,s)}catch(P){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(o,s,P)}try{_=await Zs(_,y,s)}catch(P){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(o,s,P)}s.dispatchEvent(new yt(o,_));try{await h.onResponseSendingFinal(l,y,s)}catch(P){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}try{await qs(l,y,s)}catch(P){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}return _}};function Wl(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(xn(n),{headers:{"content-type":"application/json"}})}i(Wl,"resultToResponse");var Kt=(w=>(w[w.CONTINUE=100]="CONTINUE",w[w.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",w[w.PROCESSING=102]="PROCESSING",w[w.EARLY_HINTS=103]="EARLY_HINTS",w[w.OK=200]="OK",w[w.CREATED=201]="CREATED",w[w.ACCEPTED=202]="ACCEPTED",w[w.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",w[w.NO_CONTENT=204]="NO_CONTENT",w[w.RESET_CONTENT=205]="RESET_CONTENT",w[w.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",w[w.MULTI_STATUS=207]="MULTI_STATUS",w[w.ALREADY_REPORTED=208]="ALREADY_REPORTED",w[w.IM_USED=226]="IM_USED",w[w.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",w[w.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",w[w.FOUND=302]="FOUND",w[w.SEE_OTHER=303]="SEE_OTHER",w[w.NOT_MODIFIED=304]="NOT_MODIFIED",w[w.USE_PROXY=305]="USE_PROXY",w[w.SWITCH_PROXY=306]="SWITCH_PROXY",w[w.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",w[w.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",w[w.BAD_REQUEST=400]="BAD_REQUEST",w[w.UNAUTHORIZED=401]="UNAUTHORIZED",w[w.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",w[w.FORBIDDEN=403]="FORBIDDEN",w[w.NOT_FOUND=404]="NOT_FOUND",w[w.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",w[w.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",w[w.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",w[w.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",w[w.CONFLICT=409]="CONFLICT",w[w.GONE=410]="GONE",w[w.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",w[w.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",w[w.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",w[w.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",w[w.URI_TOO_LONG=414]="URI_TOO_LONG",w[w.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",w[w.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",w[w.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",w[w.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",w[w.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",w[w.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",w[w.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",w[w.LOCKED=423]="LOCKED",w[w.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",w[w.TOO_EARLY=425]="TOO_EARLY",w[w.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",w[w.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",w[w.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",w[w.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",w[w.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",w[w.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",w[w.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",w[w.BAD_GATEWAY=502]="BAD_GATEWAY",w[w.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",w[w.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",w[w.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",w[w.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",w[w.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",w[w.LOOP_DETECTED=508]="LOOP_DETECTED",w[w.NOT_EXTENDED=510]="NOT_EXTENDED",w[w.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",w))(Kt||{}),$s={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Content Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Content",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};var Kl={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"},On=Kl;function Jl(n){return`${new URL(n.url).pathname}`}i(Jl,"instance");function Yl(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:m.instance.build.BUILD_ID},r=n.headers.get(st);return r&&(t.rayId=r),t}i(Yl,"trace");var Xl=i((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:Jl(e),trace:Yl(e,t),...r},additionalHeaders:o,statusText:On[n.status]}),"merge"),wo=class{static{i(this,"HttpProblemsBase")}static format=(e,t,r)=>"problem"in e?Je.format(e,t,r):Je.format({problem:e},t,r);static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:$s[e],...t}}},T=class extends wo{static{i(this,"HttpProblems")}static#e(e,t,r,o,s){let a=Xl(this.getProblemFromStatus(e),t,r,o,s);return Je.format(a,t,r)}static continue=(e,t,r,o)=>this.#e(200,e,t,r,o);static switchingProtocols=(e,t,r,o)=>this.#e(101,e,t,r,o);static processing=(e,t,r,o)=>this.#e(102,e,t,r,o);static earlyHints=(e,t,r,o)=>this.#e(103,e,t,r,o);static ok=(e,t,r,o)=>this.#e(200,e,t,r,o);static created=(e,t,r,o)=>this.#e(201,e,t,r,o);static accepted=(e,t,r,o)=>this.#e(202,e,t,r,o);static nonAuthoritativeInformation=(e,t,r,o)=>this.#e(203,e,t,r,o);static noContent=(e,t,r,o)=>this.#e(204,e,t,r,o);static resetContent=(e,t,r,o)=>this.#e(205,e,t,r,o);static partialContent=(e,t,r,o)=>this.#e(206,e,t,r,o);static multiStatus=(e,t,r,o)=>this.#e(207,e,t,r,o);static alreadyReported=(e,t,r,o)=>this.#e(208,e,t,r,o);static imUsed=(e,t,r,o)=>this.#e(226,e,t,r,o);static multipleChoices=(e,t,r,o)=>this.#e(300,e,t,r,o);static movedPermanently=(e,t,r,o)=>this.#e(301,e,t,r,o);static found=(e,t,r,o)=>this.#e(302,e,t,r,o);static seeOther=(e,t,r,o)=>this.#e(303,e,t,r,o);static notModified=(e,t,r,o)=>this.#e(304,e,t,r,o);static useProxy=(e,t,r,o)=>this.#e(305,e,t,r,o);static switchProxy=(e,t,r,o)=>this.#e(306,e,t,r,o);static temporaryRedirect=(e,t,r,o)=>this.#e(307,e,t,r,o);static permanentRedirect=(e,t,r,o)=>this.#e(308,e,t,r,o);static badRequest=(e,t,r,o)=>this.#e(400,e,t,r,o);static unauthorized=(e,t,r,o)=>this.#e(401,e,t,r,o);static paymentRequired=(e,t,r,o)=>this.#e(402,e,t,r,o);static forbidden=(e,t,r,o)=>this.#e(403,e,t,r,o);static notFound=(e,t,r,o)=>this.#e(404,e,t,r,o);static methodNotAllowed=(e,t,r,o)=>this.#e(405,e,t,r,o);static notAcceptable=(e,t,r,o)=>this.#e(406,e,t,r,o);static proxyAuthenticationRequired=(e,t,r,o)=>this.#e(407,e,t,r,o);static requestTimeout=(e,t,r,o)=>this.#e(408,e,t,r,o);static conflict=(e,t,r,o)=>this.#e(409,e,t,r,o);static gone=(e,t,r,o)=>this.#e(410,e,t,r,o);static lengthRequired=(e,t,r,o)=>this.#e(411,e,t,r,o);static preconditionFailed=(e,t,r,o)=>this.#e(412,e,t,r,o);static contentTooLarge=(e,t,r,o)=>this.#e(413,e,t,r,o);static uriTooLong=(e,t,r,o)=>this.#e(414,e,t,r,o);static unsupportedMediaType=(e,t,r,o)=>this.#e(415,e,t,r,o);static rangeNotSatisfiable=(e,t,r,o)=>this.#e(416,e,t,r,o);static expectationFailed=(e,t,r,o)=>this.#e(417,e,t,r,o);static imATeapot=(e,t,r,o)=>this.#e(418,e,t,r,o);static misdirectedRequest=(e,t,r,o)=>this.#e(421,e,t,r,o);static unprocessableContent=(e,t,r,o)=>this.#e(422,e,t,r,o);static locked=(e,t,r,o)=>this.#e(423,e,t,r,o);static failedDependency=(e,t,r,o)=>this.#e(424,e,t,r,o);static tooEarly=(e,t,r,o)=>this.#e(425,e,t,r,o);static upgradeRequired=(e,t,r,o)=>this.#e(426,e,t,r,o);static preconditionRequired=(e,t,r,o)=>this.#e(428,e,t,r,o);static tooManyRequests=(e,t,r,o)=>this.#e(429,e,t,r,o);static requestHeaderFieldsTooLarge=(e,t,r,o)=>this.#e(431,e,t,r,o);static unavailableForLegalReasons=(e,t,r,o)=>this.#e(451,e,t,r,o);static internalServerError=(e,t,r,o)=>this.#e(500,e,t,r,o);static notImplemented=(e,t,r,o)=>this.#e(501,e,t,r,o);static badGateway=(e,t,r,o)=>this.#e(502,e,t,r,o);static serviceUnavailable=(e,t,r,o)=>this.#e(503,e,t,r,o);static gatewayTimeout=(e,t,r,o)=>this.#e(504,e,t,r,o);static httpVersionNotSupported=(e,t,r,o)=>this.#e(505,e,t,r,o);static variantAlsoNegotiates=(e,t,r,o)=>this.#e(506,e,t,r,o);static insufficientStorage=(e,t,r,o)=>this.#e(507,e,t,r,o);static loopDetected=(e,t,r,o)=>this.#e(508,e,t,r,o);static notExtended=(e,t,r,o)=>this.#e(510,e,t,r,o);static networkAuthenticationRequired=(e,t,r,o)=>this.#e(511,e,t,r,o)};var Xe=class extends Ke{static{i(this,"MetricsPlugin")}};var te=class n{static{i(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let t=n.#e.get(e);if(!t){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new Y(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var Q=class{static{i(this,"BatchDispatch")}constructor(e,t,r,o){this.#t=e,this.#i=t,this.#r=r,this.#n=o??console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=e=>{this.#o.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{t()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var Cn=class{static{i(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=m.instance.loggingId,this.#e=e,this.#t=new Q("ellie-metrics-transport",10,this.dispatchFunction,te.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let{remoteLogURL:t,deploymentName:r}=m.instance,{ACCOUNT_NAME:o,PROJECT_NAME:s}=m.instance.build,a=e.map(d=>{let p=Object.assign({},d);return delete p.requestContentLength,delete p.responseContentLength,p}),u=Ms(),c={metadata:{timestamp:new Date,accountName:o,projectName:s,deploymentName:r},metrics:a,features:u},l=await F.fetch(`${t}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(c),headers:{"content-type":"application/json","zp-dn":m.instance.deploymentName??"unknown","user-agent":m.instance.systemUserAgent}});if(!l.ok){let d=await l.text();te.getLogger(this.#e).error(`Metrics POST responded ${l.status}: ${l.statusText}`,d),Ds(u)}}};var le=class{static{i(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:r,systemRouteName:o,corsPolicy:s="none"}){this.label=e,this.path=t,this.methods=r,this.corsPolicy=s,this.version=Jt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Jt={name:"__system-no-version",pathPrefix:""};var Ie=i(async(n,e,t,r)=>{let o=new Date,s=Date.now(),a=await r(n),u=n.headers.get(st)??void 0,c=n.headers.get(Os)??void 0,l=e.incomingRequestProperties,d;e.route instanceof le&&(d=e.route.systemRouteName);let p=Pe.getContextExtensions(e).latestRequest,h={timestamp:o,statusCode:a.status,durationMs:Date.now()-s,requestContentLength:n.headers.get("content-length")?Number(n.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:n.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:m.instance.instanceId,userSub:p.user?.sub,clientIp:c},y=[];return y.push(new Cn(e)),$e.forEach(_=>{if(_ instanceof Xe){let P=_.getTransport();y.push(P)}}),y.forEach(_=>{_.pushMetrics(h,e)}),a},"metricsProcessor");var De=(c=>(c.Build="build-data",c.CorsPreflight="cors-preflight",c.DeveloperPortal="developer-portal",c.DeveloperPortalLegacy="developer-portal-legacy",c.StripePlugin="stripe-plugin",c.EmptyGatewayCatchall="empty-gateway-catchall",c.Ping="ping",c.UnmatchedPath="unmatched-path",c))(De||{});var Ro=i((n,e)=>{let t=i(async(s,a)=>{let c=new URL(s.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return T.notFound(s,a);let l=m.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,compatibilityDate:l.COMPATIBILITY_DATE,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=s.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&te.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new fe({processors:[Ie],handler:t,gateway:e}),o=new le({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var{toString:Ql}=Object.prototype,{propertyIsEnumerable:ed}=Object.prototype;function Po(n){return Ql.call(n)}i(Po,"toString");function ve(n){return typeof n=="string"}i(ve,"isString");function bt(n){return ve(n)&&n!==""}i(bt,"isNonEmptyString");function js(n){return Po(n)==="[object RegExp]"}i(js,"isRegexp");function zs(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>ed.call(n,e))]}i(zs,"getOwnEnumerableKeys");function at(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}i(at,"isObject");function Io(n){return typeof n=="number"&&!isNaN(n)}i(Io,"isNumber");function Eo(n){return n===!0||n===!1}i(Eo,"isBoolean");function Bs(n){return typeof n>"u"}i(Bs,"isUndefined");function Gs(n){return Bs(n)||n===null}i(Gs,"isUndefinedOrNull");function Yt(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(Yt,"isErrorLike");var Vs=new Map;function wt(n){if(Array.isArray(n)&&!n.some(o=>typeof o!="number"))return n;if(typeof n!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(n))throw new Error("Malformed input string");let e=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(wt,"statusCodesStringToNumberArray");function ut(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 A(`Error applying ${t} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i(ut,"getValueFromRequestUser");function ct(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(ve(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(ct,"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(!at(t))throw new g(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!bt(t.name))throw new g("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!Io(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&&!Eo(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=To(t,"allowedHeaders"),o=To(t,"allowedMethods"),s=To(t,"exposeHeaders"),a;try{a=ct(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 To(n,e){let t;if(n[e]!==void 0)try{t=ct(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(To,"parseOptionalProperty");var Sn=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"),An=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 xo=i((n,e)=>{let t=e.routeData.corsPolicies,r=i(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return T.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let h=n.lookup(l,c);if(!h)return T.notFound(a,u);let y=h.routeConfiguration,_=td(l,d,p,y,t);return _.isValid?new Response(void 0,{status:200,statusText:"OK",headers:_.headers}):(_.error&&u.log.warn(_.error),T.notFound(a,u))},"optionsHandler"),o=new fe({processors:[Ie],handler:r,gateway:e}),s=new le({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(s,o.execute)},"registerCorsRoute"),td=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=Sn(a.allowedOrigins,t);return u?{isValid:!0,headers:An(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var Ks=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 fe({processors:[Ie],handler:t,gateway:e}),o=new le({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 vo=new le({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Js=i((n,e)=>{let t=i(async(o,s)=>{let a=Wt.value?.notFoundHandler;if(a){let u=Pe.getContextExtensions(s);return a(o,s,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return T.notFound(o,s)},"notFoundHandler"),r=new fe({processors:[Ie],handler:t,gateway:e});n.addRoute(vo,r.execute)},"registerNotMatchedHandler");var nd=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Ys=i(n=>{nd.forEach(e=>n.delete(e))},"stripCorsHeaders"),_n=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 Ys(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=rd(o,t.routeData.corsPolicies),u=od(n,a),c=new Headers(s.headers);return Ys(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"),rd=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"),od=i((n,e)=>{let t=Sn(e.allowedOrigins,n.headers.get("origin"));return t?An(e,t):{}},"getCorsHeaders");var Oo=i((n,e)=>{let t=i(async()=>new Response(JSON.stringify({buildId:m.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new fe({processors:[_n],handler:t,gateway:e}),o=new le({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");var Rt=require("@opentelemetry/api");var Le={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var Ln=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!ve(t))throw new A(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},de=class extends Ln{static{i(this,"InboundPolicy")}},je=class extends Ln{static{i(this,"OutboundPolicy")}};var Ao=class extends de{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)}},_o=class extends je{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)}},Co=new Map;function Xt(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(s=>!Co.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 de)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new Ao(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}')`);Co.set(a.name,c)}),t.map(s=>{let a=Co.get(s);if(a===void 0)throw new A("Internal error. Policy not found in cache.");return a})}i(Xt,"getInboundPolicyInstances");var So=new Map;function id(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!So.has(o)).forEach(o=>{let s=e?.find(c=>c.name===o);if(!s)throw new g(`Invalid state - no Policy with the name '${o}' on route '${n.path}' was found in the policies configuration (check case).`);if(typeof s.handler?.module!="object")throw new g(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof s.handler?.module}')`);let a=s.handler?.module[s.handler.export],u;if(typeof a!="function")throw new g(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof je)u=new a(s.handler.options??{},s.name);else if(typeof a=="function")u=new _o(a,s.handler.options??{},s.name);else throw new g(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new g(`Invalid state - invalid handler on policy '${o}' on route '${n.path}'`);So.set(s.name,u)}),t.map(o=>{let s=So.get(o);if(s===void 0)throw new A("Internal error. Policy not found in cache.");return s})}i(id,"getOutboundPolicyInstances");var Lo=i(n=>async(e,t)=>{let r=Pe.getContextExtensions(t),o=Rt.trace.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;let l=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{let p=await c.handler(u,t);if(p instanceof Request||p instanceof oe||p instanceof Response)return d.end(),p;{let h=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:Rt.SpanStatusCode.ERROR}),d.recordException(h),h}});if(l instanceof oe)u=l;else if(l instanceof Request)u=new oe(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),sd=i(n=>async(e,t,r)=>{let o=Rt.trace.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(Le.PolicyName,c.policyName),d.setAttribute(Le.PolicyType,c.policyType);let p=await c.handler(u,t,r);if(p instanceof Response)return p;{let h=new 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:Rt.SpanStatusCode.ERROR}),d.recordException(h),h}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),kn=i(async(n,e,t,r)=>{let o=Xt(e.route,t.routeData.policies),s=id(e.route,t.routeData.policies);return Qs({request:n,context:e,inboundPolicies:o,outboundPolicies:s,gateway:t,next:r})},"policyProcessor");function Xs({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>Qs({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(Xs,"createInternalPolicyProcessor");async function Qs({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:s}){let a=Lo(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await s(u),l=sd(r),d;return m.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,n,e):d=c.ok?l(c,n,e):c,d}catch(u){return e.log.error(u),o.errorHandler(n,e,u)}}i(Qs,"executePolicyProcessor");function ea(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||ad,s=0;for(;s<n.length;){let a=n.indexOf("=",s);if(a===-1)break;let u=n.indexOf(";",s);if(u===-1)u=n.length;else if(u<a){s=n.lastIndexOf(";",a-1)+1;continue}let c=n.slice(s,a).trim();if(t[c]===void 0){let l=n.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),t[c]=ud(l,o)}s=u+1}return t}i(ea,"parse");function ad(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}i(ad,"decode");function ud(n,e){try{return e(n)}catch{return n}}i(ud,"tryDecode");function ta(n,e){try{let t=/v\d+(-\d+)?/g,o=ea(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}i(ta,"devPortalBaseURL");var na="/__zuplo/dev-portal",cd="dev-portal-id",ld="dev-portal-host",dd="zp-account",pd="zp-project",md="dev-portal-build",gd=`
35
+ `)+" "+t[1]:t[0]+e+" "+n.join(", ")+" "+t[1]}i(Nl,"reduceToSingleString")});var os=zt(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.format=void 0;var Dl=Qi(),Ml=rs(),Ul=i((n,...e)=>(0,Dl.format)(Ml.inspect,n,e),"format");hn.format=Ul});var He=zt(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.debug=Ve.withoutEnv=Ve.Debugger=void 0;var ql=Ji(),Zl=os(),yn=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=(0,ql.generateColor)(t),this.last=0,this.enabled=e.enabled.some(r=>r.test(t))}log(...e){if(!this.enabled)return;let t,r=e[0];typeof r=="function"?t=r():t=String(r);let o=Date.now()-(this.last||Date.now());t=(0,Zl.format)(t,...e);let s=`${this.color(this.ns)} ${t} ${this.color(`+${o}ms`)}`;console.log(s),this.last=Date.now()}};Ve.Debugger=yn;var bn=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function is(n){return!n||n.length===0?[]:(n=n.replace(/\s/g,"").replace(/\*/g,".+"),n.split(",").map(e=>new RegExp(`^${e}$`)))}i(is,"extract");var Gt;function Hl(n){n||(n=[]),typeof n=="string"&&(n=is(n)),Gt=new bn(n)}i(Hl,"withoutEnv");Ve.withoutEnv=Hl;function Fl(n){let e=globalThis.DEBUG;Gt||(Gt=new bn(is(e)));let t=new yn(Gt,n);return Gt.debuggers.set(n,t),Object.assign(t.log.bind(t),{self:t})}i(Fl,"debug");Ve.debug=Fl});var tm={};Nc(tm,{AWSLoggingPlugin:()=>rr,AmberfloMeteringInboundPolicy:()=>Ya,AmberfloMeteringPolicy:()=>lr,ApiAuthKeyInboundPolicy:()=>tu,ApiKeyInboundPolicy:()=>dr,AuditLogDataStaxProvider:()=>sr,AuditLogPlugin:()=>ar,Auth0JwtInboundPolicy:()=>ou,AwsLambdaHandlerExtensions:()=>La,AxiomaticsAuthZInboundPolicy:()=>gr,BackgroundDispatcher:()=>Lr,BackgroundLoader:()=>kr,BasicAuthInboundPolicy:()=>iu,BasicRateLimitInboundPolicy:()=>Ai,BatchDispatch:()=>ee,BrownoutInboundPolicy:()=>yr,CachingInboundPolicy:()=>au,ChangeMethodInboundPolicy:()=>uu,ClearHeadersInboundPolicy:()=>lu,ClearHeadersOutboundPolicy:()=>du,ClerkJwtInboundPolicy:()=>pu,CognitoJwtInboundPolicy:()=>mu,ComplexRateLimitInboundPolicy:()=>Rr,CompositeInboundPolicy:()=>hu,ConfigurationError:()=>g,ContentTypes:()=>xn,ContextData:()=>ue,CryptoBeta:()=>Dr,CurityPhantomTokenInboundPolicy:()=>yu,DataDogLoggingPlugin:()=>Bn,DataDogMetricsPlugin:()=>or,DynaTraceLoggingPlugin:()=>Xn,DynatraceMetricsPlugin:()=>ir,FirebaseJwtInboundPolicy:()=>bu,FormDataToJsonInboundPolicy:()=>wu,GeoFilterInboundPolicy:()=>Ru,GoogleCloudLoggingPlugin:()=>Fn,Handler:()=>Qn,HttpProblems:()=>T,HttpStatusCode:()=>Yt,InboundPolicy:()=>le,JWTScopeValidationInboundPolicy:()=>Pu,KeyValueStore:()=>Ur,LokiLoggingPlugin:()=>er,LookupResult:()=>xt,MemoryZoneReadThroughCache:()=>se,MockApiInboundPolicy:()=>Eu,MoesifInboundPolicy:()=>Su,MonetizationInboundPolicy:()=>Ir,OktaFGAAuthZInboundPolicy:()=>xr,OktaJwtInboundPolicy:()=>qu,OpenFGAAuthZInboundPolicy:()=>Or,OpenIdJwtInboundPolicy:()=>we,OutboundPolicy:()=>je,ProblemResponseFormatter:()=>Je,PropelAuthJwtInboundPolicy:()=>Hu,QuotaInboundPolicy:()=>wr,RateLimitInboundPolicy:()=>Ai,ReadmeMetricsInboundPolicy:()=>Wu,RemoveHeadersInboundPolicy:()=>Ku,RemoveHeadersOutboundPolicy:()=>Ju,RemoveQueryParamsInboundPolicy:()=>Qu,ReplaceStringOutboundPolicy:()=>Yu,RequestSizeLimitInboundPolicy:()=>ec,RequestValidationInboundPolicy:()=>ki,RequireOriginInboundPolicy:()=>uc,ResponseSendingEvent:()=>Rt,ResponseSentEvent:()=>Pt,Router:()=>Ot,RuntimeError:()=>_,SYSTEM_LOGGER:()=>Kt,SchemaBasedRequestValidation:()=>ac,SemanticAttributes:()=>Le,ServiceProviderImpl:()=>_r,SetBodyInboundPolicy:()=>cc,SetHeadersInboundPolicy:()=>lc,SetHeadersOutboundPolicy:()=>dc,SetQueryParamsInboundPolicy:()=>pc,SetStatusOutboundPolicy:()=>mc,SleepInboundPolicy:()=>gc,StripeMonetizationPlugin:()=>gi,StripeWebhookVerificationInboundPolicy:()=>At,SumoLogicLoggingPlugin:()=>tr,SupabaseJwtInboundPolicy:()=>fc,SystemRouteName:()=>Me,TelemetryPlugin:()=>bt,UpstreamAzureAdServiceAuthInboundPolicy:()=>hc,UpstreamFirebaseAdminAuthInboundPolicy:()=>bc,UpstreamFirebaseUserAuthInboundPolicy:()=>wc,UpstreamGcpFederatedAuthInboundPolicy:()=>Sr,UpstreamGcpJwtInboundPolicy:()=>Ic,UpstreamGcpServiceAuthInboundPolicy:()=>Tc,VMWareLogInsightLoggingPlugin:()=>nr,ValidateJsonSchemaInbound:()=>xc,XmlToJsonOutboundPolicy:()=>Ar,ZoneCache:()=>yt,ZuploRequest:()=>oe,ZuploServices:()=>jt,awsLambdaHandler:()=>ka,environment:()=>Ee,getIdForParameterSchema:()=>vr,getIdForRefSchema:()=>nc,getIdForRequestBodySchema:()=>Cr,getRawOperationDataIdentifierName:()=>tc,httpStatuses:()=>Cn,openApiSpecHandler:()=>Na,redirectHandler:()=>Da,sanitizedIdentifierName:()=>it,serialize:()=>On,setMoesifContext:()=>Cu,trackFeature:()=>f,urlForwardHandler:()=>Ma,urlRewriteHandler:()=>Ua,webSocketHandler:()=>qa,webSocketPipelineHandler:()=>Fa});module.exports=Dc(tm);var cs=ze(He());var Q=class extends Error{static{i(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},_=class extends Error{static{i(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},g=class extends _{static{i(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}},wn=class extends _{static{i(this,"FeatureNotEnabledError")}constructor(e,t){super(e,t),this.name="FeatureNotEnabledError"}};var Wr="2024-03-14",ss=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0}});function as(){return new m({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),IS_PRODUCTION:!1,BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:Wr,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,IS_LOCAL_DEVELOPMENT:!1,COMPATIBILITY_FLAGS:ss[Wr]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}i(as,"getMockEnvironment");var m=class n{static{i(this,"Environment")}config;static#e;static#t=!1;static initialize(e){this.#e||(this.#e=new n(e),this.#t=!0)}static get instance(){return this.#t||(console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=as()),this.#e}constructor({build:e,runtime:t}){let r;try{if(t.__ZUPLO_CONFIG){let o=atob(t.__ZUPLO_CONFIG);r=JSON.parse(o)}}catch{console.warn("Failed to parse runtime configuration")}this.config=r??{},this.build=e,this.runtime=t,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get zuploClientAuthBucketId(){return this.config.zuplo_auth_client_bucket_id??"auth_o8PUdhKxSTOiB794GWPwLQCD"}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get developerApiUrl(){return this.config.developer_api_url??"https://dev.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get authClientId(){return this.runtime.__ZUPLO_AUTH_CLIENT_ID}get authClientSecret(){return this.runtime.__ZUPLO_AUTH_CLIENT_SECRET}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.IS_LOCAL_DEVELOPMENT}get isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var at=(0,cs.debug)("zuplo:runtime:external-service");function $l(){let n,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=m.instance.runtime;if(e&&e!=="undefined")try{let t=atob(e);n=JSON.parse(t)}catch{}return n}i($l,"getServiceAuth");async function ls(n,e){let t=$l();if(t)if(at(`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(m.instance.useLegacyServiceRouting)u=`https://${o}.zuptunnel.com`;else{at("Using sha256 service routing");let d=m.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await jl(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw at("Cannot use sha256 service routing, missing build variables"),new _("Failed to generate fully qualified tunnel url.")}let c=new URL(`${u}${r.pathname}${r.search}`);at(`Calling external service: ${c.toString()}`);let l=await F.fetch(c.toString(),s);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:t.clientId,tunnelHost:u}),new _("Could not connect to secure tunnel.");return l}else throw at("Cannot call external service with Request object"),new _("Currently, we only support fetch(<some_string>, ...).");else throw at("There is no external service auth configured for this zup."),new _("There are no external services configured for this zup.")}i(ls,"externalServiceHandler");async function jl(n,e,t,r){let o=n.toLowerCase(),s=e.toLowerCase(),a=t.toLowerCase(),u=Bl(r);at(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await us(`${s}-${o}`),l=await us(`${s}-${a}-${u}`);return`${c}.${l}`}i(jl,"hashServiceName");async function us(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(us,"hashSegment");function Bl(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(Bl,"sanitizeEnvironmentType");var ps=new Map;ps.set("service:",ls);var ds=globalThis.fetch;function Kr(n,e){let t=zl(e);if(typeof n=="string"){let r=new URL(n),o=ps.get(r.protocol);return o?o(n,t):ds(n,t)}else return ds(n,t)}i(Kr,"internalFetch");globalThis.fetch=Kr;var zl=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 Gl={fetch:Kr},F=Gl;Function.prototype.toString=function(){return"[native code]"};var Rn=globalThis,ms=Rn.caches;if(ms){let n=ms.open;Rn.caches.open=function(e){let t=m.instance.deploymentName??m.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete Rn.caches.default,Object.freeze(Rn.caches)}var gs=new Map,Jr=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)})}},We=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=gs.get(e);r||(r=new Jr(t),gs.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 Qr="__zuplo-expiry-header",yt=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(Qr);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(Qr,`${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(Qr,`${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 se=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new We(r),this.#n=new yt(r,t),this.#r=t}#e;#t;#n;#r;async get(e){let t=this.#t.get(e);if(t)return t;let r=await this.#n.get(e);if(r){let o=Math.floor((r.expires-Date.now())/1e3);if(o>0)return this.#t.put(e,r.data,o),r.data}}put(e,t,r){this.#t.put(e,t,r);let o={data:t,expires:Date.now()+r*1e3},s=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(s)}};var fs="zuplo-request-id",ut="zp-rid",Yr="zp-body-removed",ct="cf-ray",hs="x-real-ip",Xr="cf-ipcity",eo="cf-ipcontinent",to="cf-ipcountry",no="cf-iplongitude",ro="cf-iplatitude",ys="cf-region",bs="cf-region-code",ws="cf-metro-code",Rs="cf-postal-code",Ps="cf-timezone",Is="zp-ipcity",Es="zp-ipcontinent",Ts="zp-ipcountry",xs="zp-iplongitude",Os="zp-iplatitude",vs="true-client-ip",oo="zp-asn",io="zp-asorg",so="zp-colo",ao="zp-postalcode",uo="zp-metrocode",co="zp-region",lo="zp-regioncode",po="zp-timezone",Cs=[Xr,eo,to,no,ro,oo,io,so,ao,uo,co,lo,po],Ss=["zp-","cf-"],As=[ut,ct,Yr];var Vt=Symbol("zuplo_meters"),Wt=Symbol("zuplo_dynamic_meters"),Kt="system-logger";var ya=require("@opentelemetry/api"),ba=ze(He());var vn=require("@opentelemetry/api");var Qe=require("@opentelemetry/api");var _s=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function Ls(n){_s=n}i(Ls,"setTelemetryInitFunction");var ks=i(n=>_s(n),"proxyHandler");var Ke=class{static{i(this,"RuntimePlugin")}},Fe=class extends Ke{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},Pn=class extends Fe{static{i(this,"MeteringPlugin")}},bt=class extends Ke{static{i(this,"TelemetryPlugin")}};var In=new Set,Ns=new Set;function f(n){Ns.has(n)||(Ns.add(n),In.add(n))}i(f,"trackFeature");function Ds(){let n=[...In];return In.clear(),n}i(Ds,"getUnsentFeatures");function Ms(n){for(let e of n)In.add(e)}i(Ms,"restoreFeatures");var Jt=class n{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let t=e.problem,r=JSON.stringify(t,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(f("runtime.problem-response-formatter"),n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(s){throw new _("Error in custom 'problemResponseFormat'",{cause:s})}})}},Je=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,r){return await Jt.problemResponseFormat(e,t,r)}};function En(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&En(t)}return Object.freeze(n)}i(En,"deepFreeze");var oe=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 En(this.#e)}get params(){return En(this.#t)}user};var Qt={},$e=[],mo=[],go=[],fo=[];var Tn={addPlugin(n){$e.push(n)},addRequestHook(n){mo.push(n)},addResponseSendingHook(n){go.push(n)},addResponseSendingFinalHook(n){fo.push(n)}},qs=i(async(n,e)=>{if(mo.length===0)return n;let t=Qe.trace.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let s of mo){let a=await t.startActiveSpan(s.name,async u=>{let c=await s(o,e);if(c instanceof oe||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:Qe.SpanStatusCode.ERROR}),l}});if(a instanceof oe)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),Zs=i(async(n,e,t)=>{if(go.length===0)return n;let r=Qe.trace.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let s=n;for(let a of go)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:Qe.SpanStatusCode.ERROR}),u.end(),l}});return s}finally{o.end()}})},"invokeOnResponseSendingExtensions"),Hs=i(async(n,e,t)=>{if(fo.length===0)return;let r=Qe.trace.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let s of fo)await r.startActiveSpan(s.name,async a=>{try{await s(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:Qe.SpanStatusCode.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),Us=!1;async function Fs(n){if(!Us){n&&(f("runtime.extensions"),await n(Tn)),Qt.value=Tn;for(let e of $e)if(e instanceof bt){let{requestHandlerProxy:t}=e.instrument({accountName:m.instance.build.ACCOUNT_NAME,projectName:m.instance.build.PROJECT_NAME,buildId:m.instance.build.BUILD_ID,zuploVersion:m.instance.build.ZUPLO_VERSION,compatibilityDate:m.instance.build.COMPATIBILITY_DATE,instanceId:m.instance.instanceId,environmentType:m.instance.loggingEnvironmentType,environmentStage:m.instance.loggingEnvironmentStage,deploymentName:m.instance.deploymentName});Ls(t)}for(let e of $e)e instanceof Fe&&await e.initialize(Tn);Jt.setProblemResponseFormat(Tn.problemResponseFormat),Us=!0}}i(Fs,"initializeRuntime");var xn={Json:"application/json",Form:"application/x-www-form-urlencoded"};function On(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(xn.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(xn.Json)||!e?JSON.stringify(n):n}i(On,"serialize");function wt(n){return Re.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(Re.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}i(wt,"isSystemRoute");var he=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,t)=>async(r,o)=>vn.trace.getTracer("pipeline").startActiveSpan(`handler:${o.route.handler.export}`,async a=>{try{return await e(r,o)}catch(u){o.log.error("Error executing request handler.",u);let c=t.errorHandler(r,o,u);return a.setStatus({code:vn.SpanStatusCode.ERROR}),c}finally{a.end()}});#t=({processors:e,gateway:t,handler:r})=>async(o,s)=>{let a=[...e],u=i(async P=>{let O=a.pop();return O?O(o,s,t,u):await this.#e(async B=>{let q=await r(B,s);return Vl(q)},t)(P,s)},"nextPipe"),l=await u(o),d=new URL(o.url);if(wt(d)&&m.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new Rt(o,l);s.dispatchEvent(p);let h=Pe.getContextExtensions(s),y=h.latestRequest,A;try{A=await p.mutableResponse}catch(P){return s.log.error(P),t.errorHandler(o,s,P)}try{A=await h.onResponseSending(A,y,s)}catch(P){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(o,s,P)}try{A=await Zs(A,y,s)}catch(P){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(o,s,P)}s.dispatchEvent(new Pt(o,A));try{await h.onResponseSendingFinal(l,y,s)}catch(P){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}try{await Hs(l,y,s)}catch(P){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}return A}};function Vl(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(On(n),{headers:{"content-type":"application/json"}})}i(Vl,"resultToResponse");var Yt=(w=>(w[w.CONTINUE=100]="CONTINUE",w[w.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",w[w.PROCESSING=102]="PROCESSING",w[w.EARLY_HINTS=103]="EARLY_HINTS",w[w.OK=200]="OK",w[w.CREATED=201]="CREATED",w[w.ACCEPTED=202]="ACCEPTED",w[w.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",w[w.NO_CONTENT=204]="NO_CONTENT",w[w.RESET_CONTENT=205]="RESET_CONTENT",w[w.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",w[w.MULTI_STATUS=207]="MULTI_STATUS",w[w.ALREADY_REPORTED=208]="ALREADY_REPORTED",w[w.IM_USED=226]="IM_USED",w[w.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",w[w.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",w[w.FOUND=302]="FOUND",w[w.SEE_OTHER=303]="SEE_OTHER",w[w.NOT_MODIFIED=304]="NOT_MODIFIED",w[w.USE_PROXY=305]="USE_PROXY",w[w.SWITCH_PROXY=306]="SWITCH_PROXY",w[w.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",w[w.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",w[w.BAD_REQUEST=400]="BAD_REQUEST",w[w.UNAUTHORIZED=401]="UNAUTHORIZED",w[w.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",w[w.FORBIDDEN=403]="FORBIDDEN",w[w.NOT_FOUND=404]="NOT_FOUND",w[w.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",w[w.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",w[w.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",w[w.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",w[w.CONFLICT=409]="CONFLICT",w[w.GONE=410]="GONE",w[w.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",w[w.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",w[w.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",w[w.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",w[w.URI_TOO_LONG=414]="URI_TOO_LONG",w[w.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",w[w.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",w[w.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",w[w.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",w[w.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",w[w.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",w[w.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",w[w.LOCKED=423]="LOCKED",w[w.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",w[w.TOO_EARLY=425]="TOO_EARLY",w[w.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",w[w.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",w[w.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",w[w.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",w[w.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",w[w.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",w[w.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",w[w.BAD_GATEWAY=502]="BAD_GATEWAY",w[w.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",w[w.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",w[w.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",w[w.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",w[w.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",w[w.LOOP_DETECTED=508]="LOOP_DETECTED",w[w.NOT_EXTENDED=510]="NOT_EXTENDED",w[w.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",w))(Yt||{}),$s={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Content Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Content",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};var Wl={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"},Cn=Wl;function Kl(n){return`${new URL(n.url).pathname}`}i(Kl,"instance");function Jl(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:m.instance.build.BUILD_ID},r=n.headers.get(ct);return r&&(t.rayId=r),t}i(Jl,"trace");var Ql=i((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:Kl(e),trace:Jl(e,t),...r},additionalHeaders:o,statusText:Cn[n.status]}),"merge"),ho=class{static{i(this,"HttpProblemsBase")}static format=(e,t,r)=>"problem"in e?Je.format(e,t,r):Je.format({problem:e},t,r);static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:$s[e],...t}}},T=class extends ho{static{i(this,"HttpProblems")}static#e(e,t,r,o,s){let a=Ql(this.getProblemFromStatus(e),t,r,o,s);return Je.format(a,t,r)}static continue=(e,t,r,o)=>this.#e(200,e,t,r,o);static switchingProtocols=(e,t,r,o)=>this.#e(101,e,t,r,o);static processing=(e,t,r,o)=>this.#e(102,e,t,r,o);static earlyHints=(e,t,r,o)=>this.#e(103,e,t,r,o);static ok=(e,t,r,o)=>this.#e(200,e,t,r,o);static created=(e,t,r,o)=>this.#e(201,e,t,r,o);static accepted=(e,t,r,o)=>this.#e(202,e,t,r,o);static nonAuthoritativeInformation=(e,t,r,o)=>this.#e(203,e,t,r,o);static noContent=(e,t,r,o)=>this.#e(204,e,t,r,o);static resetContent=(e,t,r,o)=>this.#e(205,e,t,r,o);static partialContent=(e,t,r,o)=>this.#e(206,e,t,r,o);static multiStatus=(e,t,r,o)=>this.#e(207,e,t,r,o);static alreadyReported=(e,t,r,o)=>this.#e(208,e,t,r,o);static imUsed=(e,t,r,o)=>this.#e(226,e,t,r,o);static multipleChoices=(e,t,r,o)=>this.#e(300,e,t,r,o);static movedPermanently=(e,t,r,o)=>this.#e(301,e,t,r,o);static found=(e,t,r,o)=>this.#e(302,e,t,r,o);static seeOther=(e,t,r,o)=>this.#e(303,e,t,r,o);static notModified=(e,t,r,o)=>this.#e(304,e,t,r,o);static useProxy=(e,t,r,o)=>this.#e(305,e,t,r,o);static switchProxy=(e,t,r,o)=>this.#e(306,e,t,r,o);static temporaryRedirect=(e,t,r,o)=>this.#e(307,e,t,r,o);static permanentRedirect=(e,t,r,o)=>this.#e(308,e,t,r,o);static badRequest=(e,t,r,o)=>this.#e(400,e,t,r,o);static unauthorized=(e,t,r,o)=>this.#e(401,e,t,r,o);static paymentRequired=(e,t,r,o)=>this.#e(402,e,t,r,o);static forbidden=(e,t,r,o)=>this.#e(403,e,t,r,o);static notFound=(e,t,r,o)=>this.#e(404,e,t,r,o);static methodNotAllowed=(e,t,r,o)=>this.#e(405,e,t,r,o);static notAcceptable=(e,t,r,o)=>this.#e(406,e,t,r,o);static proxyAuthenticationRequired=(e,t,r,o)=>this.#e(407,e,t,r,o);static requestTimeout=(e,t,r,o)=>this.#e(408,e,t,r,o);static conflict=(e,t,r,o)=>this.#e(409,e,t,r,o);static gone=(e,t,r,o)=>this.#e(410,e,t,r,o);static lengthRequired=(e,t,r,o)=>this.#e(411,e,t,r,o);static preconditionFailed=(e,t,r,o)=>this.#e(412,e,t,r,o);static contentTooLarge=(e,t,r,o)=>this.#e(413,e,t,r,o);static uriTooLong=(e,t,r,o)=>this.#e(414,e,t,r,o);static unsupportedMediaType=(e,t,r,o)=>this.#e(415,e,t,r,o);static rangeNotSatisfiable=(e,t,r,o)=>this.#e(416,e,t,r,o);static expectationFailed=(e,t,r,o)=>this.#e(417,e,t,r,o);static imATeapot=(e,t,r,o)=>this.#e(418,e,t,r,o);static misdirectedRequest=(e,t,r,o)=>this.#e(421,e,t,r,o);static unprocessableContent=(e,t,r,o)=>this.#e(422,e,t,r,o);static locked=(e,t,r,o)=>this.#e(423,e,t,r,o);static failedDependency=(e,t,r,o)=>this.#e(424,e,t,r,o);static tooEarly=(e,t,r,o)=>this.#e(425,e,t,r,o);static upgradeRequired=(e,t,r,o)=>this.#e(426,e,t,r,o);static preconditionRequired=(e,t,r,o)=>this.#e(428,e,t,r,o);static tooManyRequests=(e,t,r,o)=>this.#e(429,e,t,r,o);static requestHeaderFieldsTooLarge=(e,t,r,o)=>this.#e(431,e,t,r,o);static unavailableForLegalReasons=(e,t,r,o)=>this.#e(451,e,t,r,o);static internalServerError=(e,t,r,o)=>this.#e(500,e,t,r,o);static notImplemented=(e,t,r,o)=>this.#e(501,e,t,r,o);static badGateway=(e,t,r,o)=>this.#e(502,e,t,r,o);static serviceUnavailable=(e,t,r,o)=>this.#e(503,e,t,r,o);static gatewayTimeout=(e,t,r,o)=>this.#e(504,e,t,r,o);static httpVersionNotSupported=(e,t,r,o)=>this.#e(505,e,t,r,o);static variantAlsoNegotiates=(e,t,r,o)=>this.#e(506,e,t,r,o);static insufficientStorage=(e,t,r,o)=>this.#e(507,e,t,r,o);static loopDetected=(e,t,r,o)=>this.#e(508,e,t,r,o);static notExtended=(e,t,r,o)=>this.#e(510,e,t,r,o);static networkAuthenticationRequired=(e,t,r,o)=>this.#e(511,e,t,r,o)};var Ye=class extends Ke{static{i(this,"MetricsPlugin")}};var te=class n{static{i(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let t=n.#e.get(e);if(!t){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new Q(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var ee=class{static{i(this,"BatchDispatch")}constructor(e,t,r,o){this.#t=e,this.#i=t,this.#r=r,this.#n=o??console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=e=>{this.#o.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{t()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var Sn=class{static{i(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=m.instance.loggingId,this.#e=e,this.#t=new ee("ellie-metrics-transport",10,this.dispatchFunction,te.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let{remoteLogURL:t,deploymentName:r}=m.instance,{ACCOUNT_NAME:o,PROJECT_NAME:s}=m.instance.build,a=e.map(d=>{let p=Object.assign({},d);return delete p.requestContentLength,delete p.responseContentLength,p}),u=Ds(),c={metadata:{timestamp:new Date,accountName:o,projectName:s,deploymentName:r},metrics:a,features:u},l=await F.fetch(`${t}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(c),headers:{"content-type":"application/json","zp-dn":m.instance.deploymentName??"unknown","user-agent":m.instance.systemUserAgent}});if(!l.ok){let d=await l.text();te.getLogger(this.#e).error(`Metrics POST responded ${l.status}: ${l.statusText}`,d),Ms(u)}}};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.version=Xt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Xt={name:"__system-no-version",pathPrefix:""};var Ie=i(async(n,e,t,r)=>{let o=new Date,s=Date.now(),a=await r(n),u=n.headers.get(ct)??void 0,c=n.headers.get(vs)??void 0,l=e.incomingRequestProperties,d;e.route instanceof pe&&(d=e.route.systemRouteName);let p=Pe.getContextExtensions(e).latestRequest,h={timestamp:o,statusCode:a.status,durationMs:Date.now()-s,requestContentLength:n.headers.get("content-length")?Number(n.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:n.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:m.instance.instanceId,userSub:p.user?.sub,clientIp:c},y=[];return y.push(new Sn(e)),$e.forEach(A=>{if(A instanceof Ye){let P=A.getTransport();y.push(P)}}),y.forEach(A=>{A.pushMetrics(h,e)}),a},"metricsProcessor");var Me=(c=>(c.Build="build-data",c.CorsPreflight="cors-preflight",c.DeveloperPortal="developer-portal",c.DeveloperPortalLegacy="developer-portal-legacy",c.StripePlugin="stripe-plugin",c.EmptyGatewayCatchall="empty-gateway-catchall",c.Ping="ping",c.UnmatchedPath="unmatched-path",c))(Me||{});var yo=i((n,e)=>{let t=i(async(s,a)=>{let c=new URL(s.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return T.notFound(s,a);let l=m.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,compatibilityDate:l.COMPATIBILITY_DATE,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=s.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&te.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new he({processors:[Ie],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{toString:Yl}=Object.prototype,{propertyIsEnumerable:Xl}=Object.prototype;function bo(n){return Yl.call(n)}i(bo,"toString");function Oe(n){return typeof n=="string"}i(Oe,"isString");function It(n){return Oe(n)&&n!==""}i(It,"isNonEmptyString");function js(n){return bo(n)==="[object RegExp]"}i(js,"isRegexp");function Bs(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>Xl.call(n,e))]}i(Bs,"getOwnEnumerableKeys");function lt(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}i(lt,"isObject");function wo(n){return typeof n=="number"&&!isNaN(n)}i(wo,"isNumber");function Ro(n){return n===!0||n===!1}i(Ro,"isBoolean");function zs(n){return typeof n>"u"}i(zs,"isUndefined");function Gs(n){return zs(n)||n===null}i(Gs,"isUndefinedOrNull");function en(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(en,"isErrorLike");var Vs=new Map;function Xe(n){if(Array.isArray(n)&&!n.some(o=>typeof o!="number"))return n;if(typeof n!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(n))throw new Error("Malformed input string");let e=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(Xe,"statusCodesStringToNumberArray");function dt(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 _(`Error applying ${t} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i(dt,"getValueFromRequestUser");function pt(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(Oe(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(pt,"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(!lt(t))throw new g(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!It(t.name))throw new g("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!wo(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&&!Ro(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=Po(t,"allowedHeaders"),o=Po(t,"allowedMethods"),s=Po(t,"exposeHeaders"),a;try{a=pt(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 Po(n,e){let t;if(n[e]!==void 0)try{t=pt(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(Po,"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"),_n=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 Io=i((n,e)=>{let t=e.routeData.corsPolicies,r=i(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return T.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let h=n.lookup(l,c);if(!h)return T.notFound(a,u);let y=h.routeConfiguration,A=ed(l,d,p,y,t);return A.isValid?new Response(void 0,{status:200,statusText:"OK",headers:A.headers}):(A.error&&u.log.warn(A.error),T.notFound(a,u))},"optionsHandler"),o=new he({processors:[Ie],handler:r,gateway:e}),s=new pe({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(s,o.execute)},"registerCorsRoute"),ed=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:_n(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var Ks=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:[Ie],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 Eo=new pe({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Js=i((n,e)=>{let t=i(async(o,s)=>{let a=Qt.value?.notFoundHandler;if(a){let u=Pe.getContextExtensions(s);return a(o,s,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return T.notFound(o,s)},"notFoundHandler"),r=new he({processors:[Ie],handler:t,gateway:e});n.addRoute(Eo,r.execute)},"registerNotMatchedHandler");var td=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Qs=i(n=>{td.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 Q(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=nd(o,t.routeData.corsPolicies),u=rd(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"),nd=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"),rd=i((n,e)=>{let t=An(e.allowedOrigins,n.headers.get("origin"));return t?_n(e,t):{}},"getCorsHeaders");var To=i((n,e)=>{let t=i(async()=>new Response(JSON.stringify({buildId:m.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");var Et=require("@opentelemetry/api");var Le={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var kn=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!Oe(t))throw new _(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},le=class extends kn{static{i(this,"InboundPolicy")}},je=class extends kn{static{i(this,"OutboundPolicy")}};var vo=class extends le{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)}},Co=class extends je{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)}},xo=new Map;function tn(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(s=>!xo.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 le)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new vo(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}')`);xo.set(a.name,c)}),t.map(s=>{let a=xo.get(s);if(a===void 0)throw new _("Internal error. Policy not found in cache.");return a})}i(tn,"getInboundPolicyInstances");var Oo=new Map;function od(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!Oo.has(o)).forEach(o=>{let s=e?.find(c=>c.name===o);if(!s)throw new g(`Invalid state - no Policy with the name '${o}' on route '${n.path}' was found in the policies configuration (check case).`);if(typeof s.handler?.module!="object")throw new g(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof s.handler?.module}')`);let a=s.handler?.module[s.handler.export],u;if(typeof a!="function")throw new g(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof je)u=new a(s.handler.options??{},s.name);else if(typeof a=="function")u=new Co(a,s.handler.options??{},s.name);else throw new g(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new g(`Invalid state - invalid handler on policy '${o}' on route '${n.path}'`);Oo.set(s.name,u)}),t.map(o=>{let s=Oo.get(o);if(s===void 0)throw new _("Internal error. Policy not found in cache.");return s})}i(od,"getOutboundPolicyInstances");var So=i(n=>async(e,t)=>{let r=Pe.getContextExtensions(t),o=Et.trace.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;let l=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{let p=await c.handler(u,t);if(p instanceof Request||p instanceof oe||p instanceof Response)return d.end(),p;{let h=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:Et.SpanStatusCode.ERROR}),d.recordException(h),h}});if(l instanceof oe)u=l;else if(l instanceof Request)u=new oe(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),id=i(n=>async(e,t,r)=>{let o=Et.trace.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(Le.PolicyName,c.policyName),d.setAttribute(Le.PolicyType,c.policyType);let p=await c.handler(u,t,r);if(p instanceof Response)return p;{let h=new 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:Et.SpanStatusCode.ERROR}),d.recordException(h),h}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),Nn=i(async(n,e,t,r)=>{let o=tn(e.route,t.routeData.policies),s=od(e.route,t.routeData.policies);return Xs({request:n,context:e,inboundPolicies:o,outboundPolicies:s,gateway:t,next:r})},"policyProcessor");function Ys({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>Xs({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(Ys,"createInternalPolicyProcessor");async function Xs({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:s}){let a=So(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await s(u),l=id(r),d;return m.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,n,e):d=c.ok?l(c,n,e):c,d}catch(u){return e.log.error(u),o.errorHandler(n,e,u)}}i(Xs,"executePolicyProcessor");function ea(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||sd,s=0;for(;s<n.length;){let a=n.indexOf("=",s);if(a===-1)break;let u=n.indexOf(";",s);if(u===-1)u=n.length;else if(u<a){s=n.lastIndexOf(";",a-1)+1;continue}let c=n.slice(s,a).trim();if(t[c]===void 0){let l=n.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),t[c]=ad(l,o)}s=u+1}return t}i(ea,"parse");function sd(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}i(sd,"decode");function ad(n,e){try{return e(n)}catch{return n}}i(ad,"tryDecode");function ta(n,e){try{let t=/v\d+(-\d+)?/g,o=ea(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}i(ta,"devPortalBaseURL");var na="/__zuplo/dev-portal",ud="dev-portal-id",cd="dev-portal-host",ld="zp-account",dd="zp-project",pd="dev-portal-build",md=`
36
36
  <!DOCTYPE html>
37
37
  <html lang="en">
38
38
  <head>
@@ -46,20 +46,20 @@
46
46
  <p>For more information, see <a href="https://zuplo.com/docs/articles/developer-portal">https://zuplo.com/docs/articles/developer-portal</a>.</p>
47
47
  </body>
48
48
  </html>
49
- `,ra=i((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=m.instance.deploymentName,o=m.instance.devPortalBaseUrl,s=i(async(c,l)=>{if(m.instance.isLocalDevelopment)return new Response(gd,{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=ta(o,c.headers),h=new URL(`${d.pathname}${d.search}`,p),{headers:y,method:_,body:P}=c;return m.instance.build.ACCOUNT_NAME&&y.set(dd,m.instance.build.ACCOUNT_NAME),m.instance.build.PROJECT_NAME&&y.set(pd,m.instance.build.PROJECT_NAME),y.set(cd,r),y.set(ld,d.host),y.set(md,m.instance.build.BUILD_ID),await F.fetch(h.toString(),{headers:y,method:_,body:P,redirect:"manual"})},"devPortalRoute"),a=new fe({processors:[Ie,kn],handler:s,gateway:e}),u=new le({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"),oa=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(na.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new fe({processors:[Ie],handler:r,gateway:e}),s=new le({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${na}(.*)`,systemRouteName:"developer-portal-legacy"});n.addRoute(s,o.execute)},"registerDevPortalLegacyRedirectRoute");var ga=Be(qe());var ko=0,Qt=class{static{i(this,"CoreLogger")}constructor(e,t,r,o,s){this.#n=t,this.#r=r??"local",this.#o=o,this.#i=s,this.#e(e)}#e=e=>{let t=["error","warn","info","debug"],r=!1,o=i(()=>{},"emptyFunction"),s=i((a,u)=>{this.#i.forEach(c=>{c.log(a,u)})},"pushFunction");t.forEach(a=>{this.#t[a]=r?o:s,a==e&&(r=!0)})};#t={};#n;#r;#o;#i;log(e,t,r,o,s,a){ko>=Number.MAX_SAFE_INTEGER&&(ko=0);let u={requestId:r,rayId:o,level:e,logSource:t,messages:s,timestamp:new Date,logOwner:this.#n,loggingId:this.#r,buildId:this.#o,vectorClock:ko++};this.#t[e](u,a)}};var ye=class extends Ke{static{i(this,"LogPlugin")}};var Nn=class{static{i(this,"LoggingContext")}constructor(e,t,r){this.#e=e,this.custom=t,this.originalRequest=r}#e;custom;originalRequest;waitUntil=e=>{this.#e.waitUntil(e)}};var en=class{static{i(this,"RequestLogger")}constructor(e,t,r,o){this.#t=e,this.#n=t,this.#r=r,this.#o=o}#e="request";#t;#n;#r;#o;debug=(...e)=>{this.#r.log("debug",this.#e,this.#t,this.#n,e,this.#o)};info=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};log=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};warn=(...e)=>{this.#r.log("warn",this.#e,this.#t,this.#n,e,this.#o)};error=(...e)=>{this.#r.log("error",this.#e,this.#t,this.#n,e,this.#o)}};var fd=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(n=>[n.name,n]),hd=new Map(fd);var yd=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],No=Symbol(".toJSON was called"),bd=i(n=>{n[No]=!0;let e=n.toJSON();return delete n[No],e},"toJSON"),wd=i(n=>hd.get(n)??Error,"getErrorConstructor"),ia=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&&Yt(n)){let l=wd(n.name);t=new l}else t={};if(e.push(n),s>=o)return t;if(a&&typeof n.toJSON=="function"&&n[No]!==!0)return bd(n);let c=i(l=>ia({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 yd)typeof n[l]<"u"&&n[l]!==null&&Object.defineProperty(t,l,{value:Yt(n[l])?c(n[l]):n[l],enumerable:r?!0:d,configurable:!0,writable:!0});return t},"destroyCircular");function Te(n,e){let t=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof n=="object"&&n!==null?ia({from:n,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:r,serialize:!0}):typeof n=="function"?`[Function: ${n.name??"anonymous"}]`:n}i(Te,"serializeError");var Rd=/file:\/\/\/(.*?)\/dist\//g,Pd="at async Event.respondWith";function sa(n){return typeof n!="string"?n:n.split(`
50
- `).filter(e=>!e.trim().startsWith("at async file")).map((e,t)=>{let r=e.replaceAll(Rd,"").replaceAll(Pd,"").trim();return t===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
49
+ `,ra=i((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=m.instance.deploymentName,o=m.instance.devPortalBaseUrl,s=i(async(c,l)=>{if(m.instance.isLocalDevelopment)return new Response(md,{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=ta(o,c.headers),h=new URL(`${d.pathname}${d.search}`,p),{headers:y,method:A,body:P}=c;return m.instance.build.ACCOUNT_NAME&&y.set(ld,m.instance.build.ACCOUNT_NAME),m.instance.build.PROJECT_NAME&&y.set(dd,m.instance.build.PROJECT_NAME),y.set(ud,r),y.set(cd,d.host),y.set(pd,m.instance.build.BUILD_ID),await F.fetch(h.toString(),{headers:y,method:A,body:P,redirect:"manual"})},"devPortalRoute"),a=new he({processors:[Ie,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"),oa=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(na.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new he({processors:[Ie],handler:r,gateway:e}),s=new pe({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${na}(.*)`,systemRouteName:"developer-portal-legacy"});n.addRoute(s,o.execute)},"registerDevPortalLegacyRedirectRoute");var ga=ze(He());var Ao=0,nn=class{static{i(this,"CoreLogger")}constructor(e,t,r,o,s){this.#n=t,this.#r=r??"local",this.#o=o,this.#i=s,this.#e(e)}#e=e=>{let t=["error","warn","info","debug"],r=!1,o=i(()=>{},"emptyFunction"),s=i((a,u)=>{this.#i.forEach(c=>{c.log(a,u)})},"pushFunction");t.forEach(a=>{this.#t[a]=r?o:s,a==e&&(r=!0)})};#t={};#n;#r;#o;#i;log(e,t,r,o,s,a){Ao>=Number.MAX_SAFE_INTEGER&&(Ao=0);let u={requestId:r,rayId:o,level:e,logSource:t,messages:s,timestamp:new Date,logOwner:this.#n,loggingId:this.#r,buildId:this.#o,vectorClock:Ao++};this.#t[e](u,a)}};var ye=class extends Ke{static{i(this,"LogPlugin")}};var Dn=class{static{i(this,"LoggingContext")}constructor(e,t,r){this.#e=e,this.custom=t,this.originalRequest=r}#e;custom;originalRequest;waitUntil=e=>{this.#e.waitUntil(e)}};var rn=class{static{i(this,"RequestLogger")}constructor(e,t,r,o){this.#t=e,this.#n=t,this.#r=r,this.#o=o}#e="request";#t;#n;#r;#o;debug=(...e)=>{this.#r.log("debug",this.#e,this.#t,this.#n,e,this.#o)};info=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};log=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};warn=(...e)=>{this.#r.log("warn",this.#e,this.#t,this.#n,e,this.#o)};error=(...e)=>{this.#r.log("error",this.#e,this.#t,this.#n,e,this.#o)}};var gd=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(n=>[n.name,n]),fd=new Map(gd);var hd=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],_o=Symbol(".toJSON was called"),yd=i(n=>{n[_o]=!0;let e=n.toJSON();return delete n[_o],e},"toJSON"),bd=i(n=>fd.get(n)??Error,"getErrorConstructor"),ia=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&&en(n)){let l=bd(n.name);t=new l}else t={};if(e.push(n),s>=o)return t;if(a&&typeof n.toJSON=="function"&&n[_o]!==!0)return yd(n);let c=i(l=>ia({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 hd)typeof n[l]<"u"&&n[l]!==null&&Object.defineProperty(t,l,{value:en(n[l])?c(n[l]):n[l],enumerable:r?!0:d,configurable:!0,writable:!0});return t},"destroyCircular");function Te(n,e){let t=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof n=="object"&&n!==null?ia({from:n,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:r,serialize:!0}):typeof n=="function"?`[Function: ${n.name??"anonymous"}]`:n}i(Te,"serializeError");var wd=/file:\/\/\/(.*?)\/dist\//g,Rd="at async Event.respondWith";function sa(n){return typeof n!="string"?n:n.split(`
50
+ `).filter(e=>!e.trim().startsWith("at async file")).map((e,t)=>{let r=e.replaceAll(wd,"").replaceAll(Rd,"").trim();return t===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
51
51
  `)}i(sa,"cleanStack");function Mn(n,e,t=""){let r=[],o=e?.maxDepth??3;return i(function s(a,u={},c,l){let d=u.indent||" ",p;u.inlineCharacterLimit===void 0?p={newline:`
52
52
  `,newlineOrSpace:`
53
- `,pad:c,indent:c+d}:p={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let h=i(y=>{if(u.inlineCharacterLimit===void 0)return y;let _=y.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return _.length<=u.inlineCharacterLimit?_:y.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
54
- `).replace(new RegExp(p.pad,"g"),c).replace(new RegExp(p.indent,"g"),c+d)},"expandWhiteSpace");if(r.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||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 y="["+p.newline+a.map((_,P)=>{let C=a.length-1===P?p.newline:","+p.newlineOrSpace,H=s(_,u,c+d,l+1);return u.transform&&(H=u.transform(a,P,H)),p.indent+H+C}).join("")+p.pad+"]";return r.pop(),h(y)}if(at(a)){let y=zs(a);if(u.filter&&(y=y.filter(P=>u.filter?.(a,P))),y.length===0)return"{}";r.push(a);let _="{"+p.newline+y.map((P,C)=>{let H=y.length-1===C?p.newline:","+p.newlineOrSpace,N=typeof P=="symbol",z=!N&&/^[a-z$_][$\w]*$/i.test(P),q=N||z?P:s(P,u,"",l+1),j=s(a[P],u,c+d,l+1);return u.transform&&(j=u.transform(a,P,j)),p.indent+String(q)+": "+j+H}).join("")+p.pad+"}";return r.pop(),h(_)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,y=>y===`
55
- `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}i(Mn,"stringifyObject");function Qe(n){return n.map(e=>Te(e))}i(Qe,"makeErrorsSerializable");function Pt(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:ze(Te(e))}i(Pt,"extractBestMessage");function aa(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(Yt(t))if(t.stack)e.push(t.stack);else{let r=Mn(Te(t));e.push(r)}else if(typeof t=="object"){let r=Mn(t);e.push(r)}else{let r=Mo(t);e.push(r)}}),e.join(`
56
- `)}i(aa,"messagesToMultilineText");function ze(n){return typeof n=="string"?n:JSON.stringify(n)}i(ze,"stringifyNonString");function Mo(n){return typeof n=="string"?n:n===null?"null":typeof n>"u"?"undefined":typeof n=="number"||typeof n=="boolean"||typeof n=="bigint"||typeof n=="symbol"?n.toString():typeof n=="function"?`[function ${n.name}]`:typeof n=="object"&&Array.isArray(n)?`[array ${n.length}]`:n instanceof Error?`${n.name??"Error"}: ${n.message??"unknown"}`:typeof n=="object"?Po(n):"unknown"}i(Mo,"stringifyNonStringToText");var Dn=require("jose");async function be(n,e,t){for(let r=0;r<=n.retries;r++){let o=F.fetch(e,t);if(r===n.retries)return o;let s=await o;if(s.status<500&&s.status!==429)return s;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,r)))}throw new g("An unknown error occurred, ensure retries is not negative")}i(be,"fetchRetry");async function Ue({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=n;return await new Dn.SignJWT(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(Ue,"getTokenFromGcpServiceAccount");async function ua(n,e,t){if(!n.startsWith("projects/"))throw new g(`The provided audience is invalid: ${n}. It must start with 'projects/'.`);return Do("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(ua,"exchangeIDTokenForGcpWorkloadToken");async function ca({serviceAccountEmailOrIdentifier:n,audience:e,accessToken:t},r){let o={audience:e,includeEmail:!0};return da(`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(ca,"generateServiceAccountIDToken");async function la(n,e,t){return Do(n,{token:e,returnSecureToken:!0},t)}i(la,"exchangeFirebaseJwtForIdToken");async function Un(n,e,t){return Do(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(Un,"exchangeGgpJwtForIdToken");async function Do(n,e,t){let r={method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)};return da(n,r,t)}i(Do,"fetchTokenFromBody");async function da(n,e,t){let r=await be(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 A({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(da,"fetchToken");var Oe=class n{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),r=await(0,Dn.importPKCS8)(t.private_key.trim(),"RS256");return new n({serviceAccount:t,privateKey:r})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};async function pe(n){if(n.level==="error"&&console.error(n.messages),!m.instance.remoteLogURL||!m.instance.loggingId||!m.instance.remoteLogToken){console.warn("Remote logger is not configured. Skipping log entry.");return}try{let e={logOwner:"user",logSource:"runtime",rayId:null,requestId:`global-${crypto.randomUUID()}`,timestamp:new Date,buildId:m.instance.build.BUILD_ID,loggingId:m.instance.loggingId,...n,vectorClock:0};await pa({loggingUrl:m.instance.remoteLogURL,loggingId:m.instance.loggingId,loggingToken:m.instance.remoteLogToken},[e])}catch(e){console.error(e)}}i(pe,"sendRemoteGlobalLog");async function pa({loggingUrl:n,loggingId:e,loggingToken:t},r){try{await F.fetch(`${n}/publish/${e}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:r.map(o=>({...o,messages:Qe(o.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${t}`,"user-agent":m.instance.systemUserAgent,"zp-dn":m.instance.deploymentName??"unknown"}})}catch(o){console.error(o)}}i(pa,"sendRemoteLogs");var Id=i(({url:n,remoteLogToken:e,loggingId:t,sendOnlyErrors:r})=>async o=>{let s;r===!0?s=o.filter(a=>a.level==="error"):s=o,s.length!==0&&await pa({loggingUrl:n,loggingId:t,loggingToken:e},s)},"dispatchFunction"),Hn,Zn=class{static{i(this,"RemoteLogTransport")}constructor(e){Hn||(Hn=new Q("remote-log-transport",1,Id(e)))}log(e,t){Hn.enqueue(e),t.waitUntil(Hn.waitUntilFlushed())}};var qn=class extends ye{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new tn(this.options)}},Ed="https://logging.googleapis.com/v2/entries:write?alt=json",Uo={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},tn=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=m.instance.loggingEnvironmentType,this.#i=m.instance.loggingEnvironmentStage,this.#r=m.instance.deploymentName,f("logging.google-cloud")}#e;#t;#n;#r;#o;#i;async init(){this.#t=await Oe.init(this.#e)}log(e,t){if(!this.#t)throw new Y("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:Qe(e.messages)},o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:Uo[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=Pt(r.allMessages);s.jsonPayload={...r,message:a},this.batcher.enqueue(s),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await Oe.init(this.#e));let t=await Ue({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"});try{let r=await F.fetch(Ed,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});if(!r.ok){let o="";try{o=await r.text()}catch{}await pe({level:"error",messages:[`Failed to send logs to Google: ${r.status} - ${r.statusText}`,o]})}}catch{await pe({level:"error",messages:["Failed to connect to Google logging service. Check that the URL is correct."]})}};batcher=new Q("google-log-transport",1,this.dispatchFunction)};var Fn="gcp";function $n(n){let e={allMessages:Qe(n.messages)},t="zuplo-production",r=Pt(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:Uo[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 nn=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===Fn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[$n(e)])}else this.#e.log(JSON.stringify(e))}};var jn=class extends ye{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new rn(this.options)}},Ho="__ddtags",Zo="__ddattr",qo=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),Td=i(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(qo(r)):t.push(`${qo(r)}:${qo(o.toString())}`)}),t.join(",")},"formatTags"),rn=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=m.instance.loggingEnvironmentType,this.#o=m.instance.loggingEnvironmentStage,this.#n=m.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[Ho];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(y=>y[Ho]!==void 0);a>-1&&(Object.assign(r,s[a][Ho]),s.splice(a,1));let u={},c=t.custom[Zo];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(y=>y[Zo]!==void 0);l>-1&&(Object.assign(u,s[l][Zo]),s.splice(l,1));let d=Qe(s),h={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:Pt(d),service:e.loggingId,ddtags:Td(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(h,u),this.batcher.enqueue(h),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length!==0)try{let t=await F.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!t.ok){let r="";try{r=await t.text()}catch{}await pe({level:"error",messages:[`Failed to send logs to DataDog: ${t.status} - ${t.statusText}`,r]})}}catch{await pe({level:"error",messages:["Failed to connect to DataDog logging service. Check that the URL is correct."]})}};batcher=new Q("data-dog-transport",10,this.dispatchFunction)};var on=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===Fn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[$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 xd={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},ma=i((n,e)=>t=>{let r={};return r.deploymentName=n,r.labels={requestId:t.requestId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},r.rayId=t.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=t.vectorClock,{timestamp:t.timestamp,observerdTimestamp:t.timestamp,traceId:t.requestId,severityText:t.level,severityNumber:xd[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var vd=i(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let s=ma(t,r);try{await F.fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":m.instance.systemUserAgent,"zp-dn":m.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),zn,Bn=class{static{i(this,"UnifiedLogTransport")}constructor(e){zn||(zn=new Q("unified-log-transport",1,vd(e)))}async log(e,t){zn.enqueue(e),t.waitUntil(zn.waitUntilFlushed())}};var Fo=(0,ga.debug)("zuplo:logging"),Gn=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(m.instance,e),r=await n.setupUserCoreLogger(m.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;Fo("Gateway.setupSystemCoreLogger");let o=[],s=t.getService(Gt);return s?o.push(new on(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new nn(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Bn({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new Qt(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){Fo("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=t.getService(Gt);if(a&&a.captureUserLogs===!0?r.push(new on(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new nn(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new Zn({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:!e.isWorkingCopy})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&(f("logging.google.legacy-initialization"),r.push(new tn({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 rn({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return $e.forEach(u=>{u instanceof ye&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new Qt(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,t,r,o,s){Fo("Gateway.createRequestLoggers");let a=new Nn(r,o,s),u=new en(e,t,this.systemCoreLogger,a);return{userRequestLogger:new en(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var lt=class{static{i(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};var $o=class{static{i(this,"RouterEntry")}constructor(e,t,r,o){this.fullPath=e,this.urlPattern=t,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},It=class{static{i(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},jo=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}},Et=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof lt||e instanceof le))throw new Y("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(s=>s.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let s=new URLPattern({pathname:o}),a=new $o(o,s,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new jo(`addRoute-error: Invalid path '${o}'. '${s.message}'`,{cause:s})}}lookup(e,t){if(typeof e>"u")throw new g(`Invalid request - Method was undefined. Path: '${t}'`);let r=this.routeEntries.filter(o=>o.config.methods.includes(e));if(r.length!==0)for(let o=0;o<r.length;o++){let s=r[o],u=s.urlPattern.exec({pathname:t});if(u!==null)return new It(s.config,s.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],a=o.urlPattern.exec({pathname:e});if(a!==null){let u=new It(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var zo;function fa(n){zo=n}i(fa,"setGlobalZuploEventContext");function Vn(){if(zo===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return zo}i(Vn,"getGlobalZuploEventContext");function ha({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);Ss.includes(o.toLowerCase())&&!As.includes(r.toLowerCase())&&t.delete(r)}t.delete(hs)}else Cs.forEach(r=>{t.delete(r)});return t}i(ha,"normalizeIncomingRequestHeaders");var He=(0,ba.debug)("zuplo:runtime"),Od=i(n=>{let e=n.findIndex(t=>t.name===Jt.name);return e>-1?[...n.splice(e),Jt]:[...n,Jt]},"setupSystemNoVersion"),Re=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;He("Gateway.constructor"),Le,this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(He("Gateway.initialize"),!n.#e){let s=await Gn.init(r),a=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(){He("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=[kn,_n,Ie];#o;setupRoutes=()=>{He("Gateway.setupRoutes");let e=this.routeData,t=Od(e.versions),r=new Et(t);if(e.routes.length===0)return Ro(r,this),Oo(r,this),xo(r,this),Ks(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(oa(r,this),ra(r,this)),Ro(r,this),Oo(r,this),xo(r,this);for(let s of $e)s instanceof Fe&&s.registerRoutes(r,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new g(`Invalid state - No handler on route for path '${s.path}'`);let u=new fe({processors:this.#r,handler:a,gateway:this}),c=new lt(s);r.addRoute(c,u.execute)}),Js(r,this),r};setupErrorHandler=()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new g("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=i((t,r,o)=>this.#i(t,r,o),"errorHandler");return e};errorHandler(e,t,r){try{return this.#o(e,t,r)}catch(o){return He("An error occurred in the user's errorHandler",o),this.#i(e,t,o)}}#i(e,t,r){He("Gateway.internalErrorResponse");let o={};if(m.instance.isLocalDevelopment||m.instance.isWorkingCopy){if(r instanceof A&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let s=Te(r.cause);"stack"in s&&(s.stack=sa(s.stack)),o={cause:s}}}return T.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t,r){let{requestId:o,rayId:s}=t;fa(r);let a=ha({headers:e.headers,removeAllVendorHeadersExceptListed:m.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(it,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let z=new Headers(u.headers);z.set(to,"true"),u=new Request(u,{headers:z,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(o,s,r,c,u),p=new URL(u.url),h=p.pathname,y=this.#n.lookup(u.method,h);if(!y)throw new Y(`Invalid state - no route match - should have been picked up by the not found handler, path: '${h}'`);let _=new Wn(e.headers),P=new oe(u,{params:y.params}),C=new Kn({logger:l,route:y.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:_}),H=y.routeConfiguration.raw();ya.trace.getActiveSpan()?.setAttributes({"http.route":C.route.path??C.route.pathPattern,"cloud.region":C.incomingRequestProperties.colo,[Le.RoutePathPattern]:C.route.pathPattern,[Le.RouteOperationId]:H.operationId,[Le.RouteTrace]:H["x-zuplo-trace"],[Le.RouteSystem]:ft(p)?!0:void 0});let N=Pe.initialize(C,P);if(y.routeConfiguration===vo&&Wt.value?.notFoundHandler!==void 0){let z=this.#n.lookupByPathOnly(h);N.pathOnlyMatches=z.map(q=>q.routeConfiguration).filter(q=>q instanceof lt)}try{if(te.addLogger(C,d),m.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!ft(p):!p.pathname.startsWith("/__zuplo")){let E=await Hs(P,C);if(E instanceof Response)return E;{let U=Pe.getContextExtensions(C);P=E,U.latestRequest=P}}ft(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:y.routeConfiguration.path});let z=y.executableHandler;Cd(z,y,u),He("Gateway.handleRequest - call user handler");let q=await z(P,C);if(He("Gateway.handleRequest - user handler"),!(q instanceof Response))throw new A(`Invalid Response type from the request handler: ${typeof q}`);if(q.bodyUsed)throw new A("The response object has already been used. Return a new response instead.");let j;if(q.headers.get(it)===null&&!q.webSocket){let E=new Headers(q.headers);E.set(it,o),j=new Response(q.body,{status:q.status,statusText:q.statusText,headers:E,cf:q.cf})}else j=q;return j}catch(z){return He("Gateway - error executing handler",z),z instanceof A?(l.error(z),d.warn(z)):d.error(z),await this.#i(P,C,z)}}};function Cd(n,e,t){if(He("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(Cd,"checkHandler");var wa=i(async(n,e,t)=>{let r=Re.instance.routeData.policies,o=Xt([n],r);if(o.length===0)throw new A(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy");var Wn=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(ao);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(uo)??void 0}get city(){return this.#e.get(no)??this.#e.get(Is)??void 0}get continent(){return this.#e.get(ro)??this.#e.get(Es)??void 0}get country(){return this.#e.get(oo)??this.#e.get(Ts)??void 0}get latitude(){return this.#e.get(so)??this.#e.get(vs)??void 0}get longitude(){return this.#e.get(io)??this.#e.get(xs)??void 0}get colo(){return this.#e.get(co)??void 0}get postalCode(){return this.#e.get(Rs)??this.#e.get(lo)??void 0}get metroCode(){return this.#e.get(ws)??this.#e.get(po)??void 0}get region(){return this.#e.get(ys)??this.#e.get(mo)??void 0}get regionCode(){return this.#e.get(bs)??this.#e.get(go)??void 0}get timezone(){return this.#e.get(Ps)??this.#e.get(fo)??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}}},ht=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},yt=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},Pe=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 A(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)};onResponseSending=async(e,t,r)=>{let o=e;for(let s of this.#n)o=await s(e,t,r);return o}},Kn=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=s,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>wa(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{Pe.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{Pe.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=i(s=>{try{typeof t=="function"?t(s):t.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var he=class n{static{i(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,t){n.set(e,this.#t,t)}get(e){return n.get(e,this.#t)}static set(e,t,r){n.#e||(n.#e=new WeakMap);let o=n.#e.get(e);o||(o=new Map),o.set(t,r),n.#e.set(e,o)}static get(e,t){return n.#e||(n.#e=new WeakMap),n.#e.get(e)?.get(t)}};var Sd=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function Ad(n){return n.startsWith("__ZUPLO")||n.startsWith("ZUPLO_")?!Sd.includes(n)&&!n.startsWith("ZUPLO_PUBLIC_"):!1}i(Ad,"isRestrictedEnvVariableName");function _d(n){return!!n.startsWith("ZUPLO_")}i(_d,"isZuploReadableEnvVariableName");var Ee=new Proxy({},{get(n,e){let t=String(e);switch(t){case"ZUPLO_ENVIRONMENT_TYPE":return m.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return m.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return m.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return m.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return m.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return m.instance.build.BUILD_ID}if(!(Ad(t)&&!_d(t)))return m.instance.runtime[t]}});var Ra=require("node:async_hooks");var Pa={request:new Ra.AsyncLocalStorage};var Ld="Error initializing gateway. Check your configuration for errors or contact support.",kd="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",Jn=class{constructor(e,t,r,o,s,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=async(e,t,r)=>{let o=e.headers.get(it)??e.headers.get(fs)??crypto.randomUUID(),s=e.headers.get(st),a={requestId:o,rayId:s};return Pa.request.run(a,async()=>{m.initialize({build:this.buildEnvironment,runtime:t});try{await Fs(this.runtimeInit)}catch(c){this.handleError(c,kd,e)}return ks(i(async(c,l)=>{let d;try{d=await Re.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,Ld,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,r)})};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:m.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};var Aa=Be(qe());function Nd(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(Nd,"lexer");function Bo(n,e){e===void 0&&(e={});for(var t=Nd(n),r=e.prefixes,o=r===void 0?"./":r,s="[^".concat(Dd(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=i(function(E){if(c<t.length&&t[c].type===E)return t[c++].value},"tryConsume"),p=i(function(E){var U=d(E);if(U!==void 0)return U;var V=t[c],W=V.type,O=V.index;throw new TypeError("Unexpected ".concat(W," at ").concat(O,", expected ").concat(E))},"mustConsume"),h=i(function(){for(var E="",U;U=d("CHAR")||d("ESCAPED_CHAR");)E+=U;return E},"consumeText");c<t.length;){var y=d("CHAR"),_=d("NAME"),P=d("PATTERN");if(_||P){var C=y||"";o.indexOf(C)===-1&&(l+=C,C=""),l&&(a.push(l),l=""),a.push({name:_||u++,prefix:C,suffix:"",pattern:P||s,modifier:d("MODIFIER")||""});continue}var H=y||d("ESCAPED_CHAR");if(H){l+=H;continue}l&&(a.push(l),l="");var N=d("OPEN");if(N){var C=h(),z=d("NAME")||"",q=d("PATTERN")||"",j=h();p("CLOSE"),a.push({name:z||(q?u++:""),pattern:z&&!q?s:q,prefix:C,suffix:j,modifier:d("MODIFIER")||""});continue}p("END")}return a}i(Bo,"parse");function Ia(n,e){return Md(Bo(n,e),e)}i(Ia,"compile");function Md(n,e){e===void 0&&(e={});var t=Ud(e),r=e.encode,o=r===void 0?function(c){return c}:r,s=e.validate,a=s===void 0?!0:s,u=n.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var h=c?c[p.name]:void 0,y=p.modifier==="?"||p.modifier==="*",_=p.modifier==="*"||p.modifier==="+";if(Array.isArray(h)){if(!_)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(h.length===0){if(y)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var P=0;P<h.length;P++){var C=o(h[P],p);if(a&&!u[d].test(C))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(C,'"'));l+=p.prefix+C+p.suffix}continue}if(typeof h=="string"||typeof h=="number"){var C=o(String(h),p);if(a&&!u[d].test(C))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(C,'"'));l+=p.prefix+C+p.suffix;continue}if(!y){var H=_?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(H))}}return l}}i(Md,"tokensToFunction");function Dd(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(Dd,"escapeString");function Ud(n){return n&&n.sensitive?"":"i"}i(Ud,"flags");var va=Be(qe());var Hd=(0,va.debug)("zuplo:runtime"),Vo=new TextEncoder,Ea={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"},Zd=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],Tt=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 Wo(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){Hd("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,t),a=F.fetch(o,s);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new g("An unknown error occurred, ensure retries is not negative")}},Wo=class{static{i(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:r,body:o,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:h,appendSessionToken:y,allHeaders:_,singleEncode:P}){if(t==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let C,H;(!c||!l)&&([C,H]=qd(this.url,this.headers)),this.service=c||C||"",this.region=l||H||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=h,this.appendSessionToken=y||this.service==="iotdevicegateway",this.headers.delete("Host");let N=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),N.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&N.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(q=>_||!Zd.includes(q)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(q=>q+":"+(q==="host"?this.url.host:(this.headers.get(q)||"").replace(/\s+/g," "))).join(`
57
- `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!N.has("X-Amz-Expires")&&N.set("X-Amz-Expires","86400"),N.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),N.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),N.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");P||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=xa(this.encodedPath);let z=new Set;this.encodedSearch=[...this.url.searchParams].filter(([q])=>{if(!q)return!1;if(this.service==="s3"){if(z.has(q))return!1;z.add(q)}return!0}).map(q=>q.map(j=>xa(encodeURIComponent(j)))).sort(([q,j],[E,U])=>q<E?-1:q>E?1:j<U?-1:j>U?1:0).map(q=>q.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),t=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(t);if(!r){let o=await sn("AWS4"+this.secretAccessKey,e),s=await sn(o,this.region),a=await sn(s,this.service);r=await sn(a,"aws4_request"),this.cache.set(t,r)}return Go(await sn(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Go(await Ta(await this.canonicalString()))].join(`
53
+ `,pad:c,indent:c+d}:p={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let h=i(y=>{if(u.inlineCharacterLimit===void 0)return y;let A=y.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return A.length<=u.inlineCharacterLimit?A:y.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
54
+ `).replace(new RegExp(p.pad,"g"),c).replace(new RegExp(p.indent,"g"),c+d)},"expandWhiteSpace");if(r.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||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 y="["+p.newline+a.map((A,P)=>{let O=a.length-1===P?p.newline:","+p.newlineOrSpace,D=s(A,u,c+d,l+1);return u.transform&&(D=u.transform(a,P,D)),p.indent+D+O}).join("")+p.pad+"]";return r.pop(),h(y)}if(lt(a)){let y=Bs(a);if(u.filter&&(y=y.filter(P=>u.filter?.(a,P))),y.length===0)return"{}";r.push(a);let A="{"+p.newline+y.map((P,O)=>{let D=y.length-1===O?p.newline:","+p.newlineOrSpace,k=typeof P=="symbol",B=!k&&/^[a-z$_][$\w]*$/i.test(P),q=k||B?P:s(P,u,"",l+1),j=s(a[P],u,c+d,l+1);return u.transform&&(j=u.transform(a,P,j)),p.indent+String(q)+": "+j+D}).join("")+p.pad+"}";return r.pop(),h(A)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,y=>y===`
55
+ `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}i(Mn,"stringifyObject");function et(n){return n.map(e=>Te(e))}i(et,"makeErrorsSerializable");function Tt(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:Be(Te(e))}i(Tt,"extractBestMessage");function aa(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(en(t))if(t.stack)e.push(t.stack);else{let r=Mn(Te(t));e.push(r)}else if(typeof t=="object"){let r=Mn(t);e.push(r)}else{let r=Lo(t);e.push(r)}}),e.join(`
56
+ `)}i(aa,"messagesToMultilineText");function Be(n){return typeof n=="string"?n:JSON.stringify(n)}i(Be,"stringifyNonString");function Lo(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"?bo(n):"unknown"}i(Lo,"stringifyNonStringToText");var Un=require("jose");async function be(n,e,t){for(let r=0;r<=n.retries;r++){let o=F.fetch(e,t);if(r===n.retries)return o;let s=await o;if(s.status<500&&s.status!==429)return s;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,r)))}throw new g("An unknown error occurred, ensure retries is not negative")}i(be,"fetchRetry");async function Ue({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=n;return await new Un.SignJWT(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(Ue,"getTokenFromGcpServiceAccount");async function ua(n,e,t){if(!n.startsWith("projects/"))throw new g(`The provided audience is invalid: ${n}. It must start with 'projects/'.`);return ko("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(ua,"exchangeIDTokenForGcpWorkloadToken");async function ca({serviceAccountEmailOrIdentifier:n,audience:e,accessToken:t},r){let o={audience:e,includeEmail:!0};return da(`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(ca,"generateServiceAccountIDToken");async function la(n,e,t){return ko(n,{token:e,returnSecureToken:!0},t)}i(la,"exchangeFirebaseJwtForIdToken");async function qn(n,e,t){return ko(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(qn,"exchangeGgpJwtForIdToken");async function ko(n,e,t){let r={method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)};return da(n,r,t)}i(ko,"fetchTokenFromBody");async function da(n,e,t){let r=await be(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 _({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(da,"fetchToken");var ve=class n{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),r=await(0,Un.importPKCS8)(t.private_key.trim(),"RS256");return new n({serviceAccount:t,privateKey:r})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};async function me(n){if(n.level==="error"&&console.error(n.messages),!m.instance.remoteLogURL||!m.instance.loggingId||!m.instance.remoteLogToken){console.warn("Remote logger is not configured. Skipping log entry.");return}try{let e={logOwner:"user",logSource:"runtime",rayId:null,requestId:`global-${crypto.randomUUID()}`,timestamp:new Date,buildId:m.instance.build.BUILD_ID,loggingId:m.instance.loggingId,...n,vectorClock:0};await pa({loggingUrl:m.instance.remoteLogURL,loggingId:m.instance.loggingId,loggingToken:m.instance.remoteLogToken},[e])}catch(e){console.error(e)}}i(me,"sendRemoteGlobalLog");async function pa({loggingUrl:n,loggingId:e,loggingToken:t},r){try{await F.fetch(`${n}/publish/${e}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:r.map(o=>({...o,messages:et(o.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${t}`,"user-agent":m.instance.systemUserAgent,"zp-dn":m.instance.deploymentName??"unknown"}})}catch(o){console.error(o)}}i(pa,"sendRemoteLogs");var Pd=i(({url:n,remoteLogToken:e,loggingId:t,sendOnlyErrors:r})=>async o=>{let s;r===!0?s=o.filter(a=>a.level==="error"):s=o,s.length!==0&&await pa({loggingUrl:n,loggingId:t,loggingToken:e},s)},"dispatchFunction"),Zn,Hn=class{static{i(this,"RemoteLogTransport")}constructor(e){Zn||(Zn=new ee("remote-log-transport",1,Pd(e)))}log(e,t){Zn.enqueue(e),t.waitUntil(Zn.waitUntilFlushed())}};var Fn=class extends ye{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new on(this.options)}},Id="https://logging.googleapis.com/v2/entries:write?alt=json",No={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},on=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=m.instance.loggingEnvironmentType,this.#i=m.instance.loggingEnvironmentStage,this.#r=m.instance.deploymentName,f("logging.google-cloud")}#e;#t;#n;#r;#o;#i;async init(){this.#t=await ve.init(this.#e)}log(e,t){if(!this.#t)throw new Q("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:et(e.messages)},o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:No[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=Tt(r.allMessages);s.jsonPayload={...r,message:a},this.batcher.enqueue(s),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await ve.init(this.#e));let t=await Ue({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"});try{let r=await F.fetch(Id,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});if(!r.ok){let o="";try{o=await r.text()}catch{}await me({level:"error",messages:[`Failed to send logs to Google: ${r.status} - ${r.statusText}`,o]})}}catch{await me({level:"error",messages:["Failed to connect to Google logging service. Check that the URL is correct."]})}};batcher=new ee("google-log-transport",1,this.dispatchFunction)};var $n="gcp";function jn(n){let e={allMessages:et(n.messages)},t="zuplo-production",r=Tt(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:No[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(jn,"gcpLogFormat");var sn=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===$n){if(e.messages.length===0)return;this.#e[e.level].apply(null,[jn(e)])}else this.#e.log(JSON.stringify(e))}};var Bn=class extends ye{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new an(this.options)}},Do="__ddtags",Mo="__ddattr",Uo=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),Ed=i(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(Uo(r)):t.push(`${Uo(r)}:${Uo(o.toString())}`)}),t.join(",")},"formatTags"),an=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=m.instance.loggingEnvironmentType,this.#o=m.instance.loggingEnvironmentStage,this.#n=m.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[Do];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(y=>y[Do]!==void 0);a>-1&&(Object.assign(r,s[a][Do]),s.splice(a,1));let u={},c=t.custom[Mo];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(y=>y[Mo]!==void 0);l>-1&&(Object.assign(u,s[l][Mo]),s.splice(l,1));let d=et(s),h={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:Tt(d),service:e.loggingId,ddtags:Ed(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(h,u),this.batcher.enqueue(h),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length!==0)try{let t=await F.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!t.ok){let r="";try{r=await t.text()}catch{}await me({level:"error",messages:[`Failed to send logs to DataDog: ${t.status} - ${t.statusText}`,r]})}}catch{await me({level:"error",messages:["Failed to connect to DataDog logging service. Check that the URL is correct."]})}};batcher=new ee("data-dog-transport",10,this.dispatchFunction)};var un=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===$n){if(e.messages.length===0)return;this.#e[e.level].apply(null,[jn(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId,vectorClock:e.vectorClock}])}};var Td={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},ma=i((n,e)=>t=>{let r={};return r.deploymentName=n,r.labels={requestId:t.requestId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},r.rayId=t.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=t.vectorClock,{timestamp:t.timestamp,observerdTimestamp:t.timestamp,traceId:t.requestId,severityText:t.level,severityNumber:Td[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var xd=i(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let s=ma(t,r);try{await F.fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":m.instance.systemUserAgent,"zp-dn":m.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),zn,Gn=class{static{i(this,"UnifiedLogTransport")}constructor(e){zn||(zn=new ee("unified-log-transport",1,xd(e)))}async log(e,t){zn.enqueue(e),t.waitUntil(zn.waitUntilFlushed())}};var qo=(0,ga.debug)("zuplo:logging"),Vn=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(m.instance,e),r=await n.setupUserCoreLogger(m.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;qo("Gateway.setupSystemCoreLogger");let o=[],s=t.getService(Kt);return s?o.push(new un(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new sn(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Gn({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new nn(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){qo("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=t.getService(Kt);if(a&&a.captureUserLogs===!0?r.push(new un(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new sn(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new Hn({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:!e.isWorkingCopy})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&(f("logging.google.legacy-initialization"),r.push(new on({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 an({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return $e.forEach(u=>{u instanceof ye&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new nn(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,t,r,o,s){qo("Gateway.createRequestLoggers");let a=new Dn(r,o,s),u=new rn(e,t,this.systemCoreLogger,a);return{userRequestLogger:new rn(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var mt=class{static{i(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};var Zo=class{static{i(this,"RouterEntry")}constructor(e,t,r,o){this.fullPath=e,this.urlPattern=t,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},xt=class{static{i(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},Ho=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}},Ot=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof mt||e instanceof pe))throw new Q("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(s=>s.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let s=new URLPattern({pathname:o}),a=new Zo(o,s,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new Ho(`addRoute-error: Invalid path '${o}'. '${s.message}'`,{cause:s})}}lookup(e,t){if(typeof e>"u")throw new g(`Invalid request - Method was undefined. Path: '${t}'`);let r=this.routeEntries.filter(o=>o.config.methods.includes(e));if(r.length!==0)for(let o=0;o<r.length;o++){let s=r[o],u=s.urlPattern.exec({pathname:t});if(u!==null)return new xt(s.config,s.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],a=o.urlPattern.exec({pathname:e});if(a!==null){let u=new xt(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var Fo;function fa(n){Fo=n}i(fa,"setGlobalZuploEventContext");function Wn(){if(Fo===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return Fo}i(Wn,"getGlobalZuploEventContext");function ha({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);Ss.includes(o.toLowerCase())&&!As.includes(r.toLowerCase())&&t.delete(r)}t.delete(hs)}else Cs.forEach(r=>{t.delete(r)});return t}i(ha,"normalizeIncomingRequestHeaders");var qe=(0,ba.debug)("zuplo:runtime"),Od=i(n=>{let e=n.findIndex(t=>t.name===Xt.name);return e>-1?[...n.splice(e),Xt]:[...n,Xt]},"setupSystemNoVersion"),Re=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;qe("Gateway.constructor"),Le,this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(qe("Gateway.initialize"),!n.#e){let s=await Vn.init(r),a=e(),u={...a,corsPolicies:Ws(a.corsPolicies)},c=new n(u,t,s,o);n.#e=c}if(!n.#e)throw new Q("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){qe("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new Q("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[Nn,Ln,Ie];#o;setupRoutes=()=>{qe("Gateway.setupRoutes");let e=this.routeData,t=Od(e.versions),r=new Ot(t);if(e.routes.length===0)return yo(r,this),To(r,this),Io(r,this),Ks(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(oa(r,this),ra(r,this)),yo(r,this),To(r,this),Io(r,this);for(let s of $e)s instanceof Fe&&s.registerRoutes(r,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new g(`Invalid state - No handler on route for path '${s.path}'`);let u=new he({processors:this.#r,handler:a,gateway:this}),c=new mt(s);r.addRoute(c,u.execute)}),Js(r,this),r};setupErrorHandler=()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new g("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=i((t,r,o)=>this.#i(t,r,o),"errorHandler");return e};errorHandler(e,t,r){try{return this.#o(e,t,r)}catch(o){return qe("An error occurred in the user's errorHandler",o),this.#i(e,t,o)}}#i(e,t,r){qe("Gateway.internalErrorResponse");let o={};if(m.instance.isLocalDevelopment||m.instance.isWorkingCopy){if(r instanceof _&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let s=Te(r.cause);"stack"in s&&(s.stack=sa(s.stack)),o={cause:s}}}return T.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t,r){let{requestId:o,rayId:s}=t;fa(r);let a=ha({headers:e.headers,removeAllVendorHeadersExceptListed:m.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(ut,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let B=new Headers(u.headers);B.set(Yr,"true"),u=new Request(u,{headers:B,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(o,s,r,c,u),p=new URL(u.url),h=p.pathname,y=this.#n.lookup(u.method,h);if(!y)throw new Q(`Invalid state - no route match - should have been picked up by the not found handler, path: '${h}'`);let A=new Kn(e.headers),P=new oe(u,{params:y.params}),O=new Jn({logger:l,route:y.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:A}),D=y.routeConfiguration.raw();ya.trace.getActiveSpan()?.setAttributes({"http.route":O.route.path??O.route.pathPattern,"cloud.region":O.incomingRequestProperties.colo,[Le.RoutePathPattern]:O.route.pathPattern,[Le.RouteOperationId]:D.operationId,[Le.RouteTrace]:D["x-zuplo-trace"],[Le.RouteSystem]:wt(p)?!0:void 0});let k=Pe.initialize(O,P);if(y.routeConfiguration===Eo&&Qt.value?.notFoundHandler!==void 0){let B=this.#n.lookupByPathOnly(h);k.pathOnlyMatches=B.map(q=>q.routeConfiguration).filter(q=>q instanceof mt)}try{if(te.addLogger(O,d),m.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!wt(p):!p.pathname.startsWith("/__zuplo")){let E=await qs(P,O);if(E instanceof Response)return E;{let Z=Pe.getContextExtensions(O);P=E,Z.latestRequest=P}}wt(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:y.routeConfiguration.path});let B=y.executableHandler;vd(B,y,u),qe("Gateway.handleRequest - call user handler");let q=await B(P,O);if(qe("Gateway.handleRequest - user handler"),!(q instanceof Response))throw new _(`Invalid Response type from the request handler: ${typeof q}`);if(q.bodyUsed)throw new _("The response object has already been used. Return a new response instead.");let j;if(q.headers.get(ut)===null&&!q.webSocket){let E=new Headers(q.headers);E.set(ut,o),j=new Response(q.body,{status:q.status,statusText:q.statusText,headers:E,cf:q.cf})}else j=q;return j}catch(B){return qe("Gateway - error executing handler",B),B instanceof _?(l.error(B),d.warn(B)):d.error(B),await this.#i(P,O,B)}}};function vd(n,e,t){if(qe("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(vd,"checkHandler");var wa=i(async(n,e,t)=>{let r=Re.instance.routeData.policies,o=tn([n],r);if(o.length===0)throw new _(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy");var Kn=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(oo);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(io)??void 0}get city(){return this.#e.get(Xr)??this.#e.get(Is)??void 0}get continent(){return this.#e.get(eo)??this.#e.get(Es)??void 0}get country(){return this.#e.get(to)??this.#e.get(Ts)??void 0}get latitude(){return this.#e.get(ro)??this.#e.get(Os)??void 0}get longitude(){return this.#e.get(no)??this.#e.get(xs)??void 0}get colo(){return this.#e.get(so)??void 0}get postalCode(){return this.#e.get(Rs)??this.#e.get(ao)??void 0}get metroCode(){return this.#e.get(ws)??this.#e.get(uo)??void 0}get region(){return this.#e.get(ys)??this.#e.get(co)??void 0}get regionCode(){return this.#e.get(bs)??this.#e.get(lo)??void 0}get timezone(){return this.#e.get(Ps)??this.#e.get(po)??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}}},Rt=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},Pt=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},Pe=class n{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let r=new n(t);return n.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=n.#e.get(e);if(!t)throw new _(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)};onResponseSending=async(e,t,r)=>{let o=e;for(let s of this.#n)o=await s(e,t,r);return o}},Jn=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=s,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>wa(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{Pe.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{Pe.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=i(s=>{try{typeof t=="function"?t(s):t.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var ue=class n{static{i(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,t){n.set(e,this.#t,t)}get(e){return n.get(e,this.#t)}static set(e,t,r){n.#e||(n.#e=new WeakMap);let o=n.#e.get(e);o||(o=new Map),o.set(t,r),n.#e.set(e,o)}static get(e,t){return n.#e||(n.#e=new WeakMap),n.#e.get(e)?.get(t)}};var Cd=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function Sd(n){return n.startsWith("__ZUPLO")||n.startsWith("ZUPLO_")?!Cd.includes(n)&&!n.startsWith("ZUPLO_PUBLIC_"):!1}i(Sd,"isRestrictedEnvVariableName");function Ad(n){return!!n.startsWith("ZUPLO_")}i(Ad,"isZuploReadableEnvVariableName");var Ee=new Proxy({},{get(n,e){let t=String(e);switch(t){case"ZUPLO_ENVIRONMENT_TYPE":return m.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return m.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return m.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return m.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return m.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return m.instance.build.BUILD_ID}if(!(Sd(t)&&!Ad(t)))return m.instance.runtime[t]}});var Ra=require("node:async_hooks");var Pa={request:new Ra.AsyncLocalStorage};var _d="Error initializing gateway. Check your configuration for errors or contact support.",Ld="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",Qn=class{constructor(e,t,r,o,s,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=async(e,t,r)=>{let o=e.headers.get(ut)??e.headers.get(fs)??crypto.randomUUID(),s=e.headers.get(ct),a={requestId:o,rayId:s};return Pa.request.run(a,async()=>{m.initialize({build:this.buildEnvironment,runtime:t});try{await Fs(this.runtimeInit)}catch(c){this.handleError(c,Ld,e)}return ks(i(async(c,l)=>{let d;try{d=await Re.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,_d,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,r)})};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:m.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};var Aa=ze(He());function kd(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(kd,"lexer");function $o(n,e){e===void 0&&(e={});for(var t=kd(n),r=e.prefixes,o=r===void 0?"./":r,s="[^".concat(Dd(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=i(function(E){if(c<t.length&&t[c].type===E)return t[c++].value},"tryConsume"),p=i(function(E){var Z=d(E);if(Z!==void 0)return Z;var V=t[c],W=V.type,C=V.index;throw new TypeError("Unexpected ".concat(W," at ").concat(C,", expected ").concat(E))},"mustConsume"),h=i(function(){for(var E="",Z;Z=d("CHAR")||d("ESCAPED_CHAR");)E+=Z;return E},"consumeText");c<t.length;){var y=d("CHAR"),A=d("NAME"),P=d("PATTERN");if(A||P){var O=y||"";o.indexOf(O)===-1&&(l+=O,O=""),l&&(a.push(l),l=""),a.push({name:A||u++,prefix:O,suffix:"",pattern:P||s,modifier:d("MODIFIER")||""});continue}var D=y||d("ESCAPED_CHAR");if(D){l+=D;continue}l&&(a.push(l),l="");var k=d("OPEN");if(k){var O=h(),B=d("NAME")||"",q=d("PATTERN")||"",j=h();p("CLOSE"),a.push({name:B||(q?u++:""),pattern:B&&!q?s:q,prefix:O,suffix:j,modifier:d("MODIFIER")||""});continue}p("END")}return a}i($o,"parse");function Ia(n,e){return Nd($o(n,e),e)}i(Ia,"compile");function Nd(n,e){e===void 0&&(e={});var t=Md(e),r=e.encode,o=r===void 0?function(c){return c}:r,s=e.validate,a=s===void 0?!0:s,u=n.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var h=c?c[p.name]:void 0,y=p.modifier==="?"||p.modifier==="*",A=p.modifier==="*"||p.modifier==="+";if(Array.isArray(h)){if(!A)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(h.length===0){if(y)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var P=0;P<h.length;P++){var O=o(h[P],p);if(a&&!u[d].test(O))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(O,'"'));l+=p.prefix+O+p.suffix}continue}if(typeof h=="string"||typeof h=="number"){var O=o(String(h),p);if(a&&!u[d].test(O))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(O,'"'));l+=p.prefix+O+p.suffix;continue}if(!y){var D=A?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(D))}}return l}}i(Nd,"tokensToFunction");function Dd(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(Dd,"escapeString");function Md(n){return n&&n.sensitive?"":"i"}i(Md,"flags");var Oa=ze(He());var Ud=(0,Oa.debug)("zuplo:runtime"),Bo=new TextEncoder,Ea={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"},qd=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],vt=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 zo(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){Ud("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,t),a=F.fetch(o,s);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new g("An unknown error occurred, ensure retries is not negative")}},zo=class{static{i(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:r,body:o,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:h,appendSessionToken:y,allHeaders:A,singleEncode:P}){if(t==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let O,D;(!c||!l)&&([O,D]=Zd(this.url,this.headers)),this.service=c||O||"",this.region=l||D||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=h,this.appendSessionToken=y||this.service==="iotdevicegateway",this.headers.delete("Host");let k=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),k.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&k.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(q=>A||!qd.includes(q)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(q=>q+":"+(q==="host"?this.url.host:(this.headers.get(q)||"").replace(/\s+/g," "))).join(`
57
+ `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!k.has("X-Amz-Expires")&&k.set("X-Amz-Expires","86400"),k.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),k.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),k.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");P||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=xa(this.encodedPath);let B=new Set;this.encodedSearch=[...this.url.searchParams].filter(([q])=>{if(!q)return!1;if(this.service==="s3"){if(B.has(q))return!1;B.add(q)}return!0}).map(q=>q.map(j=>xa(encodeURIComponent(j)))).sort(([q,j],[E,Z])=>q<E?-1:q>E?1:j<Z?-1:j>Z?1:0).map(q=>q.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),t=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(t);if(!r){let o=await cn("AWS4"+this.secretAccessKey,e),s=await cn(o,this.region),a=await cn(s,this.service);r=await cn(a,"aws4_request"),this.cache.set(t,r)}return jo(await cn(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,jo(await Ta(await this.canonicalString()))].join(`
58
58
  `)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
59
59
  `,this.signedHeaders,await this.hexBodyHash()].join(`
60
- `)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new A("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Go(await Ta(this.body||""))}return e}};async function sn(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?Vo.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,Vo.encode(e))}i(sn,"hmac");async function Ta(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?Vo.encode(n):n)}i(Ta,"hash");function Go(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}i(Go,"buf2hex");function xa(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(xa,"encodeRfc3986");function qd(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 Ea?[Ea[s],a]:[s,a]}i(qd,"guessServiceRegion");function Fd(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(Fd,"b64ToUint6");function Oa(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|=Fd(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(Oa,"base64Decode");function Yn(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}i(Yn,"uint6ToB64");function Ca(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(Yn(o>>>18&63),Yn(o>>>12&63),Yn(o>>>6&63),Yn(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}i(Ca,"base64Encode");function xt(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}i(xt,"numberToString");function $d(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=xt(Math.floor(t/60)),s=xt(t%60);return`${r}${o}${s}`}i($d,"getCLFOffset");function Ko(n=new Date){if(!(n instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],t=xt(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),s=xt(n.getHours()),a=xt(n.getMinutes()),u=xt(n.getSeconds()),c=$d(n);return`${t}/${r}/${o}:${s}:${a}:${u} ${c}`}i(Ko,"toCLFDate");var Sa=(0,Aa.debug)("zuplo:runtime"),jd="X-Amzn-Trace-Id",zd="x-amzn-errortype",_a=[],Bd=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 A{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(jd)??void 0,this.errorType=t.get(zd)??void 0}},La={addSendingAwsLambdaEventHook:n=>{_a.push(n)}};async function ka(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 Tt({accessKeyId:t,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(Sa(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,h]=await Kd(n,{binaryMediaTypes:c}),{options:y}=e.route.handler,_;y&&typeof y=="object"&&"payloadFormatVersion"in y&&y.payloadFormatVersion==="2.0"?_=Wd(n,e):_=await Vd(n,e,{useAwsResourcePathStyle:u}),Sa("Calling onSendingAwsLambdaEvent hook");let P=await Bd(n,e,_);P.body=p,P.isBase64Encoded=h;let C=await l.fetch(d,{body:JSON.stringify(P)});try{return Gd(C)}catch(H){if(H instanceof Ce){let N=y&&typeof y=="object"&&"returnAmazonTraceIdHeader"in y&&y.returnAmazonTraceIdHeader&&H.traceId?{AMZN_TRACE_ID_HEADER:H.traceId}:void 0;return T.internalServerError(n,e,void 0,N)}throw H}}i(ka,"awsLambdaHandler");async function Gd(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=Oa(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(Gd,"getResponse");async function Vd(n,e,{useAwsResourcePathStyle:t}){let r={},o={};n.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let s=n.query,a={};for(let[l,d]of Object.entries(s))a[l]=[d];let u=new URL(n.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:n.method,headers:r,multiValueHeaders:o,queryStringParameters:s,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:n.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:n.headers.get("CF-Connecting-IP"),user:null,userAgent:n.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:Ko(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Yd(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}i(Vd,"buildEventVersion1");function Wd(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:Ko(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}i(Wd,"buildEventVersion2");async function Kd(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&&Jd(e,o)){let s=await n.arrayBuffer();t=Ca(new Uint8Array(s)),r=!0}else t=await n.clone().text();return[t,r]}i(Kd,"getBodyResult");function Jd(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}i(Jd,"matchesContentType");function Yd(n,e=!1){if(!e)return n;let t=Bo(n),r=Ia(n),o={};return t.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),r(o)}i(Yd,"getResourcePath");var Xd=[502,503,504];async function vt(n,e){if(Xd.includes(n.status)){let t=te.getLogger(e),o=await n.clone().text(),s={};for(let[a,u]of n.headers)s[a]=u;t.warn(`BadGatewayResponse ${n.status}`,{status:n.status,statusText:n.statusText,body:o,headers:s})}}i(vt,"logBadGatewayResponses");var Jo;function et(n){if(Jo===void 0){let t=m.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),Jo=t}return n.log[Jo]}i(et,"getHandlerUserLogFunction");async function Na(n,e){f("handler.open-api");let t=m.instance.build.BUILD_ID,{buildAssetsUrl:r}=m.instance,o=e.route.handler.options,{openApiFilePath:s}=o;if(!s)throw new g("Open API Spec Handler must have 'openApiFilePath' specified");let a=Qd(s);if(!a.isValid)throw new g(a.error);let u;m.instance.isLocalDevelopment?u=`${r}/${s.substring(1)}`:u=`${r}/${t}${s.substring(1)}`;let c=await F.fetch(u,{method:n.method,body:n.body,headers:n.headers});if(c.status!==200)return T.notFound(n,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return vt(l,e),l}i(Na,"openApiSpecHandler");var Qd=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 Ma(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(Ma,"redirectHandler");function ep(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(ep,"join");async function Da(n,e){f("handler.url-forward");let t=et(e),r=e.route.handler.options,o=r.forwardSearch!==!1;if(!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new g("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(n.url),u=r.__rewriteFunction(n,s),c=ep(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();t(`URL Forwarding to '${l}'`);let p=await F.fetch(l,{method:n.method,body:n.body,headers:n.headers}),h=Date.now()-d;return t(`URL Forward received response ${p.status} - ${p.statusText} in ${h}ms`),vt(p,e),p}i(Da,"urlForwardHandler");var tp=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 Ua(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={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(n,a),c=o?tp(u,n.url):u,l=Date.now();t(`URL Rewriting to '${c}'`);let d=await F.fetch(c.toString(),{method:n.method,body:n.body,headers:n.headers,redirect:s?"follow":"manual"}),p=Date.now()-l;return t(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),vt(d,e),d}i(Ua,"urlRewriteHandler");async function Ha(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={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await F.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let d=await c.text(),p=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${d}'`;throw new Error(p)}let l=Date.now()-u;return r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${l}ms`),new Response(null,{status:101,webSocket:c.webSocket})}i(Ha,"webSocketHandler");var Yo=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"),Za=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 Za(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 Fa(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={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await F.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let C=await c.text(),H=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${C}'`;throw new Error(H)}let l=new WebSocketPair,[d,p]=Object.values(l),h=Date.now()-u;r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${h}ms`);let y=c.webSocket;y.accept(),p.accept();let _=t.policies&&t.policies.inbound?Yo(t.policies.inbound,"inbound"):[],P=t.policies&&t.policies.outbound?Yo(t.policies.outbound,"outbound"):[];return qa(p,y,n,e,_),qa(y,p,n,e,P),new Response(null,{status:101,webSocket:d})}i(Fa,"webSocketPipelineHandler");var Xn=class extends ye{constructor(t){super();this.options=t}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new Xo(this.options)}},Xo=class{static{i(this,"DynaTraceTransport")}constructor(e){f("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#r=m.instance.loggingEnvironmentType,this.#o=m.instance.loggingEnvironmentStage,this.#n=m.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:ze(Te(r)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{if(e.length!==0)try{let t=await F.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}});if(!t.ok){let r="";try{r=await t.text()}catch{}await pe({level:"error",messages:[`Failed to send logs to Dynatrace: ${t.status} - ${t.statusText}`,r]})}}catch{await pe({level:"error",messages:["Failed to connect to Dynatrace logging service. Check that the URL is correct."]})}};batcher=new Q("dyna-trace-log-transport",10,this.#i)};var Qn=class extends ye{constructor(t){super();this.options=t}static{i(this,"LokiLoggingPlugin")}getTransport(){return new ei(this.options)}},Qo=class{static{i(this,"LokiStream")}constructor(e,t,r,o,s,a){this.level=e,this.environment=t,this.environmentType=r,this.environmentStage=o,this.requestId=a,this.job=s}job;level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function np(n,e){return btoa(`${n}:${e}`)}i(np,"createBasicDigest");var ei=class{static{i(this,"LokiTransport")}constructor(e){f("logging.loki"),this.#n=e.url,this.#r=np(e.username,e.password),this.#i=m.instance.loggingEnvironmentType,this.#s=m.instance.loggingEnvironmentStage,this.#o=m.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo"}#e;#t;#n;#r;#o;#i;#s;log(e,t){let r=new Qo(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(o=>{let s={stream:r,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:ze(Te(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(s)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=e=>{let t={streams:[]};return e.forEach(r=>{let o=t.streams.find(s=>s.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},t.streams.push(o)),o.values.push(this.#e>1?[r.nanoSecondEpoch,r.message,{requestId:r.requestId,rayId:r.rayId,atomicCounter:JSON.stringify(r.atomicCounter)}]:[r.nanoSecondEpoch,r.message])}),t};#u=async e=>{if(e.length===0)return;let t=this.#a(e);try{let r=await F.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}});if(!r.ok){let o="";try{o=await r.text()}catch{}await pe({level:"error",messages:[`Failed to send logs to Loki: ${r.status} - ${r.statusText}`,o]})}}catch{await pe({level:"error",messages:["Failed to connect to Loki logging service. Check that the URL is correct."]})}};batcher=new Q("loki-log-transport",10,this.#u)};var er=class extends ye{constructor(t){super();this.options=t}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new ti(this.options)}},ti=class{static{i(this,"SumoLogicTransport")}constructor(e){f("logging.sumologic"),this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=m.instance.loggingEnvironmentType,this.#r=m.instance.loggingEnvironmentStage,this.#t=m.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:ze(Te(r)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let t=e.map(o=>JSON.stringify(o)).join(`
61
- `),r=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&r.set("X-Sumo-Name",this.#i),this.#o&&r.set("X-Sumo-Category",this.#o);try{let o=await F.fetch(this.#e,{method:"POST",body:t,headers:r});if(!o.ok){let s="";try{s=await o.text()}catch{}await pe({level:"error",messages:[`Failed to send logs to Sumologic: ${o.status} - ${o.statusText}`,s]})}}catch{await pe({level:"error",messages:["Failed to connect to Sumologic logging service. Check that the URL is correct."]})}};batcher=new Q("sumo-logic-log-transport",10,this.#s)};var rp="d3a5b78f823648f5b1df4fe269d41172",tr=class extends ye{constructor(t){super();this.options=t}static{i(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new ni(this.options)}},ni=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??rp}`)}catch{throw new g(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=t.toString(),this.#r=m.instance.loggingEnvironmentType,this.#o=m.instance.loggingEnvironmentStage,this.#n=m.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=aa(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=Mo(a);u&&o.fields.push({name:s,content:u})}),this.#i&&(o=this.#i(o)),o}#a=async e=>{if(e.length!==0)try{let t=await F.fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});if(!t.ok){let r="";try{r=await t.text()}catch{}await pe({level:"error",messages:[`Failed to send logs to Log Insight: ${t.status} - ${t.statusText}`,r]})}}catch{await pe({level:"error",messages:["Failed to connect to Log Insight logging service. Check that the URL is correct."]})}};batcher=new Q("vmware-log-insights-log-transport",10,this.#a)};var nr=class extends ye{constructor(t){super();this.options=t}static{i(this,"AWSLoggingPlugin")}getTransport(){return new ri(this.options)}},ri=class{static{i(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new Q("aws-log-transport",10,async e=>{if(e.length===0)return;let t=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});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}});if(!r.ok){let o="";try{o=await r.text()}catch{}await pe({level:"error",messages:[`Failed to send logs to AWS: ${r.status} - ${r.statusText}`,o]})}}catch{await pe({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}){f("logging.aws"),this.awsClient=new Tt({accessKeyId:e,secretAccessKey:o,service:"logs",region:s}),this.logGroupName=r,this.logStreamName=t,this.region=s,this.environmentType=m.instance.loggingEnvironmentType,this.environment=m.instance.deploymentName}log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:ze(Te(r)),severity:e.level,source:e.logSource,environment:this.environment,requestId:e.requestId,environmentType:this.environmentType,rayId:e.rayId===null?void 0:e.rayId})};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}};var oi=new WeakMap,op={tags:[]},rr=class extends Xe{constructor(t){super();this.options=t;f("metrics.datadog")}static{i(this,"DataDogMetricsPlugin")}getTransport(){return new ii(this.options)}static setContext(t,r){let o=oi.get(t);o||(o=op);let s=Object.assign({...o},r);oi.set(t,s)}},ii=class{static{i(this,"DataDogMetricsTransport")}#e;#t;#n;#r;#o;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://api.datadoghq.com/api/v2/series",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.#r=e.tags??[]}pushMetrics(e,t){this.#i===void 0&&(this.#i=new Q("data-dog-metrics-transport",10,this.dispatchFunction,te.getLogger(t)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(oi.get(t)?.tags??[]);if(this.#o.country&&o.push(`country:${e.country}`),this.#o.httpMethod&&o.push(`httpMethod:${e.method}`),this.#o.statusCode&&o.push(`statusCode:${e.statusCode}`),this.#o.path){let s=e.systemRouteName||e.routePath;o.push(`path:${s}`)}this.#n.latency&&this.#i.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:r,value:e.durationMs}],tags:o}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:r,value:e.requestContentLength}],tags:o}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:r,value:e.responseContentLength}],tags:o}),t.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let t=JSON.stringify({series:e}),r=await F.fetch(this.#t,{method:"POST",body:t,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new si(await r.text())}},si=class n extends Error{static{i(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var ai=new WeakMap,ip={dimensions:[]},or=class extends Xe{constructor(t){super();this.options=t;f("metrics.dynatrace")}static{i(this,"DynatraceMetricsPlugin")}getTransport(){return new ui(this.options)}static setContext(t,r){let o=ai.get(t);o||(o=ip);let s=Object.assign({...o},r);ai.set(t,s)}},ui=class{static{i(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#n;#r=void 0;constructor(e){this.apiToken=e.apiToken,this.#e=e.url,this.#t=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#n=e.include??{},this.dimensions=e.dimensions??[]}pushMetrics(e,t){this.#r===void 0&&(this.#r=new Q("dynatrace-metrics-transport",10,this.dispatchFunction,te.getLogger(t)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(ai.get(t)?.dimensions??[]);if(this.#n.country&&o.push(`country="${e.country}"`),this.#n.httpMethod&&o.push(`http_method="${e.method}"`),this.#n.statusCode&&o.push(`status_code="${e.statusCode}"`),this.#n.path){let a=e.systemRouteName||e.routePath;o.push(`path="${a}"`)}let s=o.join(",");this.#t.latency&&this.#r.enqueue(`zuplo.request.latency,${s} ${e.durationMs} ${r}`),this.#t.requestContentLength&&e.requestContentLength&&this.#r.enqueue(`zuplo.request.content_length,${s} ${e.requestContentLength} ${r}`),this.#t.responseContentLength&&e.responseContentLength&&this.#r.enqueue(`zuplo.response.content_length,${s} ${e.responseContentLength} ${r}`),t.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let t=e.join(`
62
- `),r=await F.fetch(this.#e,{method:"POST",body:t,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new ci(await r.text())}},ci=class n extends Error{static{i(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var ir=class{static{i(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e,f("audit-logs.datastax")}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async t=>{await F.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(t)})}))}};var sr=class extends Fe{static{i(this,"AuditLogPlugin")}constructor(e,t){super(),this.#e=e,this.#t=t,f("audit-logs")}#e;#t;async initialize(e){new li(e,this.#e,this.#t)}},$a=i(n=>{let e={};return n.forEach((t,r)=>{e[r]=t}),e},"serializableHeaders"),sp={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},li=class{static{i(this,"AuditPluginImpl")}constructor(e,t,r){this.#t=t;let o={...sp};r?.requestFilter&&(o.requestFilter=r.requestFilter),r?.include?.request&&Object.assign(o,r.include.request),r?.include?.response&&Object.assign(o,r.include.response),this.#e=o,e.addRequestHook(this.#i),this.#n=new Q("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,t,r,o,s,a)=>{try{let u={timestamp:o,durationMs:s,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:t.url,method:t.method,headers:this.#e.include?.request?.headers?$a(t.headers):void 0,body:this.#e.include?.request?.body?await t.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?$a(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(u),r.waitUntil(this.#n.waitUntilFlushed())}catch(u){r.log.error(u)}};#i=async(e,t)=>{try{if(!await this.#e.requestFilter(e,t))return e;let o=new Date,s=Date.now(),a=e.clone();return t.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#o(d,a,t,o,l-s,c.user?.sub).catch(h=>{t.log.error(h)});t.waitUntil(p)}),e}catch(r){return t.log.error(r),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}},Ze=class extends di{static{i(this,"StripeSignatureVerificationError")}header;payload;constructor(e,t,r={}){super(r),this.header=e,this.payload=t}};var ap="v1",up=300;async function ja(n,e,t,r=up,o){return await lp(n,e,t,r,o),n instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(n)):JSON.parse(n)}i(ja,"constructEventAsync");function cp(n,e){return`${e.timestamp}.${n}`}i(cp,"makeHMACContent");async function lp(n,e,t,r,o){let{decodedHeader:s,decodedPayload:a,details:u,suspectPayloadType:c}=dp(n,e,ap),l=/\s/.test(t),d=await fp(cp(a,u),t);return pp(a,s,u,d,r,c,l,o)}i(lp,"verifyHeaderAsync");function dp(n,e,t){if(!n)throw new Ze(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 Ze(e,n,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=mp(a,t);if(!u||u.timestamp===-1)throw new Ze(a,s,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new Ze(a,s,{message:"No signatures found with expected scheme"});return{decodedPayload:s,decodedHeader:a,details:u,suspectPayloadType:r}}i(dp,"parseEventDetails");function pp(n,e,t,r,o,s,a,u){let c=!!t.signatures.filter(h=>gp(h,r)).length,l=`
60
+ `)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new _("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=jo(await Ta(this.body||""))}return e}};async function cn(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?Bo.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,Bo.encode(e))}i(cn,"hmac");async function Ta(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?Bo.encode(n):n)}i(Ta,"hash");function jo(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}i(jo,"buf2hex");function xa(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(xa,"encodeRfc3986");function Zd(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 Ea?[Ea[s],a]:[s,a]}i(Zd,"guessServiceRegion");function Hd(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(Hd,"b64ToUint6");function va(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|=Hd(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(va,"base64Decode");function Yn(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}i(Yn,"uint6ToB64");function Ca(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(Yn(o>>>18&63),Yn(o>>>12&63),Yn(o>>>6&63),Yn(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}i(Ca,"base64Encode");function Ct(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}i(Ct,"numberToString");function Fd(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=Ct(Math.floor(t/60)),s=Ct(t%60);return`${r}${o}${s}`}i(Fd,"getCLFOffset");function Go(n=new Date){if(!(n instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],t=Ct(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),s=Ct(n.getHours()),a=Ct(n.getMinutes()),u=Ct(n.getSeconds()),c=Fd(n);return`${t}/${r}/${o}:${s}:${a}:${u} ${c}`}i(Go,"toCLFDate");var Sa=(0,Aa.debug)("zuplo:runtime"),$d="X-Amzn-Trace-Id",jd="x-amzn-errortype",_a=[],Bd=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 _{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get($d)??void 0,this.errorType=t.get(jd)??void 0}},La={addSendingAwsLambdaEventHook:n=>{_a.push(n)}};async function ka(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 vt({accessKeyId:t,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(Sa(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,h]=await Wd(n,{binaryMediaTypes:c}),{options:y}=e.route.handler,A;y&&typeof y=="object"&&"payloadFormatVersion"in y&&y.payloadFormatVersion==="2.0"?A=Vd(n,e):A=await Gd(n,e,{useAwsResourcePathStyle:u}),Sa("Calling onSendingAwsLambdaEvent hook");let P=await Bd(n,e,A);P.body=p,P.isBase64Encoded=h;let O=await l.fetch(d,{body:JSON.stringify(P)});try{return zd(O)}catch(D){if(D instanceof Ce){let k=y&&typeof y=="object"&&"returnAmazonTraceIdHeader"in y&&y.returnAmazonTraceIdHeader&&D.traceId?{AMZN_TRACE_ID_HEADER:D.traceId}:void 0;return T.internalServerError(n,e,void 0,k)}throw D}}i(ka,"awsLambdaHandler");async function zd(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=va(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(zd,"getResponse");async function Gd(n,e,{useAwsResourcePathStyle:t}){let r={},o={};n.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let s=n.query,a={};for(let[l,d]of Object.entries(s))a[l]=[d];let u=new URL(n.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:n.method,headers:r,multiValueHeaders:o,queryStringParameters:s,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:n.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:n.headers.get("CF-Connecting-IP"),user:null,userAgent:n.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:Go(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Jd(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}i(Gd,"buildEventVersion1");function Vd(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:Go(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}i(Vd,"buildEventVersion2");async function Wd(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&&Kd(e,o)){let s=await n.arrayBuffer();t=Ca(new Uint8Array(s)),r=!0}else t=await n.clone().text();return[t,r]}i(Wd,"getBodyResult");function Kd(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}i(Kd,"matchesContentType");function Jd(n,e=!1){if(!e)return n;let t=$o(n),r=Ia(n),o={};return t.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),r(o)}i(Jd,"getResourcePath");var Qd=[502,503,504];async function St(n,e){if(Qd.includes(n.status)){let t=te.getLogger(e),o=await n.clone().text(),s={};for(let[a,u]of n.headers)s[a]=u;t.warn(`BadGatewayResponse ${n.status}`,{status:n.status,statusText:n.statusText,body:o,headers:s})}}i(St,"logBadGatewayResponses");var Vo;function tt(n){if(Vo===void 0){let t=m.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),Vo=t}return n.log[Vo]}i(tt,"getHandlerUserLogFunction");async function Na(n,e){f("handler.open-api");let t=m.instance.build.BUILD_ID,{buildAssetsUrl:r}=m.instance,o=e.route.handler.options,{openApiFilePath:s}=o;if(!s)throw new g("Open API Spec Handler must have 'openApiFilePath' specified");let a=Yd(s);if(!a.isValid)throw new g(a.error);let u;m.instance.isLocalDevelopment?u=`${r}/${s.substring(1)}`:u=`${r}/${t}${s.substring(1)}`;let c=await F.fetch(u,{method:n.method,body:n.body,headers:n.headers});if(c.status!==200)return T.notFound(n,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return St(l,e),l}i(Na,"openApiSpecHandler");var Yd=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 Da(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(Da,"redirectHandler");function Xd(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(Xd,"join");async function Ma(n,e){f("handler.url-forward");let t=tt(e),r=e.route.handler.options,o=r.forwardSearch!==!1;if(!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new g("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(n.url),u=r.__rewriteFunction(n,s),c=Xd(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();t(`URL Forwarding to '${l}'`);let p=await F.fetch(l,{method:n.method,body:n.body,headers:n.headers}),h=Date.now()-d;return t(`URL Forward received response ${p.status} - ${p.statusText} in ${h}ms`),St(p,e),p}i(Ma,"urlForwardHandler");var ep=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 Ua(n,e){f("handler.url-rewrite");let t=tt(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={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(n,a),c=o?ep(u,n.url):u,l=Date.now();t(`URL Rewriting to '${c}'`);let d=await F.fetch(c.toString(),{method:n.method,body:n.body,headers:n.headers,redirect:s?"follow":"manual"}),p=Date.now()-l;return t(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),St(d,e),d}i(Ua,"urlRewriteHandler");async function qa(n,e){f("handler.websocket");let t=e.route.handler.options,r=tt(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={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await F.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let d=await c.text(),p=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${d}'`;throw new Error(p)}let l=Date.now()-u;return r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${l}ms`),new Response(null,{status:101,webSocket:c.webSocket})}i(qa,"webSocketHandler");var Wo=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"),Za=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 Ha(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 Za(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(Ha,"wireUpListeners");async function Fa(n,e){f("handler.websocket-pipeline");let t=e.route.handler.options,r=tt(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={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await F.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let O=await c.text(),D=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${O}'`;throw new Error(D)}let l=new WebSocketPair,[d,p]=Object.values(l),h=Date.now()-u;r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${h}ms`);let y=c.webSocket;y.accept(),p.accept();let A=t.policies&&t.policies.inbound?Wo(t.policies.inbound,"inbound"):[],P=t.policies&&t.policies.outbound?Wo(t.policies.outbound,"outbound"):[];return Ha(p,y,n,e,A),Ha(y,p,n,e,P),new Response(null,{status:101,webSocket:d})}i(Fa,"webSocketPipelineHandler");var Xn=class extends ye{constructor(t){super();this.options=t}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new Ko(this.options)}},Ko=class{static{i(this,"DynaTraceTransport")}constructor(e){f("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#r=m.instance.loggingEnvironmentType,this.#o=m.instance.loggingEnvironmentStage,this.#n=m.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Be(Te(r)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{if(e.length!==0)try{let t=await F.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}});if(!t.ok){let r="";try{r=await t.text()}catch{}await me({level:"error",messages:[`Failed to send logs to Dynatrace: ${t.status} - ${t.statusText}`,r]})}}catch{await me({level:"error",messages:["Failed to connect to Dynatrace logging service. Check that the URL is correct."]})}};batcher=new ee("dyna-trace-log-transport",10,this.#i)};var er=class extends ye{constructor(t){super();this.options=t}static{i(this,"LokiLoggingPlugin")}getTransport(){return new Qo(this.options)}},Jo=class{static{i(this,"LokiStream")}constructor(e,t,r,o,s,a){this.level=e,this.environment=t,this.environmentType=r,this.environmentStage=o,this.requestId=a,this.job=s}job;level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function tp(n,e){return btoa(`${n}:${e}`)}i(tp,"createBasicDigest");var Qo=class{static{i(this,"LokiTransport")}constructor(e){f("logging.loki"),this.#n=e.url,this.#r=tp(e.username,e.password),this.#i=m.instance.loggingEnvironmentType,this.#s=m.instance.loggingEnvironmentStage,this.#o=m.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo"}#e;#t;#n;#r;#o;#i;#s;log(e,t){let r=new Jo(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(o=>{let s={stream:r,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:Be(Te(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(s)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=e=>{let t={streams:[]};return e.forEach(r=>{let o=t.streams.find(s=>s.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},t.streams.push(o)),o.values.push(this.#e>1?[r.nanoSecondEpoch,r.message,{requestId:r.requestId,rayId:r.rayId,atomicCounter:JSON.stringify(r.atomicCounter)}]:[r.nanoSecondEpoch,r.message])}),t};#u=async e=>{if(e.length===0)return;let t=this.#a(e);try{let r=await F.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}});if(!r.ok){let o="";try{o=await r.text()}catch{}await me({level:"error",messages:[`Failed to send logs to Loki: ${r.status} - ${r.statusText}`,o]})}}catch{await me({level:"error",messages:["Failed to connect to Loki logging service. Check that the URL is correct."]})}};batcher=new ee("loki-log-transport",10,this.#u)};var tr=class extends ye{constructor(t){super();this.options=t}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new Yo(this.options)}},Yo=class{static{i(this,"SumoLogicTransport")}constructor(e){f("logging.sumologic"),this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=m.instance.loggingEnvironmentType,this.#r=m.instance.loggingEnvironmentStage,this.#t=m.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Be(Te(r)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let t=e.map(o=>JSON.stringify(o)).join(`
61
+ `),r=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&r.set("X-Sumo-Name",this.#i),this.#o&&r.set("X-Sumo-Category",this.#o);try{let o=await F.fetch(this.#e,{method:"POST",body:t,headers:r});if(!o.ok){let s="";try{s=await o.text()}catch{}await me({level:"error",messages:[`Failed to send logs to Sumologic: ${o.status} - ${o.statusText}`,s]})}}catch{await me({level:"error",messages:["Failed to connect to Sumologic logging service. Check that the URL is correct."]})}};batcher=new ee("sumo-logic-log-transport",10,this.#s)};var np="d3a5b78f823648f5b1df4fe269d41172",nr=class extends ye{constructor(t){super();this.options=t}static{i(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new Xo(this.options)}},Xo=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??np}`)}catch{throw new g(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=t.toString(),this.#r=m.instance.loggingEnvironmentType,this.#o=m.instance.loggingEnvironmentStage,this.#n=m.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=aa(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=Lo(a);u&&o.fields.push({name:s,content:u})}),this.#i&&(o=this.#i(o)),o}#a=async e=>{if(e.length!==0)try{let t=await F.fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});if(!t.ok){let r="";try{r=await t.text()}catch{}await me({level:"error",messages:[`Failed to send logs to Log Insight: ${t.status} - ${t.statusText}`,r]})}}catch{await me({level:"error",messages:["Failed to connect to Log Insight logging service. Check that the URL is correct."]})}};batcher=new ee("vmware-log-insights-log-transport",10,this.#a)};var rr=class extends ye{constructor(t){super();this.options=t}static{i(this,"AWSLoggingPlugin")}getTransport(){return new ei(this.options)}},ei=class{static{i(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new ee("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}});if(!r.ok){let o="";try{o=await r.text()}catch{}await me({level:"error",messages:[`Failed to send logs to AWS: ${r.status} - ${r.statusText}`,o]})}}catch{await me({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}){f("logging.aws"),this.awsClient=new vt({accessKeyId:e,secretAccessKey:o,service:"logs",region:s}),this.logGroupName=r,this.logStreamName=t,this.region=s,this.environmentType=m.instance.loggingEnvironmentType,this.environment=m.instance.deploymentName}log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:Be(Te(r)),severity:e.level,source:e.logSource,environment:this.environment,requestId:e.requestId,environmentType:this.environmentType,rayId:e.rayId===null?void 0:e.rayId})};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}};var ti=new WeakMap,rp={tags:[]},or=class extends Ye{constructor(t){super();this.options=t;f("metrics.datadog")}static{i(this,"DataDogMetricsPlugin")}getTransport(){return new ni(this.options)}static setContext(t,r){let o=ti.get(t);o||(o=rp);let s=Object.assign({...o},r);ti.set(t,s)}},ni=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 ee("data-dog-metrics-transport",10,this.dispatchFunction,te.getLogger(t)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(ti.get(t)?.tags??[]);if(this.#o.country&&o.push(`country:${e.country}`),this.#o.httpMethod&&o.push(`httpMethod:${e.method}`),this.#o.statusCode&&o.push(`statusCode:${e.statusCode}`),this.#o.path){let s=e.systemRouteName||e.routePath;o.push(`path:${s}`)}this.#n.latency&&this.#i.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:r,value:e.durationMs}],tags:o}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:r,value:e.requestContentLength}],tags:o}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:r,value:e.responseContentLength}],tags:o}),t.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let t=JSON.stringify({series:e}),r=await F.fetch(this.#t,{method:"POST",body:t,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new ri(await r.text())}},ri=class n extends Error{static{i(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var oi=new WeakMap,op={dimensions:[]},ir=class extends Ye{constructor(t){super();this.options=t;f("metrics.dynatrace")}static{i(this,"DynatraceMetricsPlugin")}getTransport(){return new ii(this.options)}static setContext(t,r){let o=oi.get(t);o||(o=op);let s=Object.assign({...o},r);oi.set(t,s)}},ii=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 ee("dynatrace-metrics-transport",10,this.dispatchFunction,te.getLogger(t)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(oi.get(t)?.dimensions??[]);if(this.#n.country&&o.push(`country="${e.country}"`),this.#n.httpMethod&&o.push(`http_method="${e.method}"`),this.#n.statusCode&&o.push(`status_code="${e.statusCode}"`),this.#n.path){let a=e.systemRouteName||e.routePath;o.push(`path="${a}"`)}let s=o.join(",");this.#t.latency&&this.#r.enqueue(`zuplo.request.latency,${s} ${e.durationMs} ${r}`),this.#t.requestContentLength&&e.requestContentLength&&this.#r.enqueue(`zuplo.request.content_length,${s} ${e.requestContentLength} ${r}`),this.#t.responseContentLength&&e.responseContentLength&&this.#r.enqueue(`zuplo.response.content_length,${s} ${e.responseContentLength} ${r}`),t.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let t=e.join(`
62
+ `),r=await F.fetch(this.#e,{method:"POST",body:t,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new si(await r.text())}},si=class n extends Error{static{i(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var sr=class{static{i(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e,f("audit-logs.datastax")}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async t=>{await F.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(t)})}))}};var ar=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 ai(e,this.#e,this.#t)}},$a=i(n=>{let e={};return n.forEach((t,r)=>{e[r]=t}),e},"serializableHeaders"),ip={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},ai=class{static{i(this,"AuditPluginImpl")}constructor(e,t,r){this.#t=t;let o={...ip};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 ee("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,t,r,o,s,a)=>{try{let u={timestamp:o,durationMs:s,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:t.url,method:t.method,headers:this.#e.include?.request?.headers?$a(t.headers):void 0,body:this.#e.include?.request?.body?await t.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?$a(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(u),r.waitUntil(this.#n.waitUntilFlushed())}catch(u){r.log.error(u)}};#i=async(e,t)=>{try{if(!await this.#e.requestFilter(e,t))return e;let o=new Date,s=Date.now(),a=e.clone();return t.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#o(d,a,t,o,l-s,c.user?.sub).catch(h=>{t.log.error(h)});t.waitUntil(p)}),e}catch(r){return t.log.error(r),e}}};var ui=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}},Ze=class extends ui{static{i(this,"StripeSignatureVerificationError")}header;payload;constructor(e,t,r={}){super(r),this.header=e,this.payload=t}};var sp="v1",ap=300;async function ja(n,e,t,r=ap,o){return await cp(n,e,t,r,o),n instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(n)):JSON.parse(n)}i(ja,"constructEventAsync");function up(n,e){return`${e.timestamp}.${n}`}i(up,"makeHMACContent");async function cp(n,e,t,r,o){let{decodedHeader:s,decodedPayload:a,details:u,suspectPayloadType:c}=lp(n,e,sp),l=/\s/.test(t),d=await gp(up(a,u),t);return dp(a,s,u,d,r,c,l,o)}i(cp,"verifyHeaderAsync");function lp(n,e,t){if(!n)throw new Ze(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 Ze(e,n,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=pp(a,t);if(!u||u.timestamp===-1)throw new Ze(a,s,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new Ze(a,s,{message:"No signatures found with expected scheme"});return{decodedPayload:s,decodedHeader:a,details:u,suspectPayloadType:r}}i(lp,"parseEventDetails");function dp(n,e,t,r,o,s,a,u){let c=!!t.signatures.filter(h=>mp(h,r)).length,l=`
63
63
  Learn more about webhook signing and explore webhook integration examples for various frameworks at https://github.com/stripe/stripe-node#webhook-signing`,d=a?`
64
64
 
65
65
  Note: The provided signing secret contains whitespace. This often indicates an extra newline or space is in the value`:"";if(!c)throw s?new Ze(e,n,{message:`Webhook payload must be provided as a string or a Buffer (https://nodejs.org/api/buffer.html) instance representing the _raw_ request body.Payload was provided as a parsed JavaScript object instead.
@@ -68,8 +68,9 @@ Signature verification is impossible without access to the original signed mater
68
68
  `+d}):new Ze(e,n,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
69
69
  If a webhook request is being forwarded by a third-party tool, ensure that the exact request body, including JSON formatting and new line style, is preserved.
70
70
  `+l+`
71
- `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new Ze(e,n,{message:"Timestamp outside the tolerance zone"});return!0}i(pp,"validateComputedSignature");function mp(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(mp,"parseHeader");function gp(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(gp,"secureCompare");async function fp(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(fp,"computeHMACSignatureAsync");var pi=new Array(256);for(let n=0;n<pi.length;n++)pi[n]=n.toString(16).padStart(2,"0");function ee(n,e,t="policy",r){let o=`${t} '${e}'`;if(!at(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],h=r?`${r}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new g(`Value of '${h}' on ${o} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"&&Array.isArray(p))throw new g(`Value of '${h}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new g(`Value of '${h}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new g(`Value of '${h}' on ${o} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof p=="number"&&isNaN(p))throw new g(`Value of '${h}' on ${o} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=i((c,l)=>(s(c,l,!0),{optional:a,required:u}),"optional"),u=i((c,l)=>(s(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}i(ee,"optionValidator");var Ot=class extends de{static{i(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),f("policy.inbound.stripe-webhook-verification")}async handler(e,t){ee(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 ja(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 za(n){return n!==null&&typeof n=="object"&&"id"in n&&ve(n.id)&&"type"in n&&ve(n.type)}i(za,"isStripeWebhookEvent");var hp={getSubscription:async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving subscription from Stripe API.";throw t.error(s,o),new A(s)}return o},getCustomer:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer from Stripe API.";throw t.error(s,o),new A(s)}return o},getUpcomingInvoice:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(s,o),new A(s)}return o}},ar=hp;var mi="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Ba="My API Key";async function Ga({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=m.instance,c=new URL(`/v1/buckets/${n}/consumers`,mi);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Ba,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await be({retryDelayMs:5,retries:2,logger:te.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),h=await p.json();if(p.status!==200){let y="Error creating API Key Consumer";throw a.log.error(y,h),new A(y)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(Ga,"createConsumer");async function Va({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=m.instance,u=new URL(`/v1/buckets/${n}/consumers`,mi);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:Ba,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await be({retryDelayMs:5,retries:2,logger:te.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let h="Error creating API Key Consumer";throw s.log.error(h,p),new A(h)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(Va,"createConsumerInvite");async function Wa({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=m.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,mi);o.searchParams.set("with-api-key","true");let s=await be({retryDelayMs:5,retries:2,logger:te.getLogger(t)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new A(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(Wa,"deleteConsumer");async function Ka({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:r,meteringBucketId:o,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[t],customerKey:r,customerExternalId:a,metadata:c,trialEndDate:l?l.trialEndDate:void 0,trialStartDate:l?l.trialStartDate:void 0,trialEndStatus:l?l.trialEndStatus:void 0},{authApiJWT:p,meteringServiceUrl:h}=m.instance;if(!bt(p))throw new Y("No Zuplo JWT token set.");let y=await be({retryDelayMs:5,retries:2,logger:te.getLogger(n)},`${h}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!y.ok){let _=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,P,C="";try{P=await y.json(),C=P.detail??P.title}catch{P={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:y.status,detail:y.statusText}}throw n.log.error(_,P),new A(`${_} ${C}`)}n.log.info("Successfully created monetization subscription.",d)}i(Ka,"createSubscription");async function Ct({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=m.instance;if(!bt(o))throw new Y("No Zuplo JWT token set.");let a=await be({retryDelayMs:5,retries:2,logger:te.getLogger(n)},`${s}/internal/v1/metering/${t}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Unable to update monetization subscription with: '${JSON.stringify(r)}'.`,c,l="";try{c=await a.json(),l=c.detail??c.title}catch{c={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(u,c),new A(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}i(Ct,"updateSubscription");async function St({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=m.instance;if(!bt(o))throw new Y("No Zuplo JWT token set.");let a=await be({retryDelayMs:5,retries:2,logger:te.getLogger(n)},`${s}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":n.requestId},method:"GET"});if(!a.ok){let c=`Unable to retrieve the monetization subscription for Stripe subscription '${e}'.`,l,d="";try{l=await a.json(),d=l.detail??l.title}catch{l={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(c,l),new A(`${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 A(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 A(c)}return u.data[0]}i(St,"getSubscription");var ae="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 ur(n){return n.replaceAll("_","-")}i(ur,"stripeStatusToMeteringStatus");function dt(n){return new Date(n*1e3).toISOString()}i(dt,"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:ae,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:ae,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:ae,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!==m.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:ae,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 Ga({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await ar.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),T.ok(n,e,{title:ae,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Va({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:ae,detail:p.message})}if(!c)return T.ok(n,e,{title:ae,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=ur(t.data.object.status),h;l&&d&&(h={subscriber:{sub:d,email:l}});let y;t.data.object.trial_end!==null&&t.data.object.trial_start!==null&&t.data.object.trial_settings&&t.data.object.trial_settings.end_behavior&&(t.data.object.trial_settings.end_behavior.missing_payment_method==="cancel"||t.data.object.trial_settings.end_behavior.missing_payment_method==="pause")&&(y={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:dt(t.data.object.trial_end),trialStartDate:dt(t.data.object.trial_start)}),await Ka({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:h,trial:y})}catch(p){return await Wa({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),T.ok(n,e,{title:ae,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:ae,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:ae,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!==m.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:ae,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 St({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});await Ct({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return T.ok(n,e,{title:ae,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:ae,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:ae,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!==m.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:ae,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 St({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=ur(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=dt(t.data.object.trial_end)),await Ct({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return T.ok(n,e,{title:ae,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 St({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await ar.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(h=>h.proration&&h.price.product===c),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${t.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await Ct({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return T.ok(n,e,{title:ae,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 St({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?dt(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?dt(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await Ct({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:ae,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:ae,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 yi=class extends Rn{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(Ee.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Ee.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(Ee.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=Ee.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new g("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!m.instance.build.ACCOUNT_NAME)throw new Y("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let h=this.options.primaryDataRegion??"us-central1";if(!yp(h))throw new g(`StripeMonetizationPlugin - The value '${h}' on the property 'primaryDataRegion' is invalid.`);let y=await c.json();if(!za(y))return T.ok(c,l,{title:ae,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 '${y.type}' with ID '${y.id}'.`),y.type){case"customer.subscription.created":return await gi(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await hi(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await fi(c,l,y,{meteringBucketId:d});default:return T.ok(c,l,{title:ae,detail:`Event '${y.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+xe})}},"stripeWebhookHandler"),s=Xs({inboundPolicies:[new Ot({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});ee(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new fe({processors:[Ie,s],handler:o,gateway:r}),u=new le({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function yp(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}i(yp,"isMetricsRegion");var Ya=new WeakMap,Ja={},cr=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){Ya.set(e,t)}};async function Xa(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=wt(t.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=Ya.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new A(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=ut(n.user,t.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??t.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??t.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(t.dimensions??{},a?.dimensions)},h=Ja[t.apiKey];if(!h){let y=t.apiKey,_=n.headers.get("zm-test-id")??"";h=new Q("amberflo-ingest-meter",10,async P=>{try{let C=t.url??"https://app.amberflo.io/ingest",H=await F.fetch(C,{method:"POST",body:JSON.stringify(P),headers:{"content-type":"application/json","x-api-key":y,"zm-test-id":_}});H.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${H.status}: ${await H.text()}`)}catch(C){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${C.message}`),C}}),Ja[y]=h}h.enqueue(p),e.waitUntil(h.waitUntilFlushed())}}),n}i(Xa,"AmberfloMeteringInboundPolicy");async function lr(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(t)].map(o=>o.toString(16).padStart(2,"0")).join("")}i(lr,"sha256");var Qa=new Map;async function ue(n,e,t){let r,o=`${n}-${e}`,s=Qa.get(o);return s!==void 0?r=s:(r=`zuplo-policy-${await lr(JSON.stringify({policyName:n,options:t}))}`,Qa.set(n,r)),r}i(ue,"getPolicyCacheName");var eu="key-metadata-cache-type";function bp(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}i(bp,"getKeyValue");async function dr(n,e,t,r){if(f("policy.inbound.api-key"),!t.bucketName)if(Ee.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=Ee.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(C=>o.allowUnauthenticatedRequests?n:T.unauthorized(n,e,{detail:C}),"unauthorizedResponse"),a=n.headers.get(o.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=bp(a,o);if(!u||u==="")return s("No key present");let c=await wp(u),l=await ue(r,void 0,o),d=new se(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!==eu&&te.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let h={key:u},y=await be({retryDelayMs:5,retries:2,logger:te.getLogger(e)},`${m.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":m.instance.deploymentName??"unknown","User-Agent":m.instance.systemUserAgent},body:JSON.stringify(h)});if(y.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(y.status!==200){try{let C=await y.text(),H=JSON.parse(C);e.log.error("Unexpected response from key service",H)}catch{e.log.error("Invalid response from key service")}throw new A(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${y.status}`)}let _=await y.json(),P={isValid:!0,typeId:eu,user:{sub:_.name,data:_.metadata}};return n.user=P.user,d.put(c,P,o.cacheTtlSeconds),n}i(dr,"ApiKeyInboundPolicy");async function wp(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(wp,"hashValue");var tu=dr;var an=require("jose");var nu=require("jose");var bi=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 wi&&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",m.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=(0,nu.createLocalJWKSet)(t),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(t=>{throw this.pendingFetch=void 0,t}),await this.pendingFetch}async fetchJwks(e,t,r){let o=await this.cache.get(this.url.href);if(o)return o;let s,a,u=!1;typeof AbortController=="function"&&(s=new AbortController,a=setTimeout(()=>{u=!0,s.abort()},t));let c=await F.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new Ri("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new At("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 At("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function ru(n,e,t){let r=new bi(n,e,t);return async(o,s)=>r.getKey(o,s)}i(ru,"createRemoteJWKSet");var At=class extends A{static{i(this,"JWKSError")}},wi=class extends At{static{i(this,"JWKSNoMatchingKey")}},Ri=class extends At{static{i(this,"JWKSTimeout")}};var pr={},Rp=i((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new g("Invalid State - jwkUrl not set");if(!pr[r.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(s=r.useExperimentalInMemoryCache),s){let a=await ue(n,void 0,r),u=new se(a,e);pr[r.jwkUrl]=ru(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else pr[r.jwkUrl]=(0,an.createRemoteJWKSet)(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await(0,an.jwtVerify)(t,pr[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),Pp=i(async(n,e)=>{let t;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);t=new Uint8Array(s)}else t=e.secret;let{payload:r}=await(0,an.jwtVerify)(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),we=i(async(n,e,t,r)=>{f("policy.inbound.open-id-jwt-auth");let o=n.headers.get("Authorization"),s="bearer ",a=i(h=>T.unauthorized(n,e,{detail:h}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new 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 u=t.jwkUrl?Rp(r,e):Pp,l=await i(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let h=o.substring(s.length);if(!h||h.length===0)return a("No bearer token on authorization header");try{return await u(h,t)}catch(y){let _=new URL(n.url);return"code"in y&&y.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${_.pathname} `,y):e.log.warn(`Invalid token on: ${n.method} ${_.pathname}`,y),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return t.allowUnauthenticatedRequests===!0?n:l;let d=t.subPropertyName??"sub",p=l[d];return p?(n.user={sub:p,data:l},n):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var ou=i(async(n,e,t,r)=>(f("policy.inbound.auth0-jwt-auth"),we(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"Auth0JwtInboundPolicy");var mr=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 F.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!t.ok)throw new Error(`Request to PDP service failed with response status ${t.status}.`);return await t.json()}};var gr=class n extends de{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"),ee(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new mr(e)}async handler(e,t){let r=i(a=>this.options.allowUnauthorizedRequests?e: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 iu=i(async(n,e,t)=>{f("policy.inbound.basic-auth");let r=n.headers.get("Authorization"),o="basic ",s=i(l=>T.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!r)return await s("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await s("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let h=d.substring(0,p),y=d.substring(p+1),_=t.accounts.find(P=>P.username===h&&P.password===y);return _||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return t.allowUnauthenticatedRequests?n:u;let c=u.username;return n.user={sub:c,data:u.data},n},"BasicAuthInboundPolicy");function fr(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}i(fr,"extractDateElements");function su(n,e){return new Date(n,e+1,0).getDate()}i(su,"getDaysInMonth");function Pi(n,e){return n<=e?e-n:6-n+e+1}i(Pi,"getDaysBetweenWeekdays");var hr=class{static{i(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:r,days:o,months:s,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!t||t.size===0)throw new Error("There must be at least one allowed minute.");if(!r||r.size===0)throw new Error("There must be at least one allowed hour.");if(!s||s.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!o||o.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((c,l)=>c-l),this.minutes=Array.from(t).sort((c,l)=>c-l),this.hours=Array.from(r).sort((c,l)=>c-l),this.days=Array.from(o).sort((c,l)=>c-l),this.months=Array.from(s).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=i((c,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${c} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");u("seconds",this.seconds,{min:0,max:59}),u("minutes",this.minutes,{min:0,max:59}),u("hours",this.hours,{min:0,max:23}),u("days",this.days,{min:1,max:31}),u("months",this.months,{min:0,max:11}),u("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(c=>c).reverse(),minutes:this.minutes.map(c=>c).reverse(),hours:this.hours.map(c=>c).reverse(),days:this.days.map(c=>c).reverse(),months:this.months.map(c=>c).reverse(),weekdays:this.weekdays.map(c=>c).reverse()}}findAllowedHour(e,t){return e==="next"?this.hours.find(r=>r>=t):this.reversed.hours.find(r=>r<=t)}findAllowedMinute(e,t){return e==="next"?this.minutes.find(r=>r>=t):this.reversed.minutes.find(r=>r<=t)}findAllowedSecond(e,t){return e==="next"?this.seconds.find(r=>r>t):this.reversed.seconds.find(r=>r<t)}findAllowedTime(e,t){let r=this.findAllowedHour(e,t.hour);if(r!==void 0)if(r===t.hour){let o=this.findAllowedMinute(e,t.minute);if(o!==void 0)if(o===t.minute){let s=this.findAllowedSecond(e,t.second);if(s!==void 0)return{hour:r,minute:o,second:s};if(o=this.findAllowedMinute(e,e==="next"?t.minute+1:t.minute-1),o!==void 0)return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(r=this.findAllowedHour(e,e==="next"?t.hour+1:t.hour-1),r!==void 0)return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,t,r,o){if(o<1)throw new Error("startDay must not be smaller than 1.");let s=su(t,r),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return o>s?e==="next"?void 0:s:o;let c;a&&(c=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),c!==void 0&&c>s&&(c=void 0));let l;if(u){let d=new Date(t,r,o).getDay(),p=e==="next"?this.weekdays.find(h=>h>=d)??this.weekdays[0]:this.reversed.weekdays.find(h=>h<=d)??this.reversed.weekdays[0];if(p!==void 0){let h=e==="next"?Pi(d,p):Pi(p,d);l=e==="next"?o+h:o-h,(l>s||l<1)&&(l=void 0)}}if(c!==void 0&&l!==void 0)return e==="next"?Math.min(c,l):Math.max(c,l);if(c!==void 0)return c;if(l!==void 0)return l}getNextDate(e=new Date){let t=fr(e),r=t.year,o=this.months.findIndex(a=>a>=t.month);o===-1&&(o=0,r++);let s=this.months.length*5;for(let a=0;a<s;a++){let u=r+Math.floor((o+a)/this.months.length),c=this.months[(o+a)%this.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("next",u,c,l?t.day:1),p=l&&d===t.day;if(d!==void 0&&p){let h=this.findAllowedTime("next",t);if(h!==void 0)return new Date(u,c,d,h.hour,h.minute,h.second);d=this.findAllowedDayInMonth("next",u,c,d+1),p=!1}if(d!==void 0&&!p)return new Date(u,c,d,this.hours[0],this.minutes[0],this.seconds[0])}throw new Error("No valid next date was found.")}getNextDates(e,t){let r=[],o;for(let s=0;s<e;s++)o=this.getNextDate(o??t),r.push(o);return r}*getNextDatesIterator(e,t){let r;for(;;){if(r=this.getNextDate(e),e=r,t&&t.getTime()<r.getTime())return;yield r}}getPrevDate(e=new Date){let t=fr(e),r=t.year,o=this.reversed.months.findIndex(a=>a<=t.month);o===-1&&(o=0,r--);let s=this.reversed.months.length*5;for(let a=0;a<s;a++){let u=r-Math.floor((o+a)/this.reversed.months.length),c=this.reversed.months[(o+a)%this.reversed.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("prev",u,c,l?t.day:31),p=l&&d===t.day;if(d!==void 0&&p){let h=this.findAllowedTime("prev",t);if(h!==void 0)return new Date(u,c,d,h.hour,h.minute,h.second);d>1&&(d=this.findAllowedDayInMonth("prev",u,c,d-1),p=!1)}if(d!==void 0&&!p)return new Date(u,c,d,this.reversed.hours[0],this.reversed.minutes[0],this.reversed.seconds[0])}throw new Error("No valid previous date was found.")}getPrevDates(e,t){let r=[],o;for(let s=0;s<e;s++)o=this.getPrevDate(o??t),r.push(o);return r}*getPrevDatesIterator(e,t){let r;for(;;){if(r=this.getPrevDate(e),e=r,t&&t.getTime()>r.getTime())return;yield r}}matchDate(e){let{second:t,minute:r,hour:o,day:s,month:a,weekday:u}=fr(e);return this.seconds.indexOf(t)===-1||this.minutes.indexOf(r)===-1||this.hours.indexOf(o)===-1||this.months.indexOf(a)===-1?!1:this.days.length!==31&&this.weekdays.length!==7?this.days.indexOf(s)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(s)!==-1&&this.weekdays.indexOf(u)!==-1}};var Ip={min:0,max:59},Ep={min:0,max:59},Tp={min:0,max:23},xp={min:1,max:31},vp={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"}},Op={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},Cp={"@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 pt(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=>{pt(d,e).forEach(h=>t.add(h))}),t;let o=i(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${n}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${n}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),s=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(s===null)return t.add(o(n)),t;let a=s[1]==="*"?e.min:o(s[3]),u=s[1]==="*"?e.max:o(s[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=s[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}i(pt,"parseElement");function Ii(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=Cp[n.toLowerCase()]??n;let e=n.split(" ");if(e.length<5||e.length>6)throw new Error("Invalid cron expression: expected 5 or 6 elements.");let t=e.length===6?e[0]:"0",r=e.length===6?e[1]:e[0],o=e.length===6?e[2]:e[1],s=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],u=e.length===6?e[5]:e[4];return new hr({seconds:pt(t,Ip),minutes:pt(r,Ep),hours:pt(o,Tp),days:pt(s,xp),months:new Set(Array.from(pt(a,vp)).map(c=>c-1)),weekdays:new Set(Array.from(pt(u,Op)).map(c=>c%7))})}i(Ii,"parseCronExpression");var yr=class extends de{static{i(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),f("policy.inbound.brownout"),ee(e,t).optional("problem","object"),e.problem&&ee(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=[Ii(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>Ii(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 Sp=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Ap(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(Ap,"digestMessage");var _p=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 Ap(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 au(n,e,t,r){f("policy.inbound.caching");let o=await ue(r,t.cacheId,t),s=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await _p(n,t),c=await s.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=t.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(n.method.toUpperCase()))return;let h=t?.expirationSecondsTtl??60,y=new Response(p.body,p);Sp.forEach(_=>y.headers.delete(_)),y.headers.set("cache-control",`s-maxage=${h}`),e.waitUntil(s.put(u,y))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}i(au,"CachingInboundPolicy");var uu=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 oe(n,{method:t.method})},"ChangeMethodInboundPolicy");var cu=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 oe(n,{headers:o})},"ClearHeadersInboundPolicy");var lu=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 du=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",we(n,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var pu=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 we(n,e,{issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,jwkUrl:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var hu=Be(qe());var br=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},Ei=class extends br{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Ti=class extends br{static{i(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function Lp(n,e){if(Gs(n))throw new Ei(e)}i(Lp,"throwIfUndefinedOrNull");function un(n,e){if(Lp(n,e),!ve(n))throw new Ti(e,"string")}i(un,"throwIfNotString");var wr=class n{static{i(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,t,r,o){this.redisClientUrl=e,this.clientAuthToken=t,this.deploymentName=r,this.userAgent=o}static initialize(e,t,r,o){return un(e,"redisClientUrl"),un(t,"clientAuthToken"),n.instance||(n.instance=new n(e,t,r,o)),n.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:t,method:r,requestId:o}){un(e,"url");let s=await F.fetch(`${this.redisClientUrl}${e}`,{method:r,body:t,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=s.headers.get("Content-Type")?.includes("application/json")?await s.json():await s.text();if(s.ok)return a;throw s.status===401?new Y("Rate limiting service failed with 401: Unauthorized"):new Y(`Rate limiting service failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},Rr=class{static{i(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:t,method:r}){if(un(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:s,key:a}=JSON.parse(t),u=Date.now()+s*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new Y("The in-memory rate limit client does not support this request")}};var kp=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 _t(n,e){return{function:Up(e,"RateLimitInboundPolicy",n),user:Mp,ip:Np,all:Dp}[e.rateLimitBy??"ip"]}i(_t,"getRateLimitByFunctions");var Np=i(async n=>({key:`ip-${kp(n)}`}),"getIP"),Mp=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),Dp=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Pr;function Lt(n,e){let t;if(Pr)return Pr;if(!m.instance.authApiJWT)return e.info("Using in-memory rate limit client for local development."),t=new Rr,Pr=t,t;let{authApiJWT:r,redisURL:o}=m.instance;if(!ve(o))throw new Y(`RateLimitClient used in policy '${n}' - rate limit service URL not configured`);if(!ve(r))throw new Y(`RateLimitClient used in policy '${n}' - service authentication not configured`);if(o&&(t=wr.initialize(o,r,m.instance.deploymentName??"unknown",m.instance.systemUserAgent)),!t||!t.isEnabled())throw new Y(`RateLimitClient used in policy '${n}' - no remote rate limiting service enabled`);return Pr=t,t}i(Lt,"getRedisClient");async function Ir(n,e,t,r){let o=Math.floor(e*60);return await t.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:o,key:n}),requestId:r})}i(Ir,"getCountAndUpdateExpiry");async function mu(n,e,t){return(await e.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:n}),requestId:t})).data}i(mu,"multiCount");async function gu(n,e,t){return(await e.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:n}),requestId:t})).data}i(gu,"multiIncrement");function Up(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 A(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 A(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 A(l)}return c},"outerFunction")}i(Up,"wrapUserFunction");var kt="Retry-After";var fu=(0,hu.debug)("zuplo:policies:ComplexRateLimitInboundPolicy"),xi=Symbol("complex-rate-limit-counters"),Er=class n extends de{static{i(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let r=he.get(e,xi)??{};Object.assign(r,t),he.set(e,xi,t)}static getIncrements(e){return he.get(e,xi)??{}}constructor(e,t){super(e,t),f("policy.inbound.complex-rate-limit-inbound"),ee(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&&ee(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=te.getLogger(t),s=Lt(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[kt]=l.toString()),T.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l=await _t(this.policyName,this.options)(e,t,this.policyName),d=m.instance.isTestMode||m.instance.isWorkingCopy?m.instance.build.BUILD_ID:"",p=Object.assign({},this.options.limits,l.limits),h=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;t.addResponseSendingFinalHook(async()=>{try{let C=n.getIncrements(t);fu(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(C)}`);let H=Object.entries(p).map(([z])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${z}`,ttlSeconds:h,increment:C[z]??0})),N=gu(H,s,t.requestId);t.waitUntil(N),await N}catch(C){t.log.error(C)}});let y=Object.entries(p).map(([C,H])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${C}`,ttlSeconds:h,limit:H})),_=await mu(y,s,t.requestId);return Hp(_,y).length>0?u(this.options.headerMode??"retry-after",h):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-r;fu(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function Hp(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(Hp,"findOverLimits");var yu=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=Re.instance,s=Xt(t.policies,o?.routeData.policies);return Lo(s)(n,e)},"CompositeInboundPolicy");var bu=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=Zp(o);if(!s)return T.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await ue(r,void 0,t),u=new se(a,e),c=await u.get(s);if(!c){let l=await F.fetch(t.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${t.clientId}:${t.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(s,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),T.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):T.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function Zp(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(Zp,"getToken");var wu=i(async(n,e,t,r)=>(f("policy.inbound.firebase-jwt-auth"),ee(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),we(n,e,{issuer:`https://securetoken.google.com/${t.projectId}`,audience:t.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var Ru=i(async(n,e,t)=>{f("policy.inbound.form-data-to-json");let r="application/x-www-form-urlencoded",o="multipart/form-data",s=n.headers.get("content-type")?.toLowerCase();if(!s||![o,r].includes(s))return t&&t.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):n;let a=await n.formData();if(t&&t.optionalHoneypotName&&a.get(t.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(n.headers);return c.set("content-type","application/json"),c.delete("content-length"),new oe(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var Nt="__unknown__",Pu=i(async(n,e,t,r)=>{f("policy.inbound.geo-filter");let o={allow:{countries:Dt(t.allow?.countries,"allow.countries",r),regionCodes:Dt(t.allow?.regionCodes,"allow.regionCode",r),asns:Dt(t.allow?.asns,"allow.asOrganization",r)},block:{countries:Dt(t.block?.countries,"block.countries",r),regionCodes:Dt(t.block?.regionCodes,"block.regionCode",r),asns:Dt(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??Nt,a=e.incomingRequestProperties.regionCode?.toLowerCase()??Nt,u=e.incomingRequestProperties.asn?.toString()??Nt,c=o.ignoreUnknown&&s===Nt,l=o.ignoreUnknown&&a===Nt,d=o.ignoreUnknown&&u===Nt,p=o.allow.countries,h=o.allow.regionCodes,y=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||h.length>0&&!h.includes(a)&&!l||y.length>0&&!y.includes(u)&&!d)return Mt(n,e,r,s,a,u);let _=o.block.countries,P=o.block.regionCodes,C=o.block.asns;return _.length>0&&_.includes(s)&&!c||P.length>0&&P.includes(a)&&!l||C.length>0&&C.includes(u)&&!d?Mt(n,e,r,s,a,u):n},"GeoFilterInboundPolicy");function Mt(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(Mt,"blockedResponse");function Dt(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(Dt,"toLowerStringArray");var Iu=i(async(n,e,t)=>{f("policy.inbound.jwt-scope-validation");let r=n.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(r,t.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var Tu=i(async(n,e,t,r)=>{f("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return vi(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 vi(r,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(h=>{a.push({responseName:u,contentName:l,exampleName:h,exampleValue:d[h]})})})}),a=a.filter(u=>!(t.responsePrefixFilter&&!u.responseName.startsWith(t.responsePrefixFilter)||t.contentType&&u.contentName!==t.contentType||t.exampleName&&u.exampleName!==t.exampleName)),t.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return Eu(a[u])}else return a.length>0?Eu(a[0]):vi(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 Eu(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(Eu,"generateResponse");var vi=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 qp="Incoming",Fp={logRequestBody:!0,logResponseBody:!0};function xu(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}i(xu,"headersToObject");function vu(){return new Date().toISOString()}i(vu,"timestamp");var Oi=new WeakMap,$p={};function Su(n,e){let t=Oi.get(n);t||(t=$p);let r=Object.assign({...t},e);Oi.set(n,r)}i(Su,"setMoesifContext");async function Ou(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(Ou,"readBody");var jp={},Ci;function Cu(){if(!Ci)throw new A("Invalid State - no _lastLogger");return Ci}i(Cu,"getLastLogger");function zp(n){let e=jp[n];return e||(e=new Q("moesif-inbound",100,async t=>{let r=JSON.stringify(t);Cu().debug("posting",r);let o=await F.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||Cu().error({status:o.status,body:await o.text()})})),e}i(zp,"getDispatcher");async function Au(n,e,t,r){f("policy.inbound.moesif-analytics"),Ci=e.log;let o=vu(),s=Object.assign(Fp,t);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await Ou(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=zp(s.applicationId),d=n.headers.get("true-client-ip"),p=Oi.get(e)??{},h={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:xu(n.headers)},y=s.logResponseBody?await Ou(u,e):void 0,_={time:vu(),status:u.status,headers:xu(u.headers),body:y},P={request:h,response:_,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:qp};l.enqueue(P),e.waitUntil(l.waitUntilFlushed())}),n}i(Au,"MoesifInboundPolicy");async function _u(n,e,t,r){let o=te.getLogger(n),{authApiJWT:s,meteringServiceUrl:a}=m.instance,u;try{let l=await F.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription`,l)}let c=u&&u.data&&u.data.length>0?u.data:void 0;return c&&c.length>1?c.sort((d,p)=>d.createdOn>p.createdOn?-1:1)[0]:c&&c[0]}i(_u,"loadSubscription");async function Lu(n,e,t,r,o){let{authApiJWT:s,meteringServiceUrl:a}=m.instance,u=te.getLogger(n);try{let c=await F.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`,c)}}i(Lu,"consumeSubcriptionQuotas");var Bp=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function Tr(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(Tr,"validateMeters");function ku(n,e){if(n)try{if(n.length===0)throw new g("Must set valid subscription statuses");let t=ct(n),r=[];for(let o of t)Bp.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(ku,"parseAllowedSubscriptionStatuses");function Nu(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(Nu,"compareMeters");var xr=class extends de{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return he.get(e,Bt)}static setMeters(e,t){Tr(t,"setMeters"),he.set(e,wn,t)}constructor(e,t){super(e,t),f("policy.inbound.monetization")}async handler(e,t){ee(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=wt(this.options.meterOnStatusCodes),s=he.get(t,wn),a={...this.options.meters,...s};Tr(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=ku(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(P,C,H)=>{let N=he.get(H,Bt);if((this.options.allowRequestsWithoutSubscription??!1)&&!N){H.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(Ee.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Ee.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let q=he.get(H,wn),j={...this.options.meters,...q};if(Tr(j,this.policyName),o.includes(P.status)&&N&&j){H.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${N.id}' with meters '${JSON.stringify(j)} on response status '${P.status}'`);let{metersInSubscription:E,metersNotInSubscription:U}=Nu(N.meters,j);if(U&&Object.keys(U).length>0){let V=Object.keys(U);H.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${V}'`)}await Lu(H,N.id,this.policyName,this.options.bucketId,E)}});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(Ee.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Ee.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await _u(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`),he.set(t,Bt,p));let h=he.get(t,Bt);if(!h)return u?e:(t.log.warn("Subscription is not available for user"),T.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(h&&Object.keys(h.meters).length===0)return t.log.error(`Quota is not set up for subscription '${h.id}'`),T.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let _=Object.keys(a).filter(P=>!Object.keys(h.meters).includes(P));if(_.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${_.join(", ")}`),T.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${_.join(", ")}`,title:"Quota Exceeded"});for(let P of Object.keys(a))if(h.meters[P].available<=0&&!r)return T.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${P}'`,title:"Quota Exceeded"});return e}};async function vr(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 be({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 A("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 A("Response returned from identity provider is not in the expected format.")}i(vr,"getClientCredentialsAccessToken");var Ut=class extends Error{constructor(t,r,o){super(r,o);this.code=t}static{i(this,"OpenFGAError")}},Or=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 Error("storeId is required");return r}getAuthorizationModelId(e={}){return e?.authorizationModelId||this.authorizationModelId}async get(e,t){return this.fetch(e,"GET",t)}async put(e,t,r){return this.fetch(e,"PUT",r,t)}post(e,t,r){return this.fetch(e,"POST",r,t)}async fetch(e,t,r,o){let s=new Headers(r.headers||{});s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.set("User-Agent",m.instance.systemUserAgent);let a=`${this.apiUrl}${e}`,u=new Request(a,{method:t,headers:s,body:o?JSON.stringify(o):void 0}),c=await F.fetch(u);if(c.status!==200){let l;try{l=await c.json()}catch{}throw!l||!l.code||!l.message?new Ut("unknown",`Unknown error. Status: ${c.status}`):new Ut(l.code,l.message)}return c.json()}};function cn(n,e,t){!n[e]&&t&&(n[e]=t)}i(cn,"setHeaderIfNotSet");var Mu="X-OpenFGA-Client-Method",Du="X-OpenFGA-Client-Bulk-Request-Id",ln=class extends Or{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,Mu,"BatchCheck"),cn(r,Du,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 Ut)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,Mu,"ListRelations"),cn(c,Du,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 Uu=Symbol("openfga-authz-context-data"),Ht=class extends de{static{i(this,"BaseOpenFGAAuthZInboundPolicy")}client;authorizer;cache;static setContextChecks(e,t){let r=Array.isArray(t)?t:[t];he.set(e,Uu,r)}constructor(e,t){if(super(e,t),ee(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")ee(e.credentials,t).required("clientId","string").required("clientSecret","string").required("oauthTokenEndpointUrl","string").optional("apiAudience","string");else if(e.credentials.method==="api-token")ee(e.credentials,t).required("token","string").optional("headerName","string").optional("headerValuePrefix","string");else if(e.credentials.method==="header")ee(e.credentials,t).optional("headerName","string");else if(e.credentials.method!=="none")throw new g(`${this.policyType} '${this.policyName}' - The 'credentials.type' option is invalid. It must be set to either 'none', 'api-token', 'client-credentials', or 'header'.`);this.authorizer=this.getAuthorizer(e.credentials),this.client=new ln({apiUrl:e.apiUrl,storeId:e.storeId,authorizationModelId:e.authorizationModelId})}async handler(e,t){if(!this.cache){let a=await ue(this.policyName,void 0,this.options);this.cache=new se(a,t)}let r=i(a=>this.options.allowUnauthorizedRequests?e:T.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=he.get(t,Uu);if(!o||o.length===0)throw new A(`${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 vr({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 A("Invalid state for credentials method is not valid. This should not happen.")}};var Hu=["us1","eu1","au1"],Cr=class extends Ht{static{i(this,"OktaFGAAuthZInboundPolicy")}constructor(e,t){if(!Hu.includes(e.region))throw new g(`OktaFGAAuthZInboundPolicy '${t}' - The 'region' option is invalid. Must be one of ${Hu.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 Zu=i(async(n,e,t,r)=>(f("policy.inbound.okta-jwt-auth"),we(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"OktaJwtInboundPolicy");var Sr=class extends Ht{static{i(this,"OpenFGAAuthZInboundPolicy")}constructor(e,t){super(e,t),f("policy.inbound.openfga-authz")}};var qu=require("jose");var Si,Fu=i(async(n,e,t,r)=>{if(f("policy.inbound.propel-auth-jwt-auth"),!Si)try{Si=await(0,qu.importSPKI)(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return we(n,e,{issuer:t.authUrl,secret:Si,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Gu=Be(qe());var ju=Be(qe());var $u=(0,ju.debug)("zuplo:policies:RateLimitInboundPolicy"),zu=i(async(n,e,t,r)=>{let o=te.getLogger(e),s=i((j,E)=>{let U={};return(!j||j==="retry-after")&&(U[kt]=E.toString()),T.tooManyRequests(n,e,void 0,U)},"rateLimited"),u=await _t(r,t)(n,e,r),c=u.key,l=u.requestsAllowed??t.requestsAllowed,d=u.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",h=Lt(r,o),_=`rate-limit${m.instance.isTestMode?m.instance.build.BUILD_ID:""}/${r}/${c}`,P=await ue(r,void 0,t),C=new se(P,e),H=Ir(_,d,h,e.requestId),N;i(async()=>{let j=await H;if(j.count>l){let E=Date.now()+j.ttlSeconds*1e3;C.put(_,E,j.ttlSeconds),$u(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${_}' (async mode)`),N=s(p,j.ttlSeconds)}},"asyncCheck")();let q=await C.get(_);if(q!==void 0&&q>Date.now()){$u(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${_}' (async mode)`);let j=Math.round((q-Date.now())/1e3);return s(p,j)}return e.addResponseSendingHook(async j=>N??j),n},"AsyncRateLimitInboundPolicyImpl");var Bu=(0,Gu.debug)("zuplo:policies:RateLimitInboundPolicy"),Gp="strict",Ai=i(async(n,e,t,r)=>{if(f("policy.inbound.rate-limit"),(t.mode??Gp)==="async")return zu(n,e,t,r);let s=Date.now(),a=te.getLogger(e),u=i((l,d)=>{if(t.throwOnFailure)throw new Y(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[kt]=d.toString()),T.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await _t(r,t)(n,e,r),p=d.key,h=d.requestsAllowed??t.requestsAllowed,y=d.timeWindowMinutes??t.timeWindowMinutes,_=t.headerMode??"retry-after",P=Lt(r,a),H=`rate-limit${m.instance.isTestMode||m.instance.isWorkingCopy?m.instance.build.BUILD_ID:""}/${r}/${p}`,N=await Ir(H,y,P,e.requestId);return N.count>h?(Bu(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${H}' (strict mode)`),c(_,N.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-s;Bu(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var _i;function Vu(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}i(Vu,"headersToNameValuePairs");function Vp(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}i(Vp,"queryToNameValueParis");function Wp(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}i(Wp,"parseIntOrUndefined");var Wu={};async function Ku(n,e,t,r){f("policy.inbound.readme-metrics");let o=new Date,s=Date.now();return _i||(_i={name:"zuplo",version:m.instance.build.ZUPLO_VERSION,comment:`zuplo/${m.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?ut(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?ut(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:m.instance.isWorkingCopy||m.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:_i,entries:[{startedDateTime:o.toISOString(),time:Date.now()-s,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:Vu(n.headers),queryString:Vp(n.query)},response:{status:a.status,statusText:a.statusText,headers:Vu(a.headers),content:{size:Wp(n.headers.get("content-length"))}}}]}}},d=Wu[t.apiKey];if(!d){let p=t.apiKey;d=new Q("readme-metering-inbound-policy",10,async h=>{try{let y=t.url??"https://metrics.readme.io/request",_=await F.fetch(y,{method:"POST",body:JSON.stringify(h),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});_.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${_.status}: '${await _.text()}'`)}catch(y){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${y.message}'`),y}}),Wu[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}i(Ku,"ReadmeMetricsInboundPolicy");var Ju=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 oe(n,{headers:s})},"RemoveHeadersInboundPolicy");var Yu=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 Xu=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 oe(s.toString(),n)},"RemoveQueryParamsInboundPolicy");var Qu=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 ec=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),tc=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?ec():s&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?ec():n},"RequestSizeLimitInboundPolicy");function nc(n,e,t){return`_${nt(n+"_"+e+"_"+t)}`}i(nc,"getRawOperationDataIdentifierName");function Ar(n,e,t,r){return`_${nt(n.toLowerCase())}_`+e.toLowerCase()+"_"+t.toLowerCase()+`_${r.toLowerCase()}`}i(Ar,"getIdForParameterSchema");function _r(n,e,t){return`_${nt(n.toLowerCase())}_`+e.toLowerCase()+`_rb_${nt(t.toLowerCase())}`}i(_r,"getIdForRequestBodySchema");function rc(n,e){return`_${nt(n)}__${nt(e)}`}i(rc,"getIdForRefSchema");function nt(n){let e=[];for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(n.charAt(t)):e.push("_")}return e.join("")}i(nt,"sanitizedIdentifierName");var Zt=i(n=>{let e=n.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),qt=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=Ar(t,r,o,c.name),p=Re.instance.schemaValidator[d],h=p(e[c.name]),y=Li(p.errors);h||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${y.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),ke=i((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),Ne=i(n=>n==="log-only"||n==="reject-and-log","shouldLog"),Me=i(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),Li=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 oc(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(y){let _=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,P=T.badRequest(e,n,{detail:`${_}, see errors property for more details`,errors:`${y}`});if(Ne(t.validateBody)&&ke(n,t.logLevel??"info",_,[r],y),Me(t.validateBody))return P}if(!e.headers.get("Content-Type")){let y=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,_=T.badRequest(e,n,{detail:y});return Ne(t.validateBody)&&ke(n,t.logLevel??"info",y,[r],[y]),Me(t.validateBody)?_:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=_r(n.route.path,e.method,o),u=Re.instance.schemaValidator[a];if(!u){let y=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,_=T.badRequest(e,n,{detail:y});return Ne(t.validateBody)&&ke(n,t.logLevel??"info",y,[r],[y]),Me(t.validateBody)?_:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Li(l),h=T.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(Ne(t.validateBody)&&ke(n,t.logLevel??"info",d,[r],p),Me(t.validateBody))return h}i(oc,"handleBodyValidation");function ic(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Zt(n),s=qt(o.filter(a=>a.location==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=T.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:s.errors});if(Ne(t.validateHeaders)&&ke(n,t.logLevel??"info",a,s.invalidValues,s.errors),Me(t.validateHeaders))return u}}i(ic,"handleHeadersValidation");function sc(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=Zt(n),o=qt(r.filter(s=>s.location==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let s="Path parameters validation failed",a=T.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(Ne(t.validatePathParameters)&&ke(n,t.logLevel??"info",s,o.invalidValues,o.errors),Me(t.validatePathParameters))return a}}i(sc,"handlePathParameterValidation");function ac(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=Zt(n),o=qt(r.filter(s=>s.location==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let s="Query parameters validation failed",a=T.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(Ne(t.validateQueryParameters)&&ke(n,t.logLevel??"info",s,o.invalidValues,o.errors),Me(t.validateQueryParameters))return a}}i(ac,"handleQueryParameterValidation");var ki=i(async(n,e,t)=>{f("policy.inbound.request-validation");let r=ac(e,n,t);if(r!==void 0||(r=sc(e,n,t),r!==void 0)||(r=ic(e,n,t),r!==void 0))return r;let o=await oc(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),uc=ki;var cc=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 lc=i(async(n,e,t)=>(f("policy.inbound.set-body"),new oe(n,{body:t.body})),"SetBodyInboundPolicy");var dc=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 oe(n,{headers:s})},"SetHeadersInboundPolicy");var pc=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 mc=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 oe(s.toString(),n)},"SetQueryParamsInboundPolicy");var gc=i(async(n,e,t,r,o)=>{if(f("policy.outbound.set-status"),!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(n.body,{headers:n.headers,status:r.status,statusText:r.statusText??n.statusText})},"SetStatusOutboundPolicy");var Kp=i(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),fc=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 Kp(t.sleepInMs),n},"SleepInboundPolicy");var hc=i(async(n,e,t,r)=>{f("policy.inbound.supabase-jwt-auth"),ee(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},s=await we(n,e,o,r);if(s instanceof Response)return s;if(!(s instanceof oe))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 A(`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 yc=i(async(n,e,t,r)=>{f("policy.inbound.upstream-azure-ad-service-auth"),ee(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await ue(r,void 0,t),s=new se(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 be({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 A("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 A("Response returned from Azure AD is not in the expected format.")}i(Jp,"getAccessToken");var bc="https://accounts.google.com/o/oauth2/token",Ni,wc=i(async(n,e,t,r)=>{f("policy.inbound.upstream-firebase-admin-auth"),ee(t,r).required("serviceAccountJson","string"),Ni||(Ni=await Oe.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 ue(r,void 0,t),a=new se(s,e),u=await a.get(r);if(!u){let c=await Ue({serviceAccount:Ni,audience:bc,payload:o}),l=await Un(bc,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new A("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 Yp="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Xp=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Mi,Rc=i(async(n,e,t,r)=>{if(f("policy.inbound.upstream-firebase-user-auth"),ee(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(Xp.indexOf(p)!==-1)throw new g(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}Mi||(Mi=await Oe.init(t.serviceAccountJson));let s=t.userId;if(!s&&!t.userIdPropertyPath){if(!n.user)throw new A("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 A(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=ut(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new A(`Unable to determine user from for the policy ${r}`);let a=await ue(r,void 0,t),u=new se(a,e),c={uid:s,claims:o},l=await lr(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await Ue({serviceAccount:Mi,audience:Yp,payload:c}),h=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,y=await la(h,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!y.idToken)throw new A("Invalid token response from Firebase");d=y.idToken,u.put(l,d,(y.expiresIn?parseInt(y.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var Ft=class{static{i(this,"ZuploServices")}static async getIDToken(e,t){let r=new se("0c13603a-a19f-4f03-a04a-50aa393f7ffa-zuplo-tokens",e),o=await ue("zuplo-token",void 0,t),s=await r.get(o);if(s)return s;let{authClientId:a,authClientSecret:u,developerApiUrl:c,zuploClientAuthBucketId:l}=m.instance;if(!a||!u)throw new A("Zuplo service authentication is not enabled for this deployment. Contact support assistance.");let d=await vr({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 Pc="workload-access-token",Ic="service-account-id-token",Lr=class extends de{static{i(this,"UpstreamGcpFederatedAuthInboundPolicy")}cacheName;normalizedWorkloadIdentityProvider;constructor(e,t){super(e,t),f("policy.inbound.upstream-gcp-federated-auth"),ee(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 ue(this.policyName,void 0,this.options));let r;this.options.useMemoryCacheOnly?r=new We(this.cacheName):r=new se(this.cacheName,t);let o=await r.get(Pc);if(!o){let a=`https://iam.googleapis.com/${this.normalizedWorkloadIdentityProvider}`,u=await Ft.getIDToken(t,{audience:a}),c=await ua(this.normalizedWorkloadIdentityProvider,u,{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!c.access_token||!c.expires_in)throw new A("Invalid token response from GCP");o=c.access_token,r.put(Pc,o,c.expires_in-(this.options.expirationOffsetSeconds??300))}let s=await r.get(Ic);if(!s){let a=await ca({serviceAccountEmailOrIdentifier:this.options.serviceAccountEmail,audience:this.options.audience,accessToken:o},{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!a.token)throw new A("Invalid token response from GCP");s=a.token,r.put(Ic,o,3600-(this.options.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${s}`),e}};var Di,Ec=i(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-jwt"),ee(t,r).required("audience","string").required("serviceAccountJson","string"),Di||(Di=await Oe.init(t.serviceAccountJson));let o=await Ue({serviceAccount:Di,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var Tc="https://www.googleapis.com/oauth2/v4/token",Ui,xc=i(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-service-auth"),ee(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Ui||(Ui=await Oe.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=ct(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 ue(r,void 0,t),a;t.useMemoryCacheOnly?a=new We(s):a=new se(s,e);let u=await a.get(r);if(!u){let c=await Ue({serviceAccount:Ui,audience:Tc,payload:o}),l=await Un(Tc,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new A("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new A("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var vc=i(async(n,e,t)=>{f("policy.inbound.validate-json-schema");let r=n.clone(),o;try{o=await r.json()}catch{return T.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator(o))return n;let{errors:a}=t.validator;if(!a)throw new 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 Oc=i(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=i((P,C)=>e(P,"name",{value:C,configurable:!0}),"__name"),o=i((P,C)=>i(function(){return C||(0,P[t(P)[0]])((C={exports:{}}).exports,C),C.exports},"__require"),"__commonJS"),s=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(P){var C={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(N,z){return z},attributeValueProcessor:function(N,z){return z},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(N,z,q){return N}},H=r(function(N){return Object.assign({},C,N)},"buildOptions");P.buildOptions=H,P.defaultOptions=C}}),a=o({"node_modules/fast-xml-parser/src/util.js"(P){"use strict";var C=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",H=C+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",N="["+C+"]["+H+"]*",z=new RegExp("^"+N+"$"),q=r(function(E,U){let V=[],W=U.exec(E);for(;W;){let O=[];O.startIndex=U.lastIndex-W[0].length;let x=W.length;for(let Z=0;Z<x;Z++)O.push(W[Z]);V.push(O),W=U.exec(E)}return V},"getAllMatches"),j=r(function(E){let U=z.exec(E);return!(U===null||typeof U>"u")},"isName");P.isExist=function(E){return typeof E<"u"},P.isEmptyObject=function(E){return Object.keys(E).length===0},P.merge=function(E,U,V){if(U){let W=Object.keys(U),O=W.length;for(let x=0;x<O;x++)V==="strict"?E[W[x]]=[U[W[x]]]:E[W[x]]=U[W[x]]}},P.getValue=function(E){return P.isExist(E)?E:""},P.isName=j,P.getAllMatches=q,P.nameRegexp=N}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(P,C){"use strict";var H=class{static{i(this,"XmlNode")}static{r(this,"XmlNode")}constructor(N){this.tagname=N,this.child=[],this[":@"]={}}add(N,z){N==="__proto__"&&(N="#__proto__"),this.child.push({[N]:z})}addChild(N){N.tagname==="__proto__"&&(N.tagname="#__proto__"),N[":@"]&&Object.keys(N[":@"]).length>0?this.child.push({[N.tagname]:N.child,":@":N[":@"]}):this.child.push({[N.tagname]:N.child})}};C.exports=H}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(P,C){var H=a();function N(O,x){let Z={};if(O[x+3]==="O"&&O[x+4]==="C"&&O[x+5]==="T"&&O[x+6]==="Y"&&O[x+7]==="P"&&O[x+8]==="E"){x=x+9;let me=1,X=!1,ne=!1,Se="";for(;x<O.length;x++)if(O[x]==="<"&&!ne){if(X&&j(O,x))x+=7,[entityName,val,x]=z(O,x+1),val.indexOf("&")===-1&&(Z[W(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(X&&E(O,x))x+=8;else if(X&&U(O,x))x+=8;else if(X&&V(O,x))x+=9;else if(q)ne=!0;else throw new Error("Invalid DOCTYPE");me++,Se=""}else if(O[x]===">"){if(ne?O[x-1]==="-"&&O[x-2]==="-"&&(ne=!1,me--):me--,me===0)break}else O[x]==="["?X=!0:Se+=O[x];if(me!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:Z,i:x}}i(N,"readDocType"),r(N,"readDocType");function z(O,x){let Z="";for(;x<O.length&&O[x]!=="'"&&O[x]!=='"';x++)Z+=O[x];if(Z=Z.trim(),Z.indexOf(" ")!==-1)throw new Error("External entites are not supported");let me=O[x++],X="";for(;x<O.length&&O[x]!==me;x++)X+=O[x];return[Z,X,x]}i(z,"readEntityExp"),r(z,"readEntityExp");function q(O,x){return O[x+1]==="!"&&O[x+2]==="-"&&O[x+3]==="-"}i(q,"isComment"),r(q,"isComment");function j(O,x){return O[x+1]==="!"&&O[x+2]==="E"&&O[x+3]==="N"&&O[x+4]==="T"&&O[x+5]==="I"&&O[x+6]==="T"&&O[x+7]==="Y"}i(j,"isEntity"),r(j,"isEntity");function E(O,x){return O[x+1]==="!"&&O[x+2]==="E"&&O[x+3]==="L"&&O[x+4]==="E"&&O[x+5]==="M"&&O[x+6]==="E"&&O[x+7]==="N"&&O[x+8]==="T"}i(E,"isElement"),r(E,"isElement");function U(O,x){return O[x+1]==="!"&&O[x+2]==="A"&&O[x+3]==="T"&&O[x+4]==="T"&&O[x+5]==="L"&&O[x+6]==="I"&&O[x+7]==="S"&&O[x+8]==="T"}i(U,"isAttlist"),r(U,"isAttlist");function V(O,x){return O[x+1]==="!"&&O[x+2]==="N"&&O[x+3]==="O"&&O[x+4]==="T"&&O[x+5]==="A"&&O[x+6]==="T"&&O[x+7]==="I"&&O[x+8]==="O"&&O[x+9]==="N"}i(V,"isNotation"),r(V,"isNotation");function W(O){if(H.isName(O))return O;throw new Error(`Invalid entity name ${O}`)}i(W,"validateEntityName"),r(W,"validateEntityName"),C.exports=N}}),l=o({"../../node_modules/strnum/strnum.js"(P,C){var H=/^[-+]?0x[a-fA-F0-9]+$/,N=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var z={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function q(E,U={}){if(U=Object.assign({},z,U),!E||typeof E!="string")return E;let V=E.trim();if(U.skipLike!==void 0&&U.skipLike.test(V))return E;if(U.hex&&H.test(V))return Number.parseInt(V,16);{let W=N.exec(V);if(W){let O=W[1],x=W[2],Z=j(W[3]),me=W[4]||W[6];if(!U.leadingZeros&&x.length>0&&O&&V[2]!==".")return E;if(!U.leadingZeros&&x.length>0&&!O&&V[1]!==".")return E;{let X=Number(V),ne=""+X;return ne.search(/[eE]/)!==-1||me?U.eNotation?X:E:V.indexOf(".")!==-1?ne==="0"&&Z===""||ne===Z||O&&ne==="-"+Z?X:E:x?Z===ne||O+Z===ne?X:E:V===ne||V===O+ne?X:E}}else return E}}i(q,"toNumber"),r(q,"toNumber");function j(E){return E&&E.indexOf(".")!==-1&&(E=E.replace(/0+$/,""),E==="."?E="0":E[0]==="."?E="0"+E:E[E.length-1]==="."&&(E=E.substr(0,E.length-1))),E}i(j,"trimZeros"),r(j,"trimZeros"),C.exports=q}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(P,C){"use strict";var H=a(),N=u(),z=c(),q=l(),j=class{static{i(this,"OrderedObjParser")}static{r(this,"OrderedObjParser")}constructor(R){this.options=R,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(I,L)=>String.fromCharCode(Number.parseInt(L,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(I,L)=>String.fromCharCode(Number.parseInt(L,16))}},this.addExternalEntities=E,this.parseXml=x,this.parseTextData=U,this.resolveNameSpace=V,this.buildAttributesMap=O,this.isItStopNode=ne,this.replaceEntitiesValue=me,this.readStopNodeData=G,this.saveTextToParentTag=X,this.addChild=Z}};function E(R){let I=Object.keys(R);for(let L=0;L<I.length;L++){let B=I[L];this.lastEntities[B]={regex:new RegExp("&"+B+";","g"),val:R[B]}}}i(E,"addExternalEntities"),r(E,"addExternalEntities");function U(R,I,L,B,k,M,re){if(R!==void 0&&(this.options.trimValues&&!B&&(R=R.trim()),R.length>0)){re||(R=this.replaceEntitiesValue(R));let $=this.options.tagValueProcessor(I,R,L,k,M);return $==null?R:typeof $!=typeof R||$!==R?$:this.options.trimValues?ge(R,this.options.parseTagValue,this.options.numberParseOptions):R.trim()===R?ge(R,this.options.parseTagValue,this.options.numberParseOptions):R}}i(U,"parseTextData"),r(U,"parseTextData");function V(R){if(this.options.removeNSPrefix){let I=R.split(":"),L=R.charAt(0)==="/"?"/":"";if(I[0]==="xmlns")return"";I.length===2&&(R=L+I[1])}return R}i(V,"resolveNameSpace"),r(V,"resolveNameSpace");var W=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function O(R,I,L){if(!this.options.ignoreAttributes&&typeof R=="string"){let B=H.getAllMatches(R,W),k=B.length,M={};for(let re=0;re<k;re++){let $=this.resolveNameSpace(B[re][1]),D=B[re][4],ce=this.options.attributeNamePrefix+$;if($.length)if(this.options.transformAttributeName&&(ce=this.options.transformAttributeName(ce)),ce==="__proto__"&&(ce="#__proto__"),D!==void 0){this.options.trimValues&&(D=D.trim()),D=this.replaceEntitiesValue(D);let ie=this.options.attributeValueProcessor($,D,I);ie==null?M[ce]=D:typeof ie!=typeof D||ie!==D?M[ce]=ie:M[ce]=ge(D,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(M[ce]=!0)}if(!Object.keys(M).length)return;if(this.options.attributesGroupName){let re={};return re[this.options.attributesGroupName]=M,re}return M}}i(O,"buildAttributesMap"),r(O,"buildAttributesMap");var x=r(function(R){R=R.replace(/\r\n?/g,`
72
- `);let I=new N("!xml"),L=I,B="",k="";for(let M=0;M<R.length;M++)if(R[M]==="<")if(R[M+1]==="/"){let $=b(R,">",M,"Closing Tag is not closed."),D=R.substring(M+2,$).trim();if(this.options.removeNSPrefix){let _e=D.indexOf(":");_e!==-1&&(D=D.substr(_e+1))}this.options.transformTagName&&(D=this.options.transformTagName(D)),L&&(B=this.saveTextToParentTag(B,L,k));let ce=k.substring(k.lastIndexOf(".")+1);if(D&&this.options.unpairedTags.indexOf(D)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${D}>`);let ie=0;ce&&this.options.unpairedTags.indexOf(ce)!==-1?(ie=k.lastIndexOf(".",k.lastIndexOf(".")-1),this.tagsNodeStack.pop()):ie=k.lastIndexOf("."),k=k.substring(0,ie),L=this.tagsNodeStack.pop(),B="",M=$}else if(R[M+1]==="?"){let $=S(R,M,!1,"?>");if(!$)throw new Error("Pi Tag is not closed.");if(B=this.saveTextToParentTag(B,L,k),!(this.options.ignoreDeclaration&&$.tagName==="?xml"||this.options.ignorePiTags)){let D=new N($.tagName);D.add(this.options.textNodeName,""),$.tagName!==$.tagExp&&$.attrExpPresent&&(D[":@"]=this.buildAttributesMap($.tagExp,k,$.tagName)),this.addChild(L,D,k)}M=$.closeIndex+1}else if(R.substr(M+1,3)==="!--"){let $=b(R,"-->",M+4,"Comment is not closed.");if(this.options.commentPropName){let D=R.substring(M+4,$-2);B=this.saveTextToParentTag(B,L,k),L.add(this.options.commentPropName,[{[this.options.textNodeName]:D}])}M=$}else if(R.substr(M+1,2)==="!D"){let $=z(R,M);this.docTypeEntities=$.entities,M=$.i}else if(R.substr(M+1,2)==="!["){let $=b(R,"]]>",M,"CDATA is not closed.")-2,D=R.substring(M+9,$);B=this.saveTextToParentTag(B,L,k);let ce=this.parseTextData(D,L.tagname,k,!0,!1,!0,!0);ce==null&&(ce=""),this.options.cdataPropName?L.add(this.options.cdataPropName,[{[this.options.textNodeName]:D}]):L.add(this.options.textNodeName,ce),M=$+2}else{let $=S(R,M,this.options.removeNSPrefix),D=$.tagName,ce=$.rawTagName,ie=$.tagExp,_e=$.attrExpPresent,Zi=$.closeIndex;this.options.transformTagName&&(D=this.options.transformTagName(D)),L&&B&&L.tagname!=="!xml"&&(B=this.saveTextToParentTag(B,L,k,!1));let qi=L;if(qi&&this.options.unpairedTags.indexOf(qi.tagname)!==-1&&(L=this.tagsNodeStack.pop(),k=k.substring(0,k.lastIndexOf("."))),D!==I.tagname&&(k+=k?"."+D:D),this.isItStopNode(this.options.stopNodes,k,D)){let Ae="";if(ie.length>0&&ie.lastIndexOf("/")===ie.length-1)M=$.closeIndex;else if(this.options.unpairedTags.indexOf(D)!==-1)M=$.closeIndex;else{let $r=this.readStopNodeData(R,ce,Zi+1);if(!$r)throw new Error(`Unexpected end of ${ce}`);M=$r.i,Ae=$r.tagContent}let Fr=new N(D);D!==ie&&_e&&(Fr[":@"]=this.buildAttributesMap(ie,k,D)),Ae&&(Ae=this.parseTextData(Ae,D,k,!0,_e,!0,!0)),k=k.substr(0,k.lastIndexOf(".")),Fr.add(this.options.textNodeName,Ae),this.addChild(L,Fr,k)}else{if(ie.length>0&&ie.lastIndexOf("/")===ie.length-1){D[D.length-1]==="/"?(D=D.substr(0,D.length-1),k=k.substr(0,k.length-1),ie=D):ie=ie.substr(0,ie.length-1),this.options.transformTagName&&(D=this.options.transformTagName(D));let Ae=new N(D);D!==ie&&_e&&(Ae[":@"]=this.buildAttributesMap(ie,k,D)),this.addChild(L,Ae,k),k=k.substr(0,k.lastIndexOf("."))}else{let Ae=new N(D);this.tagsNodeStack.push(L),D!==ie&&_e&&(Ae[":@"]=this.buildAttributesMap(ie,k,D)),this.addChild(L,Ae,k),L=Ae}B="",M=Zi}}else B+=R[M];return I.child},"parseXml");function Z(R,I,L){let B=this.options.updateTag(I.tagname,L,I[":@"]);B===!1||(typeof B=="string"&&(I.tagname=B),R.addChild(I))}i(Z,"addChild"),r(Z,"addChild");var me=r(function(R){if(this.options.processEntities){for(let I in this.docTypeEntities){let L=this.docTypeEntities[I];R=R.replace(L.regx,L.val)}for(let I in this.lastEntities){let L=this.lastEntities[I];R=R.replace(L.regex,L.val)}if(this.options.htmlEntities)for(let I in this.htmlEntities){let L=this.htmlEntities[I];R=R.replace(L.regex,L.val)}R=R.replace(this.ampEntity.regex,this.ampEntity.val)}return R},"replaceEntitiesValue");function X(R,I,L,B){return R&&(B===void 0&&(B=Object.keys(I.child).length===0),R=this.parseTextData(R,I.tagname,L,!1,I[":@"]?Object.keys(I[":@"]).length!==0:!1,B),R!==void 0&&R!==""&&I.add(this.options.textNodeName,R),R=""),R}i(X,"saveTextToParentTag"),r(X,"saveTextToParentTag");function ne(R,I,L){let B="*."+L;for(let k in R){let M=R[k];if(B===M||I===M)return!0}return!1}i(ne,"isItStopNode"),r(ne,"isItStopNode");function Se(R,I,L=">"){let B,k="";for(let M=I;M<R.length;M++){let re=R[M];if(B)re===B&&(B="");else if(re==='"'||re==="'")B=re;else if(re===L[0])if(L[1]){if(R[M+1]===L[1])return{data:k,index:M}}else return{data:k,index:M};else re===" "&&(re=" ");k+=re}}i(Se,"tagExpWithClosingIndex"),r(Se,"tagExpWithClosingIndex");function b(R,I,L,B){let k=R.indexOf(I,L);if(k===-1)throw new Error(B);return k+I.length-1}i(b,"findClosingIndex"),r(b,"findClosingIndex");function S(R,I,L,B=">"){let k=Se(R,I+1,B);if(!k)return;let M=k.data,re=k.index,$=M.search(/\s/),D=M,ce=!0;$!==-1&&(D=M.substring(0,$),M=M.substring($+1).trimStart());let ie=D;if(L){let _e=D.indexOf(":");_e!==-1&&(D=D.substr(_e+1),ce=D!==k.data.substr(_e+1))}return{tagName:D,tagExp:M,closeIndex:re,attrExpPresent:ce,rawTagName:ie}}i(S,"readTagExp"),r(S,"readTagExp");function G(R,I,L){let B=L,k=1;for(;L<R.length;L++)if(R[L]==="<")if(R[L+1]==="/"){let M=b(R,">",L,`${I} is not closed`);if(R.substring(L+2,M).trim()===I&&(k--,k===0))return{tagContent:R.substring(B,L),i:M};L=M}else if(R[L+1]==="?")L=b(R,"?>",L+1,"StopNode is not closed.");else if(R.substr(L+1,3)==="!--")L=b(R,"-->",L+3,"StopNode is not closed.");else if(R.substr(L+1,2)==="![")L=b(R,"]]>",L,"StopNode is not closed.")-2;else{let M=S(R,L,">");M&&((M&&M.tagName)===I&&M.tagExp[M.tagExp.length-1]!=="/"&&k++,L=M.closeIndex)}}i(G,"readStopNodeData"),r(G,"readStopNodeData");function ge(R,I,L){if(I&&typeof R=="string"){let B=R.trim();return B==="true"?!0:B==="false"?!1:q(R,L)}else return H.isExist(R)?R:""}i(ge,"parseValue"),r(ge,"parseValue"),C.exports=j}}),p=o({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(P){"use strict";function C(j,E){return H(j,E)}i(C,"prettify"),r(C,"prettify");function H(j,E,U){let V,W={};for(let O=0;O<j.length;O++){let x=j[O],Z=N(x),me="";if(U===void 0?me=Z:me=U+"."+Z,Z===E.textNodeName)V===void 0?V=x[Z]:V+=""+x[Z];else{if(Z===void 0)continue;if(x[Z]){let X=H(x[Z],E,me),ne=q(X,E);x[":@"]?z(X,x[":@"],me,E):Object.keys(X).length===1&&X[E.textNodeName]!==void 0&&!E.alwaysCreateTextNode?X=X[E.textNodeName]:Object.keys(X).length===0&&(E.alwaysCreateTextNode?X[E.textNodeName]="":X=""),W[Z]!==void 0&&W.hasOwnProperty(Z)?(Array.isArray(W[Z])||(W[Z]=[W[Z]]),W[Z].push(X)):E.isArray(Z,me,ne)?W[Z]=[X]:W[Z]=X}}}return typeof V=="string"?V.length>0&&(W[E.textNodeName]=V):V!==void 0&&(W[E.textNodeName]=V),W}i(H,"compress"),r(H,"compress");function N(j){let E=Object.keys(j);for(let U=0;U<E.length;U++){let V=E[U];if(V!==":@")return V}}i(N,"propName"),r(N,"propName");function z(j,E,U,V){if(E){let W=Object.keys(E),O=W.length;for(let x=0;x<O;x++){let Z=W[x];V.isArray(Z,U+"."+Z,!0,!0)?j[Z]=[E[Z]]:j[Z]=E[Z]}}}i(z,"assignAttributes"),r(z,"assignAttributes");function q(j,E){let{textNodeName:U}=E,V=Object.keys(j).length;return!!(V===0||V===1&&(j[U]||typeof j[U]=="boolean"||j[U]===0))}i(q,"isLeafTag"),r(q,"isLeafTag"),P.prettify=C}}),h=o({"node_modules/fast-xml-parser/src/validator.js"(P){"use strict";var C=a(),H={allowBooleanAttributes:!1,unpairedTags:[]};P.validate=function(b,S){S=Object.assign({},H,S);let G=[],ge=!1,R=!1;b[0]==="\uFEFF"&&(b=b.substr(1));for(let I=0;I<b.length;I++)if(b[I]==="<"&&b[I+1]==="?"){if(I+=2,I=z(b,I),I.err)return I}else if(b[I]==="<"){let L=I;if(I++,b[I]==="!"){I=q(b,I);continue}else{let B=!1;b[I]==="/"&&(B=!0,I++);let k="";for(;I<b.length&&b[I]!==">"&&b[I]!==" "&&b[I]!==" "&&b[I]!==`
73
- `&&b[I]!=="\r";I++)k+=b[I];if(k=k.trim(),k[k.length-1]==="/"&&(k=k.substring(0,k.length-1),I--),!X(k)){let $;return k.trim().length===0?$="Invalid space after '<'.":$="Tag '"+k+"' is an invalid name.",Z("InvalidTag",$,ne(b,I))}let M=U(b,I);if(M===!1)return Z("InvalidAttr","Attributes for '"+k+"' have open quote.",ne(b,I));let re=M.value;if(I=M.index,re[re.length-1]==="/"){let $=I-re.length;re=re.substring(0,re.length-1);let D=W(re,S);if(D===!0)ge=!0;else return Z(D.err.code,D.err.msg,ne(b,$+D.err.line))}else if(B)if(M.tagClosed){if(re.trim().length>0)return Z("InvalidTag","Closing tag '"+k+"' can't have attributes or invalid starting.",ne(b,L));{let $=G.pop();if(k!==$.tagName){let D=ne(b,$.tagStartPos);return Z("InvalidTag","Expected closing tag '"+$.tagName+"' (opened in line "+D.line+", col "+D.col+") instead of closing tag '"+k+"'.",ne(b,L))}G.length==0&&(R=!0)}}else return Z("InvalidTag","Closing tag '"+k+"' doesn't have proper closing.",ne(b,I));else{let $=W(re,S);if($!==!0)return Z($.err.code,$.err.msg,ne(b,I-re.length+$.err.line));if(R===!0)return Z("InvalidXml","Multiple possible root nodes found.",ne(b,I));S.unpairedTags.indexOf(k)!==-1||G.push({tagName:k,tagStartPos:L}),ge=!0}for(I++;I<b.length;I++)if(b[I]==="<")if(b[I+1]==="!"){I++,I=q(b,I);continue}else if(b[I+1]==="?"){if(I=z(b,++I),I.err)return I}else break;else if(b[I]==="&"){let $=x(b,I);if($==-1)return Z("InvalidChar","char '&' is not expected.",ne(b,I));I=$}else if(R===!0&&!N(b[I]))return Z("InvalidXml","Extra text at the end",ne(b,I));b[I]==="<"&&I--}}else{if(N(b[I]))continue;return Z("InvalidChar","char '"+b[I]+"' is not expected.",ne(b,I))}if(ge){if(G.length==1)return Z("InvalidTag","Unclosed tag '"+G[0].tagName+"'.",ne(b,G[0].tagStartPos));if(G.length>0)return Z("InvalidXml","Invalid '"+JSON.stringify(G.map(I=>I.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return Z("InvalidXml","Start tag expected.",1);return!0};function N(b){return b===" "||b===" "||b===`
74
- `||b==="\r"}i(N,"isWhiteSpace"),r(N,"isWhiteSpace");function z(b,S){let G=S;for(;S<b.length;S++)if(b[S]=="?"||b[S]==" "){let ge=b.substr(G,S-G);if(S>5&&ge==="xml")return Z("InvalidXml","XML declaration allowed only at the start of the document.",ne(b,S));if(b[S]=="?"&&b[S+1]==">"){S++;break}else continue}return S}i(z,"readPI"),r(z,"readPI");function q(b,S){if(b.length>S+5&&b[S+1]==="-"&&b[S+2]==="-"){for(S+=3;S<b.length;S++)if(b[S]==="-"&&b[S+1]==="-"&&b[S+2]===">"){S+=2;break}}else if(b.length>S+8&&b[S+1]==="D"&&b[S+2]==="O"&&b[S+3]==="C"&&b[S+4]==="T"&&b[S+5]==="Y"&&b[S+6]==="P"&&b[S+7]==="E"){let G=1;for(S+=8;S<b.length;S++)if(b[S]==="<")G++;else if(b[S]===">"&&(G--,G===0))break}else if(b.length>S+9&&b[S+1]==="["&&b[S+2]==="C"&&b[S+3]==="D"&&b[S+4]==="A"&&b[S+5]==="T"&&b[S+6]==="A"&&b[S+7]==="["){for(S+=8;S<b.length;S++)if(b[S]==="]"&&b[S+1]==="]"&&b[S+2]===">"){S+=2;break}}return S}i(q,"readCommentAndCDATA"),r(q,"readCommentAndCDATA");var j='"',E="'";function U(b,S){let G="",ge="",R=!1;for(;S<b.length;S++){if(b[S]===j||b[S]===E)ge===""?ge=b[S]:ge!==b[S]||(ge="");else if(b[S]===">"&&ge===""){R=!0;break}G+=b[S]}return ge!==""?!1:{value:G,index:S,tagClosed:R}}i(U,"readAttributeStr"),r(U,"readAttributeStr");var V=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function W(b,S){let G=C.getAllMatches(b,V),ge={};for(let R=0;R<G.length;R++){if(G[R][1].length===0)return Z("InvalidAttr","Attribute '"+G[R][2]+"' has no space in starting.",Se(G[R]));if(G[R][3]!==void 0&&G[R][4]===void 0)return Z("InvalidAttr","Attribute '"+G[R][2]+"' is without value.",Se(G[R]));if(G[R][3]===void 0&&!S.allowBooleanAttributes)return Z("InvalidAttr","boolean attribute '"+G[R][2]+"' is not allowed.",Se(G[R]));let I=G[R][2];if(!me(I))return Z("InvalidAttr","Attribute '"+I+"' is an invalid name.",Se(G[R]));if(!ge.hasOwnProperty(I))ge[I]=1;else return Z("InvalidAttr","Attribute '"+I+"' is repeated.",Se(G[R]))}return!0}i(W,"validateAttributeString"),r(W,"validateAttributeString");function O(b,S){let G=/\d/;for(b[S]==="x"&&(S++,G=/[\da-fA-F]/);S<b.length;S++){if(b[S]===";")return S;if(!b[S].match(G))break}return-1}i(O,"validateNumberAmpersand"),r(O,"validateNumberAmpersand");function x(b,S){if(S++,b[S]===";")return-1;if(b[S]==="#")return S++,O(b,S);let G=0;for(;S<b.length;S++,G++)if(!(b[S].match(/\w/)&&G<20)){if(b[S]===";")break;return-1}return S}i(x,"validateAmpersand"),r(x,"validateAmpersand");function Z(b,S,G){return{err:{code:b,msg:S,line:G.line||G,col:G.col}}}i(Z,"getErrorObject"),r(Z,"getErrorObject");function me(b){return C.isName(b)}i(me,"validateAttrName"),r(me,"validateAttrName");function X(b){return C.isName(b)}i(X,"validateTagName"),r(X,"validateTagName");function ne(b,S){let G=b.substring(0,S).split(/\r?\n/);return{line:G.length,col:G[G.length-1].length+1}}i(ne,"getLineNumberForPosition"),r(ne,"getLineNumberForPosition");function Se(b){return b.startIndex+b[1].length}i(Se,"getPositionFromMatch"),r(Se,"getPositionFromMatch")}}),y=o({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(P,C){var{buildOptions:H}=s(),N=d(),{prettify:z}=p(),q=h(),j=class{static{i(this,"XMLParser")}static{r(this,"XMLParser")}constructor(E){this.externalEntities={},this.options=H(E)}parse(E,U){if(typeof E!="string")if(E.toString)E=E.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(U){U===!0&&(U={});let O=q.validate(E,U);if(O!==!0)throw Error(`${O.err.msg}:${O.err.line}:${O.err.col}`)}let V=new N(this.options);V.addExternalEntities(this.externalEntities);let W=V.parseXml(E);return this.options.preserveOrder||W===void 0?W:z(W,this.options)}addEntity(E,U){if(U.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(E.indexOf("&")!==-1||E.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(U==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[E]=U}};C.exports=j}});let _=y();return new _(n)},"getXmlParser");var kr=class extends je{static{i(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),f("policy.outbound.xml-to-json"),ee(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?wt(e.parseOnStatusCodes):void 0,this.parser=Oc({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 A(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 Nr=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 Mr=class{static{i(this,"BackgroundDispatcher")}#e;constructor(e,t){if(!t||t.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new Q(t.name??"",t.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),Vn().waitUntil(this.#e.waitUntilFlushed())}};var Cc=10,Sc=3e4,Dr=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=Sc,this.#r=Cc}else{let r=t;this.#n=r.ttlSeconds*1e3,this.#o=r.loaderTimeoutSeconds?r.loaderTimeoutSeconds*1e3:Sc,this.#r=Cc}this.#t=e}#s(e){return e.expiry<=new Date}#a(e){let t=this.#i[e];return!(t===void 0||t===0)}#u(e){let t=this.#e.get(e);if(t&&!this.#s(t))return t.data}async get(e){let t=this.#u(e);if(t)return this.#l(e),t;if(this.#a(e))try{await Qp(()=>this.#u(e)!==void 0||!this.#a,this.#o+this.#r+1,this.#r);let r=this.#u(e);if(r)return r}catch{}return this.#c(e)}#l(e){if(!this.#a(e)){let t=this.#c(e);Vn().waitUntil(t)}}async#c(e){try{this.#i[e]===void 0&&(this.#i[e]=0),this.#i[e]++;let t=await Promise.race([this.#t(e),scheduler.wait(this.#o)]);if(t===void 0)throw new Error(`BackgroundLoader: Loader timed out after ${this.#o} ms.`);return this.#e.set(e,{data:t,expiry:new Date(Date.now()+this.#n)}),t}finally{this.#i[e]--}}};async function Qp(n,e,t){let r=Date.now();for(;!n();){let o=Date.now()-r;if(o>e)throw new Error(`BackgroundLoader: Timeout waiting for an on-going loader after ${o} ms.`);await scheduler.wait(t)}}i(Qp,"waitUntilTrue");var Hi=["sha-1","sha-256","sha-384","sha-512"],Ur=class{static{i(this,"BaseCryptoBeta")}};var Hr=class extends Ur{static{i(this,"WorkerCryptoBeta")}async digest(e,t){if(!Hi.includes(e.toLowerCase()))throw new A(`Algorithm ${e} is not supported. Try using ${Hi.join(", ")}`);let r=new TextEncoder().encode(t),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var Zr=class{constructor(e){this.context=e}static{i(this,"BaseKeyValueStore")}};var qr=class extends Zr{static{i(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let t=m.instance.runtime.ZUPLO_KV;if(!t)throw new yn("The Key Value Store feature is not enabled for this project.");this.#e=t,f("platform.kv-store")}put(e,t,r){if(typeof e!="string")throw new g("value must be of type string");return this.#e.put(e,t,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,t){return this.#e.get(e,{type:"text",cacheTtl:t?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};
71
+ `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new Ze(e,n,{message:"Timestamp outside the tolerance zone"});return!0}i(dp,"validateComputedSignature");function pp(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(pp,"parseHeader");function mp(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(mp,"secureCompare");async function gp(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]=ci[s[u]];return a.join("")}i(gp,"computeHMACSignatureAsync");var ci=new Array(256);for(let n=0;n<ci.length;n++)ci[n]=n.toString(16).padStart(2,"0");function Y(n,e,t="policy",r){let o=`${t} '${e}'`;if(!lt(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],h=r?`${r}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new g(`Value of '${h}' on ${o} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"&&Array.isArray(p))throw new g(`Value of '${h}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new g(`Value of '${h}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new g(`Value of '${h}' on ${o} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof p=="number"&&isNaN(p))throw new g(`Value of '${h}' on ${o} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=i((c,l)=>(s(c,l,!0),{optional:a,required:u}),"optional"),u=i((c,l)=>(s(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}i(Y,"optionValidator");var At=class extends le{static{i(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),f("policy.inbound.stripe-webhook-verification")}async handler(e,t){Y(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 ja(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 Ba(n){return n!==null&&typeof n=="object"&&"id"in n&&Oe(n.id)&&"type"in n&&Oe(n.type)}i(Ba,"isStripeWebhookEvent");var fp={getSubscription:async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving subscription from Stripe API.";throw t.error(s,o),new _(s)}return o},getCustomer:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer from Stripe API.";throw t.error(s,o),new _(s)}return o},getUpcomingInvoice:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(s,o),new _(s)}return o}},ur=fp;var li="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",za="My API Key";async function Ga({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=m.instance,c=new URL(`/v1/buckets/${n}/consumers`,li);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:za,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await be({retryDelayMs:5,retries:2,logger:te.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),h=await p.json();if(p.status!==200){let y="Error creating API Key Consumer";throw a.log.error(y,h),new _(y)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(Ga,"createConsumer");async function Va({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=m.instance,u=new URL(`/v1/buckets/${n}/consumers`,li);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:za,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await be({retryDelayMs:5,retries:2,logger:te.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let h="Error creating API Key Consumer";throw s.log.error(h,p),new _(h)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(Va,"createConsumerInvite");async function Wa({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=m.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,li);o.searchParams.set("with-api-key","true");let s=await be({retryDelayMs:5,retries:2,logger:te.getLogger(t)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new _(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(Wa,"deleteConsumer");async function Ka({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:r,meteringBucketId:o,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[t],customerKey:r,customerExternalId:a,metadata:c,trialEndDate:l?l.trialEndDate:void 0,trialStartDate:l?l.trialStartDate:void 0,trialEndStatus:l?l.trialEndStatus:void 0},{authApiJWT:p,meteringServiceUrl:h}=m.instance;if(!It(p))throw new Q("No Zuplo JWT token set.");let y=await be({retryDelayMs:5,retries:2,logger:te.getLogger(n)},`${h}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!y.ok){let A=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,P,O="";try{P=await y.json(),O=P.detail??P.title}catch{P={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:y.status,detail:y.statusText}}throw n.log.error(A,P),new _(`${A} ${O}`)}n.log.info("Successfully created monetization subscription.",d)}i(Ka,"createSubscription");async function _t({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=m.instance;if(!It(o))throw new Q("No Zuplo JWT token set.");let a=await be({retryDelayMs:5,retries:2,logger:te.getLogger(n)},`${s}/internal/v1/metering/${t}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Unable to update monetization subscription with: '${JSON.stringify(r)}'.`,c,l="";try{c=await a.json(),l=c.detail??c.title}catch{c={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(u,c),new _(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}i(_t,"updateSubscription");async function Lt({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=m.instance;if(!It(o))throw new Q("No Zuplo JWT token set.");let a=await be({retryDelayMs:5,retries:2,logger:te.getLogger(n)},`${s}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":n.requestId},method:"GET"});if(!a.ok){let c=`Unable to retrieve the monetization subscription for Stripe subscription '${e}'.`,l,d="";try{l=await a.json(),d=l.detail??l.title}catch{l={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(c,l),new _(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(c),new _(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(c),new _(c)}return u.data[0]}i(Lt,"getSubscription");var ae="Skipping since we're unable to process the webhook event.",nt="Successfully processed the webhook event",xe="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function cr(n){return n.replaceAll("_","-")}i(cr,"stripeStatusToMeteringStatus");function gt(n){return new Date(n*1e3).toISOString()}i(gt,"unixTimestampToISOString");async function di(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:ae,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:ae,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:ae,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!==m.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:ae,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 Ga({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await ur.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:ae,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Va({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:ae,detail:p.message})}if(!c)return T.ok(n,e,{title:ae,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=cr(t.data.object.status),h;l&&d&&(h={subscriber:{sub:d,email:l}});let y;t.data.object.trial_end!==null&&t.data.object.trial_start!==null&&t.data.object.trial_settings&&t.data.object.trial_settings.end_behavior&&(t.data.object.trial_settings.end_behavior.missing_payment_method==="cancel"||t.data.object.trial_settings.end_behavior.missing_payment_method==="pause")&&(y={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:gt(t.data.object.trial_end),trialStartDate:gt(t.data.object.trial_start)}),await Ka({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:h,trial:y})}catch(p){return await Wa({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),T.ok(n,e,{title:ae,detail:p.message})}return T.ok(n,e,{title:nt})}i(di,"onCustomerSubscriptionCreated");async function pi(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:ae,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:ae,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!==m.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:ae,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 Lt({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});await _t({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return T.ok(n,e,{title:ae,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:nt})}i(pi,"onCustomerSubscriptionDeleted");async function mi(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:ae,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:ae,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!==m.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:ae,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 Lt({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=cr(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=gt(t.data.object.trial_end)),await _t({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return T.ok(n,e,{title:ae,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:nt})}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 Lt({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await ur.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(h=>h.proration&&h.price.product===c),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${t.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await _t({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return T.ok(n,e,{title:ae,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:nt})}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 Lt({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?gt(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?gt(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await _t({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:ae,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:nt})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),T.ok(n,e,{title:ae,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(mi,"onCustomerSubscriptionUpdated");var gi=class extends Pn{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(Ee.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Ee.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(Ee.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=Ee.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new g("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!m.instance.build.ACCOUNT_NAME)throw new Q("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let h=this.options.primaryDataRegion??"us-central1";if(!hp(h))throw new g(`StripeMonetizationPlugin - The value '${h}' on the property 'primaryDataRegion' is invalid.`);let y=await c.json();if(!Ba(y))return T.ok(c,l,{title:ae,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 '${y.type}' with ID '${y.id}'.`),y.type){case"customer.subscription.created":return await di(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await mi(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await pi(c,l,y,{meteringBucketId:d});default:return T.ok(c,l,{title:ae,detail:`Event '${y.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+xe})}},"stripeWebhookHandler"),s=Ys({inboundPolicies:[new At({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});Y(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new he({processors:[Ie,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 hp(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}i(hp,"isMetricsRegion");var Qa=new WeakMap,Ja={},lr=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){Qa.set(e,t)}};async function Ya(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=Xe(t.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=Qa.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new _(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=dt(n.user,t.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??t.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??t.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(t.dimensions??{},a?.dimensions)},h=Ja[t.apiKey];if(!h){let y=t.apiKey,A=n.headers.get("zm-test-id")??"";h=new ee("amberflo-ingest-meter",10,async P=>{try{let O=t.url??"https://app.amberflo.io/ingest",D=await F.fetch(O,{method:"POST",body:JSON.stringify(P),headers:{"content-type":"application/json","x-api-key":y,"zm-test-id":A}});D.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${D.status}: ${await D.text()}`)}catch(O){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${O.message}`),O}}),Ja[y]=h}h.enqueue(p),e.waitUntil(h.waitUntilFlushed())}}),n}i(Ya,"AmberfloMeteringInboundPolicy");async function ft(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(ft,"sha256");var Xa=new Map;async function ce(n,e,t){let r,o=`${n}-${e}`,s=Xa.get(o);return s!==void 0?r=s:(r=`zuplo-policy-${await ft(JSON.stringify({policyName:n,options:t}))}`,Xa.set(n,r)),r}i(ce,"getPolicyCacheName");var eu="key-metadata-cache-type";function yp(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}i(yp,"getKeyValue");async function dr(n,e,t,r){if(f("policy.inbound.api-key"),!t.bucketName)if(Ee.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=Ee.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(O=>o.allowUnauthenticatedRequests?n:T.unauthorized(n,e,{detail:O}),"unauthorizedResponse"),a=n.headers.get(o.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=yp(a,o);if(!u||u==="")return s("No key present");let c=await bp(u),l=await ce(r,void 0,o),d=new se(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!==eu&&te.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let h={key:u},y=await be({retryDelayMs:5,retries:2,logger:te.getLogger(e)},`${m.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":m.instance.deploymentName??"unknown","User-Agent":m.instance.systemUserAgent},body:JSON.stringify(h)});if(y.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(y.status!==200){try{let O=await y.text(),D=JSON.parse(O);e.log.error("Unexpected response from key service",D)}catch{e.log.error("Invalid response from key service")}throw new _(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${y.status}`)}let A=await y.json(),P={isValid:!0,typeId:eu,user:{sub:A.name,data:A.metadata}};return n.user=P.user,d.put(c,P,o.cacheTtlSeconds),n}i(dr,"ApiKeyInboundPolicy");async function bp(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(bp,"hashValue");var tu=dr;var ln=require("jose");var nu=require("jose");var fi=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 hi&&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",m.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=(0,nu.createLocalJWKSet)(t),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(t=>{throw this.pendingFetch=void 0,t}),await this.pendingFetch}async fetchJwks(e,t,r){let o=await this.cache.get(this.url.href);if(o)return o;let s,a,u=!1;typeof AbortController=="function"&&(s=new AbortController,a=setTimeout(()=>{u=!0,s.abort()},t));let c=await F.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new yi("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new kt("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 kt("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function ru(n,e,t){let r=new fi(n,e,t);return async(o,s)=>r.getKey(o,s)}i(ru,"createRemoteJWKSet");var kt=class extends _{static{i(this,"JWKSError")}},hi=class extends kt{static{i(this,"JWKSNoMatchingKey")}},yi=class extends kt{static{i(this,"JWKSTimeout")}};var pr={},wp=i((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new g("Invalid State - jwkUrl not set");if(!pr[r.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(s=r.useExperimentalInMemoryCache),s){let a=await ce(n,void 0,r),u=new se(a,e);pr[r.jwkUrl]=ru(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else pr[r.jwkUrl]=(0,ln.createRemoteJWKSet)(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await(0,ln.jwtVerify)(t,pr[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),Rp=i(async(n,e)=>{let t;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);t=new Uint8Array(s)}else t=e.secret;let{payload:r}=await(0,ln.jwtVerify)(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),we=i(async(n,e,t,r)=>{f("policy.inbound.open-id-jwt-auth");let o=n.headers.get("Authorization"),s="bearer ",a=i(h=>T.unauthorized(n,e,{detail:h}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new 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 u=t.jwkUrl?wp(r,e):Rp,l=await i(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let h=o.substring(s.length);if(!h||h.length===0)return a("No bearer token on authorization header");try{return await u(h,t)}catch(y){let A=new URL(n.url);return"code"in y&&y.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${A.pathname} `,y):e.log.warn(`Invalid token on: ${n.method} ${A.pathname}`,y),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return t.allowUnauthenticatedRequests===!0?n:l;let d=t.subPropertyName??"sub",p=l[d];return p?(n.user={sub:p,data:l},n):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var ou=i(async(n,e,t,r)=>(f("policy.inbound.auth0-jwt-auth"),we(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"Auth0JwtInboundPolicy");var mr=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 F.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!t.ok)throw new Error(`Request to PDP service failed with response status ${t.status}.`);return await t.json()}};var gr=class n extends le{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"),Y(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new mr(e)}async handler(e,t){let r=i(a=>this.options.allowUnauthorizedRequests?e: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 iu=i(async(n,e,t)=>{f("policy.inbound.basic-auth");let r=n.headers.get("Authorization"),o="basic ",s=i(l=>T.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!r)return await s("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await s("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let h=d.substring(0,p),y=d.substring(p+1),A=t.accounts.find(P=>P.username===h&&P.password===y);return A||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return t.allowUnauthenticatedRequests?n:u;let c=u.username;return n.user={sub:c,data:u.data},n},"BasicAuthInboundPolicy");function fr(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}i(fr,"extractDateElements");function su(n,e){return new Date(n,e+1,0).getDate()}i(su,"getDaysInMonth");function bi(n,e){return n<=e?e-n:6-n+e+1}i(bi,"getDaysBetweenWeekdays");var hr=class{static{i(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:r,days:o,months:s,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!t||t.size===0)throw new Error("There must be at least one allowed minute.");if(!r||r.size===0)throw new Error("There must be at least one allowed hour.");if(!s||s.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!o||o.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((c,l)=>c-l),this.minutes=Array.from(t).sort((c,l)=>c-l),this.hours=Array.from(r).sort((c,l)=>c-l),this.days=Array.from(o).sort((c,l)=>c-l),this.months=Array.from(s).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=i((c,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${c} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");u("seconds",this.seconds,{min:0,max:59}),u("minutes",this.minutes,{min:0,max:59}),u("hours",this.hours,{min:0,max:23}),u("days",this.days,{min:1,max:31}),u("months",this.months,{min:0,max:11}),u("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(c=>c).reverse(),minutes:this.minutes.map(c=>c).reverse(),hours:this.hours.map(c=>c).reverse(),days:this.days.map(c=>c).reverse(),months:this.months.map(c=>c).reverse(),weekdays:this.weekdays.map(c=>c).reverse()}}findAllowedHour(e,t){return e==="next"?this.hours.find(r=>r>=t):this.reversed.hours.find(r=>r<=t)}findAllowedMinute(e,t){return e==="next"?this.minutes.find(r=>r>=t):this.reversed.minutes.find(r=>r<=t)}findAllowedSecond(e,t){return e==="next"?this.seconds.find(r=>r>t):this.reversed.seconds.find(r=>r<t)}findAllowedTime(e,t){let r=this.findAllowedHour(e,t.hour);if(r!==void 0)if(r===t.hour){let o=this.findAllowedMinute(e,t.minute);if(o!==void 0)if(o===t.minute){let s=this.findAllowedSecond(e,t.second);if(s!==void 0)return{hour:r,minute:o,second:s};if(o=this.findAllowedMinute(e,e==="next"?t.minute+1:t.minute-1),o!==void 0)return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(r=this.findAllowedHour(e,e==="next"?t.hour+1:t.hour-1),r!==void 0)return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,t,r,o){if(o<1)throw new Error("startDay must not be smaller than 1.");let s=su(t,r),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return o>s?e==="next"?void 0:s:o;let c;a&&(c=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),c!==void 0&&c>s&&(c=void 0));let l;if(u){let d=new Date(t,r,o).getDay(),p=e==="next"?this.weekdays.find(h=>h>=d)??this.weekdays[0]:this.reversed.weekdays.find(h=>h<=d)??this.reversed.weekdays[0];if(p!==void 0){let h=e==="next"?bi(d,p):bi(p,d);l=e==="next"?o+h:o-h,(l>s||l<1)&&(l=void 0)}}if(c!==void 0&&l!==void 0)return e==="next"?Math.min(c,l):Math.max(c,l);if(c!==void 0)return c;if(l!==void 0)return l}getNextDate(e=new Date){let t=fr(e),r=t.year,o=this.months.findIndex(a=>a>=t.month);o===-1&&(o=0,r++);let s=this.months.length*5;for(let a=0;a<s;a++){let u=r+Math.floor((o+a)/this.months.length),c=this.months[(o+a)%this.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("next",u,c,l?t.day:1),p=l&&d===t.day;if(d!==void 0&&p){let h=this.findAllowedTime("next",t);if(h!==void 0)return new Date(u,c,d,h.hour,h.minute,h.second);d=this.findAllowedDayInMonth("next",u,c,d+1),p=!1}if(d!==void 0&&!p)return new Date(u,c,d,this.hours[0],this.minutes[0],this.seconds[0])}throw new Error("No valid next date was found.")}getNextDates(e,t){let r=[],o;for(let s=0;s<e;s++)o=this.getNextDate(o??t),r.push(o);return r}*getNextDatesIterator(e,t){let r;for(;;){if(r=this.getNextDate(e),e=r,t&&t.getTime()<r.getTime())return;yield r}}getPrevDate(e=new Date){let t=fr(e),r=t.year,o=this.reversed.months.findIndex(a=>a<=t.month);o===-1&&(o=0,r--);let s=this.reversed.months.length*5;for(let a=0;a<s;a++){let u=r-Math.floor((o+a)/this.reversed.months.length),c=this.reversed.months[(o+a)%this.reversed.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("prev",u,c,l?t.day:31),p=l&&d===t.day;if(d!==void 0&&p){let h=this.findAllowedTime("prev",t);if(h!==void 0)return new Date(u,c,d,h.hour,h.minute,h.second);d>1&&(d=this.findAllowedDayInMonth("prev",u,c,d-1),p=!1)}if(d!==void 0&&!p)return new Date(u,c,d,this.reversed.hours[0],this.reversed.minutes[0],this.reversed.seconds[0])}throw new Error("No valid previous date was found.")}getPrevDates(e,t){let r=[],o;for(let s=0;s<e;s++)o=this.getPrevDate(o??t),r.push(o);return r}*getPrevDatesIterator(e,t){let r;for(;;){if(r=this.getPrevDate(e),e=r,t&&t.getTime()>r.getTime())return;yield r}}matchDate(e){let{second:t,minute:r,hour:o,day:s,month:a,weekday:u}=fr(e);return this.seconds.indexOf(t)===-1||this.minutes.indexOf(r)===-1||this.hours.indexOf(o)===-1||this.months.indexOf(a)===-1?!1:this.days.length!==31&&this.weekdays.length!==7?this.days.indexOf(s)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(s)!==-1&&this.weekdays.indexOf(u)!==-1}};var Pp={min:0,max:59},Ip={min:0,max:59},Ep={min:0,max:23},Tp={min:1,max:31},xp={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"}},Op={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},vp={"@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 ht(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=>{ht(d,e).forEach(h=>t.add(h))}),t;let o=i(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${n}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${n}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),s=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(s===null)return t.add(o(n)),t;let a=s[1]==="*"?e.min:o(s[3]),u=s[1]==="*"?e.max:o(s[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=s[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}i(ht,"parseElement");function wi(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=vp[n.toLowerCase()]??n;let e=n.split(" ");if(e.length<5||e.length>6)throw new Error("Invalid cron expression: expected 5 or 6 elements.");let t=e.length===6?e[0]:"0",r=e.length===6?e[1]:e[0],o=e.length===6?e[2]:e[1],s=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],u=e.length===6?e[5]:e[4];return new hr({seconds:ht(t,Pp),minutes:ht(r,Ip),hours:ht(o,Ep),days:ht(s,Tp),months:new Set(Array.from(ht(a,xp)).map(c=>c-1)),weekdays:new Set(Array.from(ht(u,Op)).map(c=>c%7))})}i(wi,"parseCronExpression");var yr=class extends le{static{i(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),f("policy.inbound.brownout"),Y(e,t).optional("problem","object"),e.problem&&Y(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=[wi(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>wi(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 Cp=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Sp(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Sp,"digestMessage");var Ap=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 Sp(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 au(n,e,t,r){f("policy.inbound.caching");let o=await ce(r,t.cacheId,t),s=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Ap(n,t),c=await s.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=t.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(n.method.toUpperCase()))return;let h=t?.expirationSecondsTtl??60,y=new Response(p.body,p);Cp.forEach(A=>y.headers.delete(A)),y.headers.set("cache-control",`s-maxage=${h}`),e.waitUntil(s.put(u,y))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}i(au,"CachingInboundPolicy");var uu=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 oe(n,{method:t.method})},"ChangeMethodInboundPolicy");var br=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},Ri=class extends br{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Pi=class extends br{static{i(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function _p(n,e){if(Gs(n))throw new Ri(e)}i(_p,"throwIfUndefinedOrNull");function cu(n,e){if(_p(n,e),!Oe(n))throw new Pi(e,"string")}i(cu,"throwIfNotString");var Ii=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.")}isEnabled(){return!0}},Ei=class{constructor(e,t,r,o){this.clientUrl=e;this.clientAuthToken=t;this.deploymentName=r;this.userAgent=o}static{i(this,"RemoteRateLimitClient")}static instance;isEnabled(){return this.clientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:t,method:r,requestId:o}){cu(e,"url");let s=await F.fetch(`${this.clientUrl}${e}`,{method:r,body:t,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=s.headers.get("Content-Type")?.includes("application/json")?await s.json():await s.text();if(s.ok)return a;throw s.status===401?new Q("Rate limiting service failed with 401: Unauthorized"):new Q(`Rate limiting service failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}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 ft(e);return await this.fetch({url:`/quota/${r}`,method:"GET",requestId:t})}async setQuota(e,t,r){let o=await ft(e);await this.fetch({url:`/quota/${o}`,method:"POST",body:JSON.stringify(t),requestId:r})}},rt;function ot(n,e){if(rt)return rt;if(!m.instance.authApiJWT)return e.info("Using in-memory rate limit client for local development."),rt=new Ii,rt;let{authApiJWT:t,redisURL:r}=m.instance;if(!Oe(r))throw new Q(`RateLimitClient used in policy '${n}' - rate limit service URL not configured`);if(!Oe(t))throw new Q(`RateLimitClient used in policy '${n}' - service authentication not configured`);if(r&&(rt=new Ei(r,t,m.instance.deploymentName??"unknown",m.instance.systemUserAgent)),!rt||!rt.isEnabled())throw new Q(`RateLimitClient used in policy '${n}' - no remote rate limiting service enabled`);return rt}i(ot,"getRateLimitClient");var Ti="quota-inbound-policy-f307056c-8c00-4f2c-b4ac-c0ac7d04eca0";var wr=class n extends le{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}),Y(this.options,this.policyName).required("period","string").required("quotaBy","string").optional("quotaAnchorMode","string").optional("allowances","object"),n.setMeters(t,{requests:1});let o=te.getLogger(t);try{let s=Lp(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=kp(l.key,this.policyName);r&&t.log.debug(`QuotaInboundPolicy: key - '${d}'`);let p=ot(this.policyName,o),h=await p.getQuota(d,t.requestId);r&&t.log.debug("QuotaInboundPolicy: quotaResult",h),c&&new Date(h.anchorDate)!==c&&t.log.warn(`QuotaInboundPolicy '${this.policyName}' provided anchorDate ('${c}') did not match the stored, immutable anchorDate ('${h.anchorDate}')`);let y=Object.assign({},s.defaultAllowances);Object.assign(y,l.allowances);let A=[],P="";if(Object.entries(y).forEach(([O,D])=>{r&&(P+=`${O} - allowed: ${D} value: ${h.meters[O]??0}
72
+ `),(h.meters[O]??0)>=D&&A.push(O)}),r&&t.log.debug("QuotaInboundPolicy: debugTable",P),A.length>0)return T.tooManyRequests(e,t,{detail:`Quota exceeded for meters '${A.join(", ")}'`});t.addResponseSendingFinalHook(async(O,D,k)=>{if(r&&k.log.debug(`QuotaInboundPolicy: backend response - ${O.status}: ${O.statusText}`),!s.quotaOnStatusCodes.includes(O.status))return;let B=ue.get(k,Ti),q={config:{period:s.period,anchorDate:c?.toISOString()??""},increments:B};r&&k.log.debug("QuotaInboundPolicy: setQuotaDetails",q),await p.setQuota(d,q,k.requestId)})}catch(s){o.error(s),t.log.error(s)}return e}static setMeters(e,t){let r=ue.get(e,Ti)??{};Object.assign(r,t),ue.set(e,Ti,r)}};function Lp(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:Xe(n.quotaOnStatusCodes??"200-299"),defaultAllowances:Object.assign({},n.allowances),functions:{getQuotaDetail:t,getAnchorDate:r}}}i(Lp,"validateAndParseOptions");function kp(n,e){return encodeURIComponent(`${e}-${n}`)}i(kp,"processKey");var lu=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 oe(n,{headers:o})},"ClearHeadersInboundPolicy");var du=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 pu=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",we(n,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var mu=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 we(n,e,{issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,jwkUrl:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var fu=ze(He());var Np=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 Nt(n,e){return{function:qp(e,"RateLimitInboundPolicy",n),user:Mp,ip:Dp,all:Up}[e.rateLimitBy??"ip"]}i(Nt,"getRateLimitByFunctions");var Dp=i(async n=>({key:`ip-${Np(n)}`}),"getIP"),Mp=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),Up=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll");function qp(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 _(l)}if(!("key"in c)){let l=`${e} '${u}' - Custom rate limit function must return a valid key property.`;throw a.log.error(l,c),new _(l)}if(typeof c.key!="string"){let l=`${e} '${u}' - Custom rate limit function must return a valid key property of type string. Received type '${typeof c.key}'`;throw a.log.error(l),new _(l)}return c},"outerFunction")}i(qp,"wrapUserFunction");var Dt="Retry-After";var gu=(0,fu.debug)("zuplo:policies:ComplexRateLimitInboundPolicy"),xi=Symbol("complex-rate-limit-counters"),Rr=class n extends le{static{i(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let r=ue.get(e,xi)??{};Object.assign(r,t),ue.set(e,xi,t)}static getIncrements(e){return ue.get(e,xi)??{}}constructor(e,t){super(e,t),f("policy.inbound.complex-rate-limit-inbound"),Y(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&&Y(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=te.getLogger(t),s=ot(this.policyName,o),a=i((c,l)=>{if(this.options.throwOnFailure)throw new Q(c,{cause:l});o.error(c,l)},"throwOrLog"),u=i((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[Dt]=l.toString()),T.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l=await Nt(this.policyName,this.options)(e,t,this.policyName),d=m.instance.isTestMode||m.instance.isWorkingCopy?m.instance.build.BUILD_ID:"",p=Object.assign({},this.options.limits,l.limits),h=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;t.addResponseSendingFinalHook(async()=>{try{let O=n.getIncrements(t);gu(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(O)}`);let D=Object.entries(p).map(([B])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${B}`,ttlSeconds:h,increment:O[B]??0})),k=s.multiIncrement(D,t.requestId);t.waitUntil(k),await k}catch(O){o.error(O),t.log.error(O)}});let y=Object.entries(p).map(([O,D])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${O}`,ttlSeconds:h,limit:D})),A=await s.multiCount(y,t.requestId);return Zp(A,y).length>0?u(this.options.headerMode??"retry-after",h):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-r;gu(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function Zp(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(Zp,"findOverLimits");var hu=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=Re.instance,s=tn(t.policies,o?.routeData.policies);return So(s)(n,e)},"CompositeInboundPolicy");var yu=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=Hp(o);if(!s)return T.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await ce(r,void 0,t),u=new se(a,e),c=await u.get(s);if(!c){let l=await F.fetch(t.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${t.clientId}:${t.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(s,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),T.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):T.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function Hp(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(Hp,"getToken");var bu=i(async(n,e,t,r)=>(f("policy.inbound.firebase-jwt-auth"),Y(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),we(n,e,{issuer:`https://securetoken.google.com/${t.projectId}`,audience:t.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var wu=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 oe(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var Mt="__unknown__",Ru=i(async(n,e,t,r)=>{f("policy.inbound.geo-filter");let o={allow:{countries:qt(t.allow?.countries,"allow.countries",r),regionCodes:qt(t.allow?.regionCodes,"allow.regionCode",r),asns:qt(t.allow?.asns,"allow.asOrganization",r)},block:{countries:qt(t.block?.countries,"block.countries",r),regionCodes:qt(t.block?.regionCodes,"block.regionCode",r),asns:qt(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??Mt,a=e.incomingRequestProperties.regionCode?.toLowerCase()??Mt,u=e.incomingRequestProperties.asn?.toString()??Mt,c=o.ignoreUnknown&&s===Mt,l=o.ignoreUnknown&&a===Mt,d=o.ignoreUnknown&&u===Mt,p=o.allow.countries,h=o.allow.regionCodes,y=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||h.length>0&&!h.includes(a)&&!l||y.length>0&&!y.includes(u)&&!d)return Ut(n,e,r,s,a,u);let A=o.block.countries,P=o.block.regionCodes,O=o.block.asns;return A.length>0&&A.includes(s)&&!c||P.length>0&&P.includes(a)&&!l||O.length>0&&O.includes(u)&&!d?Ut(n,e,r,s,a,u):n},"GeoFilterInboundPolicy");function Ut(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(Ut,"blockedResponse");function qt(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(qt,"toLowerStringArray");var Pu=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 Eu=i(async(n,e,t,r)=>{f("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return Oi(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 Oi(r,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(h=>{a.push({responseName:u,contentName:l,exampleName:h,exampleValue:d[h]})})})}),a=a.filter(u=>!(t.responsePrefixFilter&&!u.responseName.startsWith(t.responsePrefixFilter)||t.contentType&&u.contentName!==t.contentType||t.exampleName&&u.exampleName!==t.exampleName)),t.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return Iu(a[u])}else return a.length>0?Iu(a[0]):Oi(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 Iu(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(Iu,"generateResponse");var Oi=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 Fp="Incoming",$p={logRequestBody:!0,logResponseBody:!0};function Tu(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}i(Tu,"headersToObject");function xu(){return new Date().toISOString()}i(xu,"timestamp");var vi=new WeakMap,jp={};function Cu(n,e){let t=vi.get(n);t||(t=jp);let r=Object.assign({...t},e);vi.set(n,r)}i(Cu,"setMoesifContext");async function Ou(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(Ou,"readBody");var Bp={},Ci;function vu(){if(!Ci)throw new _("Invalid State - no _lastLogger");return Ci}i(vu,"getLastLogger");function zp(n){let e=Bp[n];return e||(e=new ee("moesif-inbound",100,async t=>{let r=JSON.stringify(t);vu().debug("posting",r);let o=await F.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||vu().error({status:o.status,body:await o.text()})})),e}i(zp,"getDispatcher");async function Su(n,e,t,r){f("policy.inbound.moesif-analytics"),Ci=e.log;let o=xu(),s=Object.assign($p,t);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await Ou(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=zp(s.applicationId),d=n.headers.get("true-client-ip"),p=vi.get(e)??{},h={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Tu(n.headers)},y=s.logResponseBody?await Ou(u,e):void 0,A={time:xu(),status:u.status,headers:Tu(u.headers),body:y},P={request:h,response:A,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Fp};l.enqueue(P),e.waitUntil(l.waitUntilFlushed())}),n}i(Su,"MoesifInboundPolicy");async function Au(n,e,t,r){let o=te.getLogger(n),{authApiJWT:s,meteringServiceUrl:a}=m.instance,u;try{let l=await F.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription`,l)}let c=u&&u.data&&u.data.length>0?u.data:void 0;return c&&c.length>1?c.sort((d,p)=>d.createdOn>p.createdOn?-1:1)[0]:c&&c[0]}i(Au,"loadSubscription");async function _u(n,e,t,r,o){let{authApiJWT:s,meteringServiceUrl:a}=m.instance,u=te.getLogger(n);try{let c=await F.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`,c)}}i(_u,"consumeSubcriptionQuotas");var Gp=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function Pr(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(Pr,"validateMeters");function Lu(n,e){if(n)try{if(n.length===0)throw new g("Must set valid subscription statuses");let t=pt(n),r=[];for(let o of t)Gp.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(Lu,"parseAllowedSubscriptionStatuses");function ku(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(ku,"compareMeters");var Ir=class extends le{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return ue.get(e,Vt)}static setMeters(e,t){Pr(t,"setMeters");let r=ue.get(e,Wt)??{};Object.assign(r,t),ue.set(e,Wt,r)}constructor(e,t){super(e,t),f("policy.inbound.monetization")}async handler(e,t){Y(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=Xe(this.options.meterOnStatusCodes),s=ue.get(t,Wt),a={...this.options.meters,...s};Pr(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=Lu(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(P,O,D)=>{let k=ue.get(D,Vt);if((this.options.allowRequestsWithoutSubscription??!1)&&!k){D.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(Ee.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Ee.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let q=ue.get(D,Wt),j={...this.options.meters,...q};if(Pr(j,this.policyName),o.includes(P.status)&&k&&j){D.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${k.id}' with meters '${JSON.stringify(j)} on response status '${P.status}'`);let{metersInSubscription:E,metersNotInSubscription:Z}=ku(k.meters,j);if(Z&&Object.keys(Z).length>0){let V=Object.keys(Z);D.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${V}'`)}await _u(D,k.id,this.policyName,this.options.bucketId,E)}});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(Ee.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Ee.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await Au(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`),ue.set(t,Vt,p));let h=ue.get(t,Vt);if(!h)return u?e:(t.log.warn("Subscription is not available for user"),T.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(h&&Object.keys(h.meters).length===0)return t.log.error(`Quota is not set up for subscription '${h.id}'`),T.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let A=Object.keys(a).filter(P=>!Object.keys(h.meters).includes(P));if(A.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${A.join(", ")}`),T.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${A.join(", ")}`,title:"Quota Exceeded"});for(let P of Object.keys(a))if(h.meters[P].available<=0&&!r)return T.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${P}'`,title:"Quota Exceeded"});return e}};async function Er(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 be({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 _("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 _("Response returned from identity provider is not in the expected format.")}i(Er,"getClientCredentialsAccessToken");var Zt=class extends Error{constructor(t,r,o){super(r,o);this.code=t}static{i(this,"OpenFGAError")}},Tr=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 Error("storeId is required");return r}getAuthorizationModelId(e={}){return e?.authorizationModelId||this.authorizationModelId}async get(e,t){return this.fetch(e,"GET",t)}async put(e,t,r){return this.fetch(e,"PUT",r,t)}post(e,t,r){return this.fetch(e,"POST",r,t)}async fetch(e,t,r,o){let s=new Headers(r.headers||{});s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.set("User-Agent",m.instance.systemUserAgent);let a=`${this.apiUrl}${e}`,u=new Request(a,{method:t,headers:s,body:o?JSON.stringify(o):void 0}),c=await F.fetch(u);if(c.status!==200){let l;try{l=await c.json()}catch{}throw!l||!l.code||!l.message?new Zt("unknown",`Unknown error. Status: ${c.status}`):new Zt(l.code,l.message)}return c.json()}};function dn(n,e,t){!n[e]&&t&&(n[e]=t)}i(dn,"setHeaderIfNotSet");var Nu="X-OpenFGA-Client-Method",Du="X-OpenFGA-Client-Bulk-Request-Id",pn=class extends Tr{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 dn(r,Nu,"BatchCheck"),dn(r,Du,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 Zt)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(dn(c,Nu,"ListRelations"),dn(c,Du,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 Mu=Symbol("openfga-authz-context-data"),Ht=class extends le{static{i(this,"BaseOpenFGAAuthZInboundPolicy")}client;authorizer;cache;static setContextChecks(e,t){let r=Array.isArray(t)?t:[t];ue.set(e,Mu,r)}constructor(e,t){if(super(e,t),Y(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")Y(e.credentials,t).required("clientId","string").required("clientSecret","string").required("oauthTokenEndpointUrl","string").optional("apiAudience","string");else if(e.credentials.method==="api-token")Y(e.credentials,t).required("token","string").optional("headerName","string").optional("headerValuePrefix","string");else if(e.credentials.method==="header")Y(e.credentials,t).optional("headerName","string");else if(e.credentials.method!=="none")throw new g(`${this.policyType} '${this.policyName}' - The 'credentials.type' option is invalid. It must be set to either 'none', 'api-token', 'client-credentials', or 'header'.`);this.authorizer=this.getAuthorizer(e.credentials),this.client=new pn({apiUrl:e.apiUrl,storeId:e.storeId,authorizationModelId:e.authorizationModelId})}async handler(e,t){if(!this.cache){let a=await ce(this.policyName,void 0,this.options);this.cache=new se(a,t)}let r=i(a=>this.options.allowUnauthorizedRequests?e:T.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=ue.get(t,Mu);if(!o||o.length===0)throw new _(`${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 Q(`${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 Er({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 _("Invalid state for credentials method is not valid. This should not happen.")}};var Uu=["us1","eu1","au1"],xr=class extends Ht{static{i(this,"OktaFGAAuthZInboundPolicy")}constructor(e,t){if(!Uu.includes(e.region))throw new g(`OktaFGAAuthZInboundPolicy '${t}' - The 'region' option is invalid. Must be one of ${Uu.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 qu=i(async(n,e,t,r)=>(f("policy.inbound.okta-jwt-auth"),we(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"OktaJwtInboundPolicy");var Or=class extends Ht{static{i(this,"OpenFGAAuthZInboundPolicy")}constructor(e,t){super(e,t),f("policy.inbound.openfga-authz")}};var Zu=require("jose");var Si,Hu=i(async(n,e,t,r)=>{if(f("policy.inbound.propel-auth-jwt-auth"),!Si)try{Si=await(0,Zu.importSPKI)(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return we(n,e,{issuer:t.authUrl,secret:Si,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var zu=ze(He());var $u=ze(He());var Fu=(0,$u.debug)("zuplo:policies:RateLimitInboundPolicy"),ju=i(async(n,e,t,r)=>{let o=te.getLogger(e),s=i((j,E)=>{let Z={};return(!j||j==="retry-after")&&(Z[Dt]=E.toString()),T.tooManyRequests(n,e,void 0,Z)},"rateLimited"),u=await Nt(r,t)(n,e,r),c=u.key,l=u.requestsAllowed??t.requestsAllowed,d=u.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",h=ot(r,o),A=`rate-limit${m.instance.isTestMode?m.instance.build.BUILD_ID:""}/${r}/${c}`,P=await ce(r,void 0,t),O=new se(P,e),D=h.getCountAndUpdateExpiry(A,d,e.requestId),k;i(async()=>{let j=await D;if(j.count>l){let E=Date.now()+j.ttlSeconds*1e3;O.put(A,E,j.ttlSeconds),Fu(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${A}' (async mode)`),k=s(p,j.ttlSeconds)}},"asyncCheck")();let q=await O.get(A);if(q!==void 0&&q>Date.now()){Fu(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${A}' (async mode)`);let j=Math.round((q-Date.now())/1e3);return s(p,j)}return e.addResponseSendingHook(async j=>k??j),n},"AsyncRateLimitInboundPolicyImpl");var Bu=(0,zu.debug)("zuplo:policies:RateLimitInboundPolicy"),Vp="strict",Ai=i(async(n,e,t,r)=>{if(f("policy.inbound.rate-limit"),(t.mode??Vp)==="async")return ju(n,e,t,r);let s=Date.now(),a=te.getLogger(e),u=i((l,d)=>{if(t.throwOnFailure)throw new Q(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[Dt]=d.toString()),T.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await Nt(r,t)(n,e,r),p=d.key,h=d.requestsAllowed??t.requestsAllowed,y=d.timeWindowMinutes??t.timeWindowMinutes,A=t.headerMode??"retry-after",P=ot(r,a),D=`rate-limit${m.instance.isTestMode||m.instance.isWorkingCopy?m.instance.build.BUILD_ID:""}/${r}/${p}`,k=await P.getCountAndUpdateExpiry(D,y,e.requestId);return k.count>h?(Bu(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${D}' (strict mode)`),c(A,k.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-s;Bu(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var _i;function Gu(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}i(Gu,"headersToNameValuePairs");function Wp(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}i(Wp,"queryToNameValueParis");function Kp(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}i(Kp,"parseIntOrUndefined");var Vu={};async function Wu(n,e,t,r){f("policy.inbound.readme-metrics");let o=new Date,s=Date.now();return _i||(_i={name:"zuplo",version:m.instance.build.ZUPLO_VERSION,comment:`zuplo/${m.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?dt(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?dt(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:m.instance.isWorkingCopy||m.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:_i,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:Gu(n.headers),queryString:Wp(n.query)},response:{status:a.status,statusText:a.statusText,headers:Gu(a.headers),content:{size:Kp(n.headers.get("content-length"))}}}]}}},d=Vu[t.apiKey];if(!d){let p=t.apiKey;d=new ee("readme-metering-inbound-policy",10,async h=>{try{let y=t.url??"https://metrics.readme.io/request",A=await F.fetch(y,{method:"POST",body:JSON.stringify(h),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});A.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${A.status}: '${await A.text()}'`)}catch(y){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${y.message}'`),y}}),Vu[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}i(Wu,"ReadmeMetricsInboundPolicy");var Ku=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 oe(n,{headers:s})},"RemoveHeadersInboundPolicy");var Ju=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 Qu=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 oe(s.toString(),n)},"RemoveQueryParamsInboundPolicy");var Yu=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 Xu=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),ec=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?Xu():s&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?Xu():n},"RequestSizeLimitInboundPolicy");function tc(n,e,t){return`_${it(n+"_"+e+"_"+t)}`}i(tc,"getRawOperationDataIdentifierName");function vr(n,e,t,r){return`_${it(n.toLowerCase())}_`+e.toLowerCase()+"_"+t.toLowerCase()+`_${r.toLowerCase()}`}i(vr,"getIdForParameterSchema");function Cr(n,e,t){return`_${it(n.toLowerCase())}_`+e.toLowerCase()+`_rb_${it(t.toLowerCase())}`}i(Cr,"getIdForRequestBodySchema");function nc(n,e){return`_${it(n)}__${it(e)}`}i(nc,"getIdForRefSchema");function it(n){let e=[];for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(n.charAt(t)):e.push("_")}return e.join("")}i(it,"sanitizedIdentifierName");var Ft=i(n=>{let e=n.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),$t=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=vr(t,r,o,c.name),p=Re.instance.schemaValidator[d],h=p(e[c.name]),y=Li(p.errors);h||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${y.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),ke=i((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),Ne=i(n=>n==="log-only"||n==="reject-and-log","shouldLog"),De=i(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),Li=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 rc(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(y){let A=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,P=T.badRequest(e,n,{detail:`${A}, see errors property for more details`,errors:`${y}`});if(Ne(t.validateBody)&&ke(n,t.logLevel??"info",A,[r],y),De(t.validateBody))return P}if(!e.headers.get("Content-Type")){let y=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,A=T.badRequest(e,n,{detail:y});return Ne(t.validateBody)&&ke(n,t.logLevel??"info",y,[r],[y]),De(t.validateBody)?A:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=Cr(n.route.path,e.method,o),u=Re.instance.schemaValidator[a];if(!u){let y=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,A=T.badRequest(e,n,{detail:y});return Ne(t.validateBody)&&ke(n,t.logLevel??"info",y,[r],[y]),De(t.validateBody)?A:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Li(l),h=T.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(Ne(t.validateBody)&&ke(n,t.logLevel??"info",d,[r],p),De(t.validateBody))return h}i(rc,"handleBodyValidation");function oc(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Ft(n),s=$t(o.filter(a=>a.location==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=T.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:s.errors});if(Ne(t.validateHeaders)&&ke(n,t.logLevel??"info",a,s.invalidValues,s.errors),De(t.validateHeaders))return u}}i(oc,"handleHeadersValidation");function ic(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=Ft(n),o=$t(r.filter(s=>s.location==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let s="Path parameters validation failed",a=T.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(Ne(t.validatePathParameters)&&ke(n,t.logLevel??"info",s,o.invalidValues,o.errors),De(t.validatePathParameters))return a}}i(ic,"handlePathParameterValidation");function sc(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=Ft(n),o=$t(r.filter(s=>s.location==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let s="Query parameters validation failed",a=T.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(Ne(t.validateQueryParameters)&&ke(n,t.logLevel??"info",s,o.invalidValues,o.errors),De(t.validateQueryParameters))return a}}i(sc,"handleQueryParameterValidation");var ki=i(async(n,e,t)=>{f("policy.inbound.request-validation");let r=sc(e,n,t);if(r!==void 0||(r=ic(e,n,t),r!==void 0)||(r=oc(e,n,t),r!==void 0))return r;let o=await rc(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),ac=ki;var uc=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 cc=i(async(n,e,t)=>(f("policy.inbound.set-body"),new oe(n,{body:t.body})),"SetBodyInboundPolicy");var lc=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 oe(n,{headers:s})},"SetHeadersInboundPolicy");var dc=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 pc=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 oe(s.toString(),n)},"SetQueryParamsInboundPolicy");var mc=i(async(n,e,t,r,o)=>{if(f("policy.outbound.set-status"),!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(n.body,{headers:n.headers,status:r.status,statusText:r.statusText??n.statusText})},"SetStatusOutboundPolicy");var Jp=i(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),gc=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 fc=i(async(n,e,t,r)=>{f("policy.inbound.supabase-jwt-auth"),Y(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},s=await we(n,e,o,r);if(s instanceof Response)return s;if(!(s instanceof oe))throw new Q("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return s;let u=n.user?.data.app_metadata;if(!u)throw new _(`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 hc=i(async(n,e,t,r)=>{f("policy.inbound.upstream-azure-ad-service-auth"),Y(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await ce(r,void 0,t),s=new se(o,e),a=await s.get(r);if(!a){let u=await Qp(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 Qp(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await be({retries:n.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${n.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let s=await r.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new _("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new _("Response returned from Azure AD is not in the expected format.")}i(Qp,"getAccessToken");var yc="https://accounts.google.com/o/oauth2/token",Ni,bc=i(async(n,e,t,r)=>{f("policy.inbound.upstream-firebase-admin-auth"),Y(t,r).required("serviceAccountJson","string"),Ni||(Ni=await ve.init(t.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},s=await ce(r,void 0,t),a=new se(s,e),u=await a.get(r);if(!u){let c=await Ue({serviceAccount:Ni,audience:yc,payload:o}),l=await qn(yc,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new _("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var Yp="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Xp=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Di,wc=i(async(n,e,t,r)=>{if(f("policy.inbound.upstream-firebase-user-auth"),Y(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(Xp.indexOf(p)!==-1)throw new g(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}Di||(Di=await ve.init(t.serviceAccountJson));let s=t.userId;if(!s&&!t.userIdPropertyPath){if(!n.user)throw new _("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new _(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=dt(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new _(`Unable to determine user from for the policy ${r}`);let a=await ce(r,void 0,t),u=new se(a,e),c={uid:s,claims:o},l=await ft(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await Ue({serviceAccount:Di,audience:Yp,payload:c}),h=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,y=await la(h,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!y.idToken)throw new _("Invalid token response from Firebase");d=y.idToken,u.put(l,d,(y.expiresIn?parseInt(y.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var jt=class{static{i(this,"ZuploServices")}static async getIDToken(e,t){let r=new se("0c13603a-a19f-4f03-a04a-50aa393f7ffa-zuplo-tokens",e),o=await ce("zuplo-token",void 0,t),s=await r.get(o);if(s)return s;let{authClientId:a,authClientSecret:u,developerApiUrl:c,zuploClientAuthBucketId:l}=m.instance;if(!a||!u)throw new _("Zuplo service authentication is not enabled for this deployment. Contact support assistance.");let d=await Er({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 Rc="workload-access-token",Pc="service-account-id-token",Sr=class extends le{static{i(this,"UpstreamGcpFederatedAuthInboundPolicy")}cacheName;normalizedWorkloadIdentityProvider;constructor(e,t){super(e,t),f("policy.inbound.upstream-gcp-federated-auth"),Y(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 ce(this.policyName,void 0,this.options));let r;this.options.useMemoryCacheOnly?r=new We(this.cacheName):r=new se(this.cacheName,t);let o=await r.get(Rc);if(!o){let a=`https://iam.googleapis.com/${this.normalizedWorkloadIdentityProvider}`,u=await jt.getIDToken(t,{audience:a}),c=await ua(this.normalizedWorkloadIdentityProvider,u,{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!c.access_token||!c.expires_in)throw new _("Invalid token response from GCP");o=c.access_token,r.put(Rc,o,c.expires_in-(this.options.expirationOffsetSeconds??300))}let s=await r.get(Pc);if(!s){let a=await ca({serviceAccountEmailOrIdentifier:this.options.serviceAccountEmail,audience:this.options.audience,accessToken:o},{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!a.token)throw new _("Invalid token response from GCP");s=a.token,r.put(Pc,o,3600-(this.options.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${s}`),e}};var Mi,Ic=i(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-jwt"),Y(t,r).required("audience","string").required("serviceAccountJson","string"),Mi||(Mi=await ve.init(t.serviceAccountJson));let o=await Ue({serviceAccount:Mi,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var Ec="https://www.googleapis.com/oauth2/v4/token",Ui,Tc=i(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-service-auth"),Y(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Ui||(Ui=await ve.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=pt(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 ce(r,void 0,t),a;t.useMemoryCacheOnly?a=new We(s):a=new se(s,e);let u=await a.get(r);if(!u){let c=await Ue({serviceAccount:Ui,audience:Ec,payload:o}),l=await qn(Ec,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new _("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new _("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var xc=i(async(n,e,t)=>{f("policy.inbound.validate-json-schema");let r=n.clone(),o;try{o=await r.json()}catch{return T.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator(o))return n;let{errors:a}=t.validator;if(!a)throw new Q("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return T.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var Oc=i(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=i((P,O)=>e(P,"name",{value:O,configurable:!0}),"__name"),o=i((P,O)=>i(function(){return O||(0,P[t(P)[0]])((O={exports:{}}).exports,O),O.exports},"__require"),"__commonJS"),s=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(P){var O={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(k,B){return B},attributeValueProcessor:function(k,B){return B},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(k,B,q){return k}},D=r(function(k){return Object.assign({},O,k)},"buildOptions");P.buildOptions=D,P.defaultOptions=O}}),a=o({"node_modules/fast-xml-parser/src/util.js"(P){"use strict";var O=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",D=O+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",k="["+O+"]["+D+"]*",B=new RegExp("^"+k+"$"),q=r(function(E,Z){let V=[],W=Z.exec(E);for(;W;){let C=[];C.startIndex=Z.lastIndex-W[0].length;let x=W.length;for(let H=0;H<x;H++)C.push(W[H]);V.push(C),W=Z.exec(E)}return V},"getAllMatches"),j=r(function(E){let Z=B.exec(E);return!(Z===null||typeof Z>"u")},"isName");P.isExist=function(E){return typeof E<"u"},P.isEmptyObject=function(E){return Object.keys(E).length===0},P.merge=function(E,Z,V){if(Z){let W=Object.keys(Z),C=W.length;for(let x=0;x<C;x++)V==="strict"?E[W[x]]=[Z[W[x]]]:E[W[x]]=Z[W[x]]}},P.getValue=function(E){return P.isExist(E)?E:""},P.isName=j,P.getAllMatches=q,P.nameRegexp=k}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(P,O){"use strict";var D=class{static{i(this,"XmlNode")}static{r(this,"XmlNode")}constructor(k){this.tagname=k,this.child=[],this[":@"]={}}add(k,B){k==="__proto__"&&(k="#__proto__"),this.child.push({[k]:B})}addChild(k){k.tagname==="__proto__"&&(k.tagname="#__proto__"),k[":@"]&&Object.keys(k[":@"]).length>0?this.child.push({[k.tagname]:k.child,":@":k[":@"]}):this.child.push({[k.tagname]:k.child})}};O.exports=D}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(P,O){var D=a();function k(C,x){let H={};if(C[x+3]==="O"&&C[x+4]==="C"&&C[x+5]==="T"&&C[x+6]==="Y"&&C[x+7]==="P"&&C[x+8]==="E"){x=x+9;let ge=1,X=!1,ne=!1,Se="";for(;x<C.length;x++)if(C[x]==="<"&&!ne){if(X&&j(C,x))x+=7,[entityName,val,x]=B(C,x+1),val.indexOf("&")===-1&&(H[W(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(X&&E(C,x))x+=8;else if(X&&Z(C,x))x+=8;else if(X&&V(C,x))x+=9;else if(q)ne=!0;else throw new Error("Invalid DOCTYPE");ge++,Se=""}else if(C[x]===">"){if(ne?C[x-1]==="-"&&C[x-2]==="-"&&(ne=!1,ge--):ge--,ge===0)break}else C[x]==="["?X=!0:Se+=C[x];if(ge!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:H,i:x}}i(k,"readDocType"),r(k,"readDocType");function B(C,x){let H="";for(;x<C.length&&C[x]!=="'"&&C[x]!=='"';x++)H+=C[x];if(H=H.trim(),H.indexOf(" ")!==-1)throw new Error("External entites are not supported");let ge=C[x++],X="";for(;x<C.length&&C[x]!==ge;x++)X+=C[x];return[H,X,x]}i(B,"readEntityExp"),r(B,"readEntityExp");function q(C,x){return C[x+1]==="!"&&C[x+2]==="-"&&C[x+3]==="-"}i(q,"isComment"),r(q,"isComment");function j(C,x){return C[x+1]==="!"&&C[x+2]==="E"&&C[x+3]==="N"&&C[x+4]==="T"&&C[x+5]==="I"&&C[x+6]==="T"&&C[x+7]==="Y"}i(j,"isEntity"),r(j,"isEntity");function E(C,x){return C[x+1]==="!"&&C[x+2]==="E"&&C[x+3]==="L"&&C[x+4]==="E"&&C[x+5]==="M"&&C[x+6]==="E"&&C[x+7]==="N"&&C[x+8]==="T"}i(E,"isElement"),r(E,"isElement");function Z(C,x){return C[x+1]==="!"&&C[x+2]==="A"&&C[x+3]==="T"&&C[x+4]==="T"&&C[x+5]==="L"&&C[x+6]==="I"&&C[x+7]==="S"&&C[x+8]==="T"}i(Z,"isAttlist"),r(Z,"isAttlist");function V(C,x){return C[x+1]==="!"&&C[x+2]==="N"&&C[x+3]==="O"&&C[x+4]==="T"&&C[x+5]==="A"&&C[x+6]==="T"&&C[x+7]==="I"&&C[x+8]==="O"&&C[x+9]==="N"}i(V,"isNotation"),r(V,"isNotation");function W(C){if(D.isName(C))return C;throw new Error(`Invalid entity name ${C}`)}i(W,"validateEntityName"),r(W,"validateEntityName"),O.exports=k}}),l=o({"../../node_modules/strnum/strnum.js"(P,O){var D=/^[-+]?0x[a-fA-F0-9]+$/,k=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var B={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function q(E,Z={}){if(Z=Object.assign({},B,Z),!E||typeof E!="string")return E;let V=E.trim();if(Z.skipLike!==void 0&&Z.skipLike.test(V))return E;if(Z.hex&&D.test(V))return Number.parseInt(V,16);{let W=k.exec(V);if(W){let C=W[1],x=W[2],H=j(W[3]),ge=W[4]||W[6];if(!Z.leadingZeros&&x.length>0&&C&&V[2]!==".")return E;if(!Z.leadingZeros&&x.length>0&&!C&&V[1]!==".")return E;{let X=Number(V),ne=""+X;return ne.search(/[eE]/)!==-1||ge?Z.eNotation?X:E:V.indexOf(".")!==-1?ne==="0"&&H===""||ne===H||C&&ne==="-"+H?X:E:x?H===ne||C+H===ne?X:E:V===ne||V===C+ne?X:E}}else return E}}i(q,"toNumber"),r(q,"toNumber");function j(E){return E&&E.indexOf(".")!==-1&&(E=E.replace(/0+$/,""),E==="."?E="0":E[0]==="."?E="0"+E:E[E.length-1]==="."&&(E=E.substr(0,E.length-1))),E}i(j,"trimZeros"),r(j,"trimZeros"),O.exports=q}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(P,O){"use strict";var D=a(),k=u(),B=c(),q=l(),j=class{static{i(this,"OrderedObjParser")}static{r(this,"OrderedObjParser")}constructor(R){this.options=R,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(I,L)=>String.fromCharCode(Number.parseInt(L,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(I,L)=>String.fromCharCode(Number.parseInt(L,16))}},this.addExternalEntities=E,this.parseXml=x,this.parseTextData=Z,this.resolveNameSpace=V,this.buildAttributesMap=C,this.isItStopNode=ne,this.replaceEntitiesValue=ge,this.readStopNodeData=G,this.saveTextToParentTag=X,this.addChild=H}};function E(R){let I=Object.keys(R);for(let L=0;L<I.length;L++){let z=I[L];this.lastEntities[z]={regex:new RegExp("&"+z+";","g"),val:R[z]}}}i(E,"addExternalEntities"),r(E,"addExternalEntities");function Z(R,I,L,z,N,M,re){if(R!==void 0&&(this.options.trimValues&&!z&&(R=R.trim()),R.length>0)){re||(R=this.replaceEntitiesValue(R));let $=this.options.tagValueProcessor(I,R,L,N,M);return $==null?R:typeof $!=typeof R||$!==R?$:this.options.trimValues?fe(R,this.options.parseTagValue,this.options.numberParseOptions):R.trim()===R?fe(R,this.options.parseTagValue,this.options.numberParseOptions):R}}i(Z,"parseTextData"),r(Z,"parseTextData");function V(R){if(this.options.removeNSPrefix){let I=R.split(":"),L=R.charAt(0)==="/"?"/":"";if(I[0]==="xmlns")return"";I.length===2&&(R=L+I[1])}return R}i(V,"resolveNameSpace"),r(V,"resolveNameSpace");var W=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function C(R,I,L){if(!this.options.ignoreAttributes&&typeof R=="string"){let z=D.getAllMatches(R,W),N=z.length,M={};for(let re=0;re<N;re++){let $=this.resolveNameSpace(z[re][1]),U=z[re][4],de=this.options.attributeNamePrefix+$;if($.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 ie=this.options.attributeValueProcessor($,U,I);ie==null?M[de]=U:typeof ie!=typeof U||ie!==U?M[de]=ie:M[de]=fe(U,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(M[de]=!0)}if(!Object.keys(M).length)return;if(this.options.attributesGroupName){let re={};return re[this.options.attributesGroupName]=M,re}return M}}i(C,"buildAttributesMap"),r(C,"buildAttributesMap");var x=r(function(R){R=R.replace(/\r\n?/g,`
73
+ `);let I=new k("!xml"),L=I,z="",N="";for(let M=0;M<R.length;M++)if(R[M]==="<")if(R[M+1]==="/"){let $=b(R,">",M,"Closing Tag is not closed."),U=R.substring(M+2,$).trim();if(this.options.removeNSPrefix){let _e=U.indexOf(":");_e!==-1&&(U=U.substr(_e+1))}this.options.transformTagName&&(U=this.options.transformTagName(U)),L&&(z=this.saveTextToParentTag(z,L,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 ie=0;de&&this.options.unpairedTags.indexOf(de)!==-1?(ie=N.lastIndexOf(".",N.lastIndexOf(".")-1),this.tagsNodeStack.pop()):ie=N.lastIndexOf("."),N=N.substring(0,ie),L=this.tagsNodeStack.pop(),z="",M=$}else if(R[M+1]==="?"){let $=S(R,M,!1,"?>");if(!$)throw new Error("Pi Tag is not closed.");if(z=this.saveTextToParentTag(z,L,N),!(this.options.ignoreDeclaration&&$.tagName==="?xml"||this.options.ignorePiTags)){let U=new k($.tagName);U.add(this.options.textNodeName,""),$.tagName!==$.tagExp&&$.attrExpPresent&&(U[":@"]=this.buildAttributesMap($.tagExp,N,$.tagName)),this.addChild(L,U,N)}M=$.closeIndex+1}else if(R.substr(M+1,3)==="!--"){let $=b(R,"-->",M+4,"Comment is not closed.");if(this.options.commentPropName){let U=R.substring(M+4,$-2);z=this.saveTextToParentTag(z,L,N),L.add(this.options.commentPropName,[{[this.options.textNodeName]:U}])}M=$}else if(R.substr(M+1,2)==="!D"){let $=B(R,M);this.docTypeEntities=$.entities,M=$.i}else if(R.substr(M+1,2)==="!["){let $=b(R,"]]>",M,"CDATA is not closed.")-2,U=R.substring(M+9,$);z=this.saveTextToParentTag(z,L,N);let de=this.parseTextData(U,L.tagname,N,!0,!1,!0,!0);de==null&&(de=""),this.options.cdataPropName?L.add(this.options.cdataPropName,[{[this.options.textNodeName]:U}]):L.add(this.options.textNodeName,de),M=$+2}else{let $=S(R,M,this.options.removeNSPrefix),U=$.tagName,de=$.rawTagName,ie=$.tagExp,_e=$.attrExpPresent,Zi=$.closeIndex;this.options.transformTagName&&(U=this.options.transformTagName(U)),L&&z&&L.tagname!=="!xml"&&(z=this.saveTextToParentTag(z,L,N,!1));let Hi=L;if(Hi&&this.options.unpairedTags.indexOf(Hi.tagname)!==-1&&(L=this.tagsNodeStack.pop(),N=N.substring(0,N.lastIndexOf("."))),U!==I.tagname&&(N+=N?"."+U:U),this.isItStopNode(this.options.stopNodes,N,U)){let Ae="";if(ie.length>0&&ie.lastIndexOf("/")===ie.length-1)M=$.closeIndex;else if(this.options.unpairedTags.indexOf(U)!==-1)M=$.closeIndex;else{let Zr=this.readStopNodeData(R,de,Zi+1);if(!Zr)throw new Error(`Unexpected end of ${de}`);M=Zr.i,Ae=Zr.tagContent}let qr=new k(U);U!==ie&&_e&&(qr[":@"]=this.buildAttributesMap(ie,N,U)),Ae&&(Ae=this.parseTextData(Ae,U,N,!0,_e,!0,!0)),N=N.substr(0,N.lastIndexOf(".")),qr.add(this.options.textNodeName,Ae),this.addChild(L,qr,N)}else{if(ie.length>0&&ie.lastIndexOf("/")===ie.length-1){U[U.length-1]==="/"?(U=U.substr(0,U.length-1),N=N.substr(0,N.length-1),ie=U):ie=ie.substr(0,ie.length-1),this.options.transformTagName&&(U=this.options.transformTagName(U));let Ae=new k(U);U!==ie&&_e&&(Ae[":@"]=this.buildAttributesMap(ie,N,U)),this.addChild(L,Ae,N),N=N.substr(0,N.lastIndexOf("."))}else{let Ae=new k(U);this.tagsNodeStack.push(L),U!==ie&&_e&&(Ae[":@"]=this.buildAttributesMap(ie,N,U)),this.addChild(L,Ae,N),L=Ae}z="",M=Zi}}else z+=R[M];return I.child},"parseXml");function H(R,I,L){let z=this.options.updateTag(I.tagname,L,I[":@"]);z===!1||(typeof z=="string"&&(I.tagname=z),R.addChild(I))}i(H,"addChild"),r(H,"addChild");var ge=r(function(R){if(this.options.processEntities){for(let I in this.docTypeEntities){let L=this.docTypeEntities[I];R=R.replace(L.regx,L.val)}for(let I in this.lastEntities){let L=this.lastEntities[I];R=R.replace(L.regex,L.val)}if(this.options.htmlEntities)for(let I in this.htmlEntities){let L=this.htmlEntities[I];R=R.replace(L.regex,L.val)}R=R.replace(this.ampEntity.regex,this.ampEntity.val)}return R},"replaceEntitiesValue");function X(R,I,L,z){return R&&(z===void 0&&(z=Object.keys(I.child).length===0),R=this.parseTextData(R,I.tagname,L,!1,I[":@"]?Object.keys(I[":@"]).length!==0:!1,z),R!==void 0&&R!==""&&I.add(this.options.textNodeName,R),R=""),R}i(X,"saveTextToParentTag"),r(X,"saveTextToParentTag");function ne(R,I,L){let z="*."+L;for(let N in R){let M=R[N];if(z===M||I===M)return!0}return!1}i(ne,"isItStopNode"),r(ne,"isItStopNode");function Se(R,I,L=">"){let z,N="";for(let M=I;M<R.length;M++){let re=R[M];if(z)re===z&&(z="");else if(re==='"'||re==="'")z=re;else if(re===L[0])if(L[1]){if(R[M+1]===L[1])return{data:N,index:M}}else return{data:N,index:M};else re===" "&&(re=" ");N+=re}}i(Se,"tagExpWithClosingIndex"),r(Se,"tagExpWithClosingIndex");function b(R,I,L,z){let N=R.indexOf(I,L);if(N===-1)throw new Error(z);return N+I.length-1}i(b,"findClosingIndex"),r(b,"findClosingIndex");function S(R,I,L,z=">"){let N=Se(R,I+1,z);if(!N)return;let M=N.data,re=N.index,$=M.search(/\s/),U=M,de=!0;$!==-1&&(U=M.substring(0,$),M=M.substring($+1).trimStart());let ie=U;if(L){let _e=U.indexOf(":");_e!==-1&&(U=U.substr(_e+1),de=U!==N.data.substr(_e+1))}return{tagName:U,tagExp:M,closeIndex:re,attrExpPresent:de,rawTagName:ie}}i(S,"readTagExp"),r(S,"readTagExp");function G(R,I,L){let z=L,N=1;for(;L<R.length;L++)if(R[L]==="<")if(R[L+1]==="/"){let M=b(R,">",L,`${I} is not closed`);if(R.substring(L+2,M).trim()===I&&(N--,N===0))return{tagContent:R.substring(z,L),i:M};L=M}else if(R[L+1]==="?")L=b(R,"?>",L+1,"StopNode is not closed.");else if(R.substr(L+1,3)==="!--")L=b(R,"-->",L+3,"StopNode is not closed.");else if(R.substr(L+1,2)==="![")L=b(R,"]]>",L,"StopNode is not closed.")-2;else{let M=S(R,L,">");M&&((M&&M.tagName)===I&&M.tagExp[M.tagExp.length-1]!=="/"&&N++,L=M.closeIndex)}}i(G,"readStopNodeData"),r(G,"readStopNodeData");function fe(R,I,L){if(I&&typeof R=="string"){let z=R.trim();return z==="true"?!0:z==="false"?!1:q(R,L)}else return D.isExist(R)?R:""}i(fe,"parseValue"),r(fe,"parseValue"),O.exports=j}}),p=o({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(P){"use strict";function O(j,E){return D(j,E)}i(O,"prettify"),r(O,"prettify");function D(j,E,Z){let V,W={};for(let C=0;C<j.length;C++){let x=j[C],H=k(x),ge="";if(Z===void 0?ge=H:ge=Z+"."+H,H===E.textNodeName)V===void 0?V=x[H]:V+=""+x[H];else{if(H===void 0)continue;if(x[H]){let X=D(x[H],E,ge),ne=q(X,E);x[":@"]?B(X,x[":@"],ge,E):Object.keys(X).length===1&&X[E.textNodeName]!==void 0&&!E.alwaysCreateTextNode?X=X[E.textNodeName]:Object.keys(X).length===0&&(E.alwaysCreateTextNode?X[E.textNodeName]="":X=""),W[H]!==void 0&&W.hasOwnProperty(H)?(Array.isArray(W[H])||(W[H]=[W[H]]),W[H].push(X)):E.isArray(H,ge,ne)?W[H]=[X]:W[H]=X}}}return typeof V=="string"?V.length>0&&(W[E.textNodeName]=V):V!==void 0&&(W[E.textNodeName]=V),W}i(D,"compress"),r(D,"compress");function k(j){let E=Object.keys(j);for(let Z=0;Z<E.length;Z++){let V=E[Z];if(V!==":@")return V}}i(k,"propName"),r(k,"propName");function B(j,E,Z,V){if(E){let W=Object.keys(E),C=W.length;for(let x=0;x<C;x++){let H=W[x];V.isArray(H,Z+"."+H,!0,!0)?j[H]=[E[H]]:j[H]=E[H]}}}i(B,"assignAttributes"),r(B,"assignAttributes");function q(j,E){let{textNodeName:Z}=E,V=Object.keys(j).length;return!!(V===0||V===1&&(j[Z]||typeof j[Z]=="boolean"||j[Z]===0))}i(q,"isLeafTag"),r(q,"isLeafTag"),P.prettify=O}}),h=o({"node_modules/fast-xml-parser/src/validator.js"(P){"use strict";var O=a(),D={allowBooleanAttributes:!1,unpairedTags:[]};P.validate=function(b,S){S=Object.assign({},D,S);let G=[],fe=!1,R=!1;b[0]==="\uFEFF"&&(b=b.substr(1));for(let I=0;I<b.length;I++)if(b[I]==="<"&&b[I+1]==="?"){if(I+=2,I=B(b,I),I.err)return I}else if(b[I]==="<"){let L=I;if(I++,b[I]==="!"){I=q(b,I);continue}else{let z=!1;b[I]==="/"&&(z=!0,I++);let N="";for(;I<b.length&&b[I]!==">"&&b[I]!==" "&&b[I]!==" "&&b[I]!==`
74
+ `&&b[I]!=="\r";I++)N+=b[I];if(N=N.trim(),N[N.length-1]==="/"&&(N=N.substring(0,N.length-1),I--),!X(N)){let $;return N.trim().length===0?$="Invalid space after '<'.":$="Tag '"+N+"' is an invalid name.",H("InvalidTag",$,ne(b,I))}let M=Z(b,I);if(M===!1)return H("InvalidAttr","Attributes for '"+N+"' have open quote.",ne(b,I));let re=M.value;if(I=M.index,re[re.length-1]==="/"){let $=I-re.length;re=re.substring(0,re.length-1);let U=W(re,S);if(U===!0)fe=!0;else return H(U.err.code,U.err.msg,ne(b,$+U.err.line))}else if(z)if(M.tagClosed){if(re.trim().length>0)return H("InvalidTag","Closing tag '"+N+"' can't have attributes or invalid starting.",ne(b,L));{let $=G.pop();if(N!==$.tagName){let U=ne(b,$.tagStartPos);return H("InvalidTag","Expected closing tag '"+$.tagName+"' (opened in line "+U.line+", col "+U.col+") instead of closing tag '"+N+"'.",ne(b,L))}G.length==0&&(R=!0)}}else return H("InvalidTag","Closing tag '"+N+"' doesn't have proper closing.",ne(b,I));else{let $=W(re,S);if($!==!0)return H($.err.code,$.err.msg,ne(b,I-re.length+$.err.line));if(R===!0)return H("InvalidXml","Multiple possible root nodes found.",ne(b,I));S.unpairedTags.indexOf(N)!==-1||G.push({tagName:N,tagStartPos:L}),fe=!0}for(I++;I<b.length;I++)if(b[I]==="<")if(b[I+1]==="!"){I++,I=q(b,I);continue}else if(b[I+1]==="?"){if(I=B(b,++I),I.err)return I}else break;else if(b[I]==="&"){let $=x(b,I);if($==-1)return H("InvalidChar","char '&' is not expected.",ne(b,I));I=$}else if(R===!0&&!k(b[I]))return H("InvalidXml","Extra text at the end",ne(b,I));b[I]==="<"&&I--}}else{if(k(b[I]))continue;return H("InvalidChar","char '"+b[I]+"' is not expected.",ne(b,I))}if(fe){if(G.length==1)return H("InvalidTag","Unclosed tag '"+G[0].tagName+"'.",ne(b,G[0].tagStartPos));if(G.length>0)return H("InvalidXml","Invalid '"+JSON.stringify(G.map(I=>I.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return H("InvalidXml","Start tag expected.",1);return!0};function k(b){return b===" "||b===" "||b===`
75
+ `||b==="\r"}i(k,"isWhiteSpace"),r(k,"isWhiteSpace");function B(b,S){let G=S;for(;S<b.length;S++)if(b[S]=="?"||b[S]==" "){let fe=b.substr(G,S-G);if(S>5&&fe==="xml")return H("InvalidXml","XML declaration allowed only at the start of the document.",ne(b,S));if(b[S]=="?"&&b[S+1]==">"){S++;break}else continue}return S}i(B,"readPI"),r(B,"readPI");function q(b,S){if(b.length>S+5&&b[S+1]==="-"&&b[S+2]==="-"){for(S+=3;S<b.length;S++)if(b[S]==="-"&&b[S+1]==="-"&&b[S+2]===">"){S+=2;break}}else if(b.length>S+8&&b[S+1]==="D"&&b[S+2]==="O"&&b[S+3]==="C"&&b[S+4]==="T"&&b[S+5]==="Y"&&b[S+6]==="P"&&b[S+7]==="E"){let G=1;for(S+=8;S<b.length;S++)if(b[S]==="<")G++;else if(b[S]===">"&&(G--,G===0))break}else if(b.length>S+9&&b[S+1]==="["&&b[S+2]==="C"&&b[S+3]==="D"&&b[S+4]==="A"&&b[S+5]==="T"&&b[S+6]==="A"&&b[S+7]==="["){for(S+=8;S<b.length;S++)if(b[S]==="]"&&b[S+1]==="]"&&b[S+2]===">"){S+=2;break}}return S}i(q,"readCommentAndCDATA"),r(q,"readCommentAndCDATA");var j='"',E="'";function Z(b,S){let G="",fe="",R=!1;for(;S<b.length;S++){if(b[S]===j||b[S]===E)fe===""?fe=b[S]:fe!==b[S]||(fe="");else if(b[S]===">"&&fe===""){R=!0;break}G+=b[S]}return fe!==""?!1:{value:G,index:S,tagClosed:R}}i(Z,"readAttributeStr"),r(Z,"readAttributeStr");var V=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function W(b,S){let G=O.getAllMatches(b,V),fe={};for(let R=0;R<G.length;R++){if(G[R][1].length===0)return H("InvalidAttr","Attribute '"+G[R][2]+"' has no space in starting.",Se(G[R]));if(G[R][3]!==void 0&&G[R][4]===void 0)return H("InvalidAttr","Attribute '"+G[R][2]+"' is without value.",Se(G[R]));if(G[R][3]===void 0&&!S.allowBooleanAttributes)return H("InvalidAttr","boolean attribute '"+G[R][2]+"' is not allowed.",Se(G[R]));let I=G[R][2];if(!ge(I))return H("InvalidAttr","Attribute '"+I+"' is an invalid name.",Se(G[R]));if(!fe.hasOwnProperty(I))fe[I]=1;else return H("InvalidAttr","Attribute '"+I+"' is repeated.",Se(G[R]))}return!0}i(W,"validateAttributeString"),r(W,"validateAttributeString");function C(b,S){let G=/\d/;for(b[S]==="x"&&(S++,G=/[\da-fA-F]/);S<b.length;S++){if(b[S]===";")return S;if(!b[S].match(G))break}return-1}i(C,"validateNumberAmpersand"),r(C,"validateNumberAmpersand");function x(b,S){if(S++,b[S]===";")return-1;if(b[S]==="#")return S++,C(b,S);let G=0;for(;S<b.length;S++,G++)if(!(b[S].match(/\w/)&&G<20)){if(b[S]===";")break;return-1}return S}i(x,"validateAmpersand"),r(x,"validateAmpersand");function H(b,S,G){return{err:{code:b,msg:S,line:G.line||G,col:G.col}}}i(H,"getErrorObject"),r(H,"getErrorObject");function ge(b){return O.isName(b)}i(ge,"validateAttrName"),r(ge,"validateAttrName");function X(b){return O.isName(b)}i(X,"validateTagName"),r(X,"validateTagName");function ne(b,S){let G=b.substring(0,S).split(/\r?\n/);return{line:G.length,col:G[G.length-1].length+1}}i(ne,"getLineNumberForPosition"),r(ne,"getLineNumberForPosition");function Se(b){return b.startIndex+b[1].length}i(Se,"getPositionFromMatch"),r(Se,"getPositionFromMatch")}}),y=o({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(P,O){var{buildOptions:D}=s(),k=d(),{prettify:B}=p(),q=h(),j=class{static{i(this,"XMLParser")}static{r(this,"XMLParser")}constructor(E){this.externalEntities={},this.options=D(E)}parse(E,Z){if(typeof E!="string")if(E.toString)E=E.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(Z){Z===!0&&(Z={});let C=q.validate(E,Z);if(C!==!0)throw Error(`${C.err.msg}:${C.err.line}:${C.err.col}`)}let V=new k(this.options);V.addExternalEntities(this.externalEntities);let W=V.parseXml(E);return this.options.preserveOrder||W===void 0?W:B(W,this.options)}addEntity(E,Z){if(Z.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(E.indexOf("&")!==-1||E.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(Z==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[E]=Z}};O.exports=j}});let A=y();return new A(n)},"getXmlParser");var Ar=class extends je{static{i(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),f("policy.outbound.xml-to-json"),Y(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?Xe(e.parseOnStatusCodes):void 0,this.parser=Oc({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,t,r){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let o;try{let u=await e.text();o=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw r.log.error(c,u),new _(c)}let s=new Headers(e.headers);return s.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:s})}};var _r=class{static{i(this,"ServiceProviderImpl")}services=new Map;addService(e,t){if(this.services.get(e))throw new Q(`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 Lr=class{static{i(this,"BackgroundDispatcher")}#e;constructor(e,t){if(!t||t.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new ee(t.name??"",t.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),Wn().waitUntil(this.#e.waitUntilFlushed())}};var vc=10,Cc=3e4,kr=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=Cc,this.#r=vc}else{let r=t;this.#n=r.ttlSeconds*1e3,this.#o=r.loaderTimeoutSeconds?r.loaderTimeoutSeconds*1e3:Cc,this.#r=vc}this.#t=e}#s(e){return e.expiry<=new Date}#a(e){let t=this.#i[e];return!(t===void 0||t===0)}#u(e){let t=this.#e.get(e);if(t&&!this.#s(t))return t.data}async get(e){let t=this.#u(e);if(t)return this.#l(e),t;if(this.#a(e))try{await em(()=>this.#u(e)!==void 0||!this.#a,this.#o+this.#r+1,this.#r);let r=this.#u(e);if(r)return r}catch{}return this.#c(e)}#l(e){if(!this.#a(e)){let t=this.#c(e);Wn().waitUntil(t)}}async#c(e){try{this.#i[e]===void 0&&(this.#i[e]=0),this.#i[e]++;let t=await Promise.race([this.#t(e),scheduler.wait(this.#o)]);if(t===void 0)throw new Error(`BackgroundLoader: Loader timed out after ${this.#o} ms.`);return this.#e.set(e,{data:t,expiry:new Date(Date.now()+this.#n)}),t}finally{this.#i[e]--}}};async function em(n,e,t){let r=Date.now();for(;!n();){let o=Date.now()-r;if(o>e)throw new Error(`BackgroundLoader: Timeout waiting for an on-going loader after ${o} ms.`);await scheduler.wait(t)}}i(em,"waitUntilTrue");var qi=["sha-1","sha-256","sha-384","sha-512"],Nr=class{static{i(this,"BaseCryptoBeta")}};var Dr=class extends Nr{static{i(this,"WorkerCryptoBeta")}async digest(e,t){if(!qi.includes(e.toLowerCase()))throw new _(`Algorithm ${e} is not supported. Try using ${qi.join(", ")}`);let r=new TextEncoder().encode(t),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var Mr=class{constructor(e){this.context=e}static{i(this,"BaseKeyValueStore")}};var Ur=class extends Mr{static{i(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let t=m.instance.runtime.ZUPLO_KV;if(!t)throw new wn("The Key Value Store feature is not enabled for this project.");this.#e=t,f("platform.kv-store")}put(e,t,r){if(typeof e!="string")throw new g("value must be of type string");return this.#e.put(e,t,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,t){return this.#e.get(e,{type:"text",cacheTtl:t?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};
75
76
  /*! For license information please see index.js.LEGAL.txt */