@zuplo/runtime 5.2410.0 → 5.2412.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 _c=Object.create;var Bt=Object.defineProperty;var Lc=Object.getOwnPropertyDescriptor;var kc=Object.getOwnPropertyNames;var Nc=Object.getPrototypeOf,Dc=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),Mc=(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 kc(e))!Dc.call(n,o)&&o!==t&&Bt(n,o,{get:()=>e[o],enumerable:!(r=Lc(e,o))||r.enumerable});return n};var ze=(n,e,t)=>(t=n!=null?_c(Nc(n)):{},Fi(e||!n||!n.__esModule?Bt(t,"default",{value:n,enumerable:!0}):t,n)),Uc=n=>Fi(Bt({},"__esModule",{value:!0}),n);var Ji=zt(C=>{"use strict";Object.defineProperty(C,"__esModule",{value:!0});C.generateColor=C.colorFunctions=C.stripColor=C.bgRgb24=C.rgb24=C.bgRgb8=C.rgb8=C.bgBrightWhite=C.bgBrightCyan=C.bgBrightMagenta=C.bgBrightBlue=C.bgBrightYellow=C.bgBrightGreen=C.bgBrightRed=C.bgBrightBlack=C.bgWhite=C.bgCyan=C.bgMagenta=C.bgBlue=C.bgYellow=C.bgGreen=C.bgRed=C.bgBlack=C.brightWhite=C.brightCyan=C.brightMagenta=C.brightBlue=C.brightYellow=C.brightGreen=C.brightRed=C.brightBlack=C.gray=C.white=C.cyan=C.magenta=C.blue=C.yellow=C.green=C.red=C.black=C.strikethrough=C.hidden=C.inverse=C.underline=C.italic=C.dim=C.bold=C.reset=C.getColorEnabled=C.setColorEnabled=void 0;var $i=!0,Hr=!$i;function qc(n){$i||(Hr=n)}i(qc,"setColorEnabled");C.setColorEnabled=qc;function Zc(){return Hr}i(Zc,"getColorEnabled");C.getColorEnabled=Zc;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 Hc(n){return J(n,K([0],0))}i(Hc,"reset");C.reset=Hc;function Fc(n){return J(n,K([1],22))}i(Fc,"bold");C.bold=Fc;function $c(n){return J(n,K([2],22))}i($c,"dim");C.dim=$c;function jc(n){return J(n,K([3],23))}i(jc,"italic");C.italic=jc;function Bc(n){return J(n,K([4],24))}i(Bc,"underline");C.underline=Bc;function zc(n){return J(n,K([7],27))}i(zc,"inverse");C.inverse=zc;function Gc(n){return J(n,K([8],28))}i(Gc,"hidden");C.hidden=Gc;function Vc(n){return J(n,K([9],29))}i(Vc,"strikethrough");C.strikethrough=Vc;function Wc(n){return J(n,K([30],39))}i(Wc,"black");C.black=Wc;function ji(n){return J(n,K([31],39))}i(ji,"red");C.red=ji;function Bi(n){return J(n,K([32],39))}i(Bi,"green");C.green=Bi;function zi(n){return J(n,K([33],39))}i(zi,"yellow");C.yellow=zi;function Gi(n){return J(n,K([34],39))}i(Gi,"blue");C.blue=Gi;function Vi(n){return J(n,K([35],39))}i(Vi,"magenta");C.magenta=Vi;function Wi(n){return J(n,K([36],39))}i(Wi,"cyan");C.cyan=Wi;function Kc(n){return J(n,K([37],39))}i(Kc,"white");C.white=Kc;function Jc(n){return Ki(n)}i(Jc,"gray");C.gray=Jc;function Ki(n){return J(n,K([90],39))}i(Ki,"brightBlack");C.brightBlack=Ki;function Qc(n){return J(n,K([91],39))}i(Qc,"brightRed");C.brightRed=Qc;function Yc(n){return J(n,K([92],39))}i(Yc,"brightGreen");C.brightGreen=Yc;function Xc(n){return J(n,K([93],39))}i(Xc,"brightYellow");C.brightYellow=Xc;function el(n){return J(n,K([94],39))}i(el,"brightBlue");C.brightBlue=el;function tl(n){return J(n,K([95],39))}i(tl,"brightMagenta");C.brightMagenta=tl;function nl(n){return J(n,K([96],39))}i(nl,"brightCyan");C.brightCyan=nl;function rl(n){return J(n,K([97],39))}i(rl,"brightWhite");C.brightWhite=rl;function ol(n){return J(n,K([40],49))}i(ol,"bgBlack");C.bgBlack=ol;function il(n){return J(n,K([41],49))}i(il,"bgRed");C.bgRed=il;function sl(n){return J(n,K([42],49))}i(sl,"bgGreen");C.bgGreen=sl;function al(n){return J(n,K([43],49))}i(al,"bgYellow");C.bgYellow=al;function ul(n){return J(n,K([44],49))}i(ul,"bgBlue");C.bgBlue=ul;function cl(n){return J(n,K([45],49))}i(cl,"bgMagenta");C.bgMagenta=cl;function ll(n){return J(n,K([46],49))}i(ll,"bgCyan");C.bgCyan=ll;function dl(n){return J(n,K([47],49))}i(dl,"bgWhite");C.bgWhite=dl;function pl(n){return J(n,K([100],49))}i(pl,"bgBrightBlack");C.bgBrightBlack=pl;function ml(n){return J(n,K([101],49))}i(ml,"bgBrightRed");C.bgBrightRed=ml;function gl(n){return J(n,K([102],49))}i(gl,"bgBrightGreen");C.bgBrightGreen=gl;function fl(n){return J(n,K([103],49))}i(fl,"bgBrightYellow");C.bgBrightYellow=fl;function hl(n){return J(n,K([104],49))}i(hl,"bgBrightBlue");C.bgBrightBlue=hl;function yl(n){return J(n,K([105],49))}i(yl,"bgBrightMagenta");C.bgBrightMagenta=yl;function bl(n){return J(n,K([106],49))}i(bl,"bgBrightCyan");C.bgBrightCyan=bl;function wl(n){return J(n,K([107],49))}i(wl,"bgBrightWhite");C.bgBrightWhite=wl;function Ge(n,e=255,t=0){return Math.trunc(Math.max(Math.min(n,e),t))}i(Ge,"clampAndTruncate");function Rl(n,e){return J(n,K([38,5,Ge(e)],39))}i(Rl,"rgb8");C.rgb8=Rl;function Pl(n,e){return J(n,K([48,5,Ge(e)],49))}i(Pl,"bgRgb8");C.bgRgb8=Pl;function Il(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(Il,"rgb24");C.rgb24=Il;function El(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(El,"bgRgb24");C.bgRgb24=El;var Tl=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 xl(n){return n.replace(Tl,"")}i(xl,"stripColor");C.stripColor=xl;C.colorFunctions=[ji,Bi,zi,Gi,Vi,Wi];function Ol(n){let e=0,t=n.length,r=0;if(t>0)for(;r<t;)e=(e<<5)-e+n.charCodeAt(r++)|0;return e}i(Ol,"hashCode");function vl(n){let e=Math.abs(Ol(n));return C.colorFunctions[e%C.colorFunctions.length]}i(vl,"generateColor");C.generateColor=vl});var Qi=zt(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.format=void 0;function Cl(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(Cl,"format");mn.format=Cl});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:Sl,showHidden:e??!1,depth:t??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=_l),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 Sl(n,e){return n}i(Sl,"stylizeNoColor");function Al(n){return typeof n=="boolean"}i(Al,"isBoolean");function Xi(n){return n===void 0}i(Xi,"isUndefined");function _l(n,e){let t=st.styles[e];return t?"\x1B["+st.colors[t][0]+"m"+n+"\x1B["+st.colors[t][1]+"m":n}i(_l,"stylizeWithColor");function Fr(n){return typeof n=="function"}i(Fr,"isFunction");function es(n){return typeof n=="string"}i(es,"isString");function Ll(n){return typeof n=="number"}i(Ll,"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 kl(n){let e={};return n.forEach(function(t,r){e[t]=!0}),e}i(kl,"arrayToHash");function Nl(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(Nl,"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=Dl(n,e);if(r)return r;let o=Object.keys(e),s=kl(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=Nl(n,e,t,s,o):l=o.map(function(d){return zr(n,e,t,s,d,u)}),n.seen.pop(),Ml(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(`
25
+ "use strict";var _c=Object.create;var zt=Object.defineProperty;var Lc=Object.getOwnPropertyDescriptor;var kc=Object.getOwnPropertyNames;var Nc=Object.getPrototypeOf,Dc=Object.prototype.hasOwnProperty;var i=(n,e)=>zt(n,"name",{value:e,configurable:!0});var Bt=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Mc=(n,e)=>{for(var t in e)zt(n,t,{get:e[t],enumerable:!0})},Fi=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of kc(e))!Dc.call(n,o)&&o!==t&&zt(n,o,{get:()=>e[o],enumerable:!(r=Lc(e,o))||r.enumerable});return n};var Be=(n,e,t)=>(t=n!=null?_c(Nc(n)):{},Fi(e||!n||!n.__esModule?zt(t,"default",{value:n,enumerable:!0}):t,n)),Uc=n=>Fi(zt({},"__esModule",{value:!0}),n);var Ji=Bt(C=>{"use strict";Object.defineProperty(C,"__esModule",{value:!0});C.generateColor=C.colorFunctions=C.stripColor=C.bgRgb24=C.rgb24=C.bgRgb8=C.rgb8=C.bgBrightWhite=C.bgBrightCyan=C.bgBrightMagenta=C.bgBrightBlue=C.bgBrightYellow=C.bgBrightGreen=C.bgBrightRed=C.bgBrightBlack=C.bgWhite=C.bgCyan=C.bgMagenta=C.bgBlue=C.bgYellow=C.bgGreen=C.bgRed=C.bgBlack=C.brightWhite=C.brightCyan=C.brightMagenta=C.brightBlue=C.brightYellow=C.brightGreen=C.brightRed=C.brightBlack=C.gray=C.white=C.cyan=C.magenta=C.blue=C.yellow=C.green=C.red=C.black=C.strikethrough=C.hidden=C.inverse=C.underline=C.italic=C.dim=C.bold=C.reset=C.getColorEnabled=C.setColorEnabled=void 0;var $i=!0,Hr=!$i;function qc(n){$i||(Hr=n)}i(qc,"setColorEnabled");C.setColorEnabled=qc;function Zc(){return Hr}i(Zc,"getColorEnabled");C.getColorEnabled=Zc;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 Hc(n){return J(n,K([0],0))}i(Hc,"reset");C.reset=Hc;function Fc(n){return J(n,K([1],22))}i(Fc,"bold");C.bold=Fc;function $c(n){return J(n,K([2],22))}i($c,"dim");C.dim=$c;function jc(n){return J(n,K([3],23))}i(jc,"italic");C.italic=jc;function zc(n){return J(n,K([4],24))}i(zc,"underline");C.underline=zc;function Bc(n){return J(n,K([7],27))}i(Bc,"inverse");C.inverse=Bc;function Gc(n){return J(n,K([8],28))}i(Gc,"hidden");C.hidden=Gc;function Vc(n){return J(n,K([9],29))}i(Vc,"strikethrough");C.strikethrough=Vc;function Wc(n){return J(n,K([30],39))}i(Wc,"black");C.black=Wc;function ji(n){return J(n,K([31],39))}i(ji,"red");C.red=ji;function zi(n){return J(n,K([32],39))}i(zi,"green");C.green=zi;function Bi(n){return J(n,K([33],39))}i(Bi,"yellow");C.yellow=Bi;function Gi(n){return J(n,K([34],39))}i(Gi,"blue");C.blue=Gi;function Vi(n){return J(n,K([35],39))}i(Vi,"magenta");C.magenta=Vi;function Wi(n){return J(n,K([36],39))}i(Wi,"cyan");C.cyan=Wi;function Kc(n){return J(n,K([37],39))}i(Kc,"white");C.white=Kc;function Jc(n){return Ki(n)}i(Jc,"gray");C.gray=Jc;function Ki(n){return J(n,K([90],39))}i(Ki,"brightBlack");C.brightBlack=Ki;function Qc(n){return J(n,K([91],39))}i(Qc,"brightRed");C.brightRed=Qc;function Yc(n){return J(n,K([92],39))}i(Yc,"brightGreen");C.brightGreen=Yc;function Xc(n){return J(n,K([93],39))}i(Xc,"brightYellow");C.brightYellow=Xc;function el(n){return J(n,K([94],39))}i(el,"brightBlue");C.brightBlue=el;function tl(n){return J(n,K([95],39))}i(tl,"brightMagenta");C.brightMagenta=tl;function nl(n){return J(n,K([96],39))}i(nl,"brightCyan");C.brightCyan=nl;function rl(n){return J(n,K([97],39))}i(rl,"brightWhite");C.brightWhite=rl;function ol(n){return J(n,K([40],49))}i(ol,"bgBlack");C.bgBlack=ol;function il(n){return J(n,K([41],49))}i(il,"bgRed");C.bgRed=il;function sl(n){return J(n,K([42],49))}i(sl,"bgGreen");C.bgGreen=sl;function al(n){return J(n,K([43],49))}i(al,"bgYellow");C.bgYellow=al;function ul(n){return J(n,K([44],49))}i(ul,"bgBlue");C.bgBlue=ul;function cl(n){return J(n,K([45],49))}i(cl,"bgMagenta");C.bgMagenta=cl;function ll(n){return J(n,K([46],49))}i(ll,"bgCyan");C.bgCyan=ll;function dl(n){return J(n,K([47],49))}i(dl,"bgWhite");C.bgWhite=dl;function pl(n){return J(n,K([100],49))}i(pl,"bgBrightBlack");C.bgBrightBlack=pl;function ml(n){return J(n,K([101],49))}i(ml,"bgBrightRed");C.bgBrightRed=ml;function gl(n){return J(n,K([102],49))}i(gl,"bgBrightGreen");C.bgBrightGreen=gl;function fl(n){return J(n,K([103],49))}i(fl,"bgBrightYellow");C.bgBrightYellow=fl;function hl(n){return J(n,K([104],49))}i(hl,"bgBrightBlue");C.bgBrightBlue=hl;function yl(n){return J(n,K([105],49))}i(yl,"bgBrightMagenta");C.bgBrightMagenta=yl;function bl(n){return J(n,K([106],49))}i(bl,"bgBrightCyan");C.bgBrightCyan=bl;function wl(n){return J(n,K([107],49))}i(wl,"bgBrightWhite");C.bgBrightWhite=wl;function Ge(n,e=255,t=0){return Math.trunc(Math.max(Math.min(n,e),t))}i(Ge,"clampAndTruncate");function Rl(n,e){return J(n,K([38,5,Ge(e)],39))}i(Rl,"rgb8");C.rgb8=Rl;function Pl(n,e){return J(n,K([48,5,Ge(e)],49))}i(Pl,"bgRgb8");C.bgRgb8=Pl;function Il(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(Il,"rgb24");C.rgb24=Il;function El(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(El,"bgRgb24");C.bgRgb24=El;var Tl=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 xl(n){return n.replace(Tl,"")}i(xl,"stripColor");C.stripColor=xl;C.colorFunctions=[ji,zi,Bi,Gi,Vi,Wi];function Ol(n){let e=0,t=n.length,r=0;if(t>0)for(;r<t;)e=(e<<5)-e+n.charCodeAt(r++)|0;return e}i(Ol,"hashCode");function vl(n){let e=Math.abs(Ol(n));return C.colorFunctions[e%C.colorFunctions.length]}i(vl,"generateColor");C.generateColor=vl});var Qi=Bt(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.format=void 0;function Cl(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(Cl,"format");mn.format=Cl});var rs=Bt(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.inspect=void 0;function st(n,e,t,r){let o={seen:[],stylize:Sl,showHidden:e??!1,depth:t??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=_l),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 Sl(n,e){return n}i(Sl,"stylizeNoColor");function Al(n){return typeof n=="boolean"}i(Al,"isBoolean");function Xi(n){return n===void 0}i(Xi,"isUndefined");function _l(n,e){let t=st.styles[e];return t?"\x1B["+st.colors[t][0]+"m"+n+"\x1B["+st.colors[t][1]+"m":n}i(_l,"stylizeWithColor");function Fr(n){return typeof n=="function"}i(Fr,"isFunction");function es(n){return typeof n=="string"}i(es,"isString");function Ll(n){return typeof n=="number"}i(Ll,"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 kl(n){let e={};return n.forEach(function(t,r){e[t]=!0}),e}i(kl,"arrayToHash");function Nl(n,e,t,r,o){let s=[];for(let a=0,u=e.length;a<u;++a)ns(e,String(a))?s.push(Br(n,e,t,r,String(a),!0)):s.push("");return o.forEach(function(a){a.match(/^\d+$/)||s.push(Br(n,e,t,r,a,!0))}),s}i(Nl,"formatArray");function zr(n){return"["+Error.prototype.toString.call(n)+"]"}i(zr,"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=Dl(n,e);if(r)return r;let o=Object.keys(e),s=kl(o);try{n.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(jr(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return zr(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 zr(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=" "+zr(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=Nl(n,e,t,s,o):l=o.map(function(d){return Br(n,e,t,s,d,u)}),n.seen.pop(),Ml(l,a,c)}i(gn,"formatValue");function Br(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")),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 Dl(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(Ll(e))return n.stylize(""+e,"number");if(Al(e))return n.stylize(""+e,"boolean");if(ts(e))return n.stylize("null","null")}i(Dl,"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(Br,"formatProperty");function Dl(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(Ll(e))return n.stylize(""+e,"number");if(Al(e))return n.stylize(""+e,"boolean");if(ts(e))return n.stylize("null","null")}i(Dl,"formatPrimitive");function Ml(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=zt(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.format=void 0;var Ul=Qi(),ql=rs(),Zl=i((n,...e)=>(0,Ul.format)(ql.inspect,n,e),"format");hn.format=Zl});var He=zt(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.debug=Ve.withoutEnv=Ve.Debugger=void 0;var Hl=Ji(),Fl=os(),yn=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=(0,Hl.generateColor)(t),this.last=0,this.enabled=e.enabled.some(r=>r.test(t))}log(...e){if(!this.enabled)return;let t,r=e[0];typeof r=="function"?t=r():t=String(r);let o=Date.now()-(this.last||Date.now());t=(0,Fl.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 $l(n){n||(n=[]),typeof n=="string"&&(n=is(n)),Gt=new bn(n)}i($l,"withoutEnv");Ve.withoutEnv=$l;function jl(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(jl,"debug");Ve.debug=jl});var im={};Mc(im,{AWSLoggingPlugin:()=>rr,AmberfloMeteringInboundPolicy:()=>eu,AmberfloMeteringPolicy:()=>lr,ApiAuthKeyInboundPolicy:()=>ru,ApiKeyInboundPolicy:()=>dr,AuditLogDataStaxProvider:()=>sr,AuditLogPlugin:()=>ar,Auth0JwtInboundPolicy:()=>su,AwsLambdaHandlerExtensions:()=>Na,AxiomaticsAuthZInboundPolicy:()=>gr,BackgroundDispatcher:()=>Lr,BackgroundLoader:()=>kr,BasicAuthInboundPolicy:()=>au,BasicRateLimitInboundPolicy:()=>Ai,BatchDispatch:()=>ee,BrownoutInboundPolicy:()=>yr,CachingInboundPolicy:()=>cu,ChangeMethodInboundPolicy:()=>lu,ClearHeadersInboundPolicy:()=>pu,ClearHeadersOutboundPolicy:()=>mu,ClerkJwtInboundPolicy:()=>gu,CognitoJwtInboundPolicy:()=>fu,ComplexRateLimitInboundPolicy:()=>Rr,CompositeInboundPolicy:()=>bu,ConfigurationError:()=>f,ContentTypes:()=>xn,ContextData:()=>ue,CryptoBeta:()=>Dr,CurityPhantomTokenInboundPolicy:()=>wu,DataDogLoggingPlugin:()=>Bn,DataDogMetricsPlugin:()=>or,DynaTraceLoggingPlugin:()=>Xn,DynatraceMetricsPlugin:()=>ir,FirebaseJwtInboundPolicy:()=>Ru,FormDataToJsonInboundPolicy:()=>Pu,GeoFilterInboundPolicy:()=>Iu,GoogleCloudLoggingPlugin:()=>Fn,Handler:()=>Qn,HttpProblems:()=>x,HttpStatusCode:()=>Yt,InboundPolicy:()=>le,JWTScopeValidationInboundPolicy:()=>Eu,KeyValueStore:()=>Ur,LokiLoggingPlugin:()=>er,LookupResult:()=>xt,MemoryZoneReadThroughCache:()=>se,MockApiInboundPolicy:()=>xu,MoesifInboundPolicy:()=>_u,MonetizationInboundPolicy:()=>Ir,OktaFGAAuthZInboundPolicy:()=>xr,OktaJwtInboundPolicy:()=>Hu,OpenFGAAuthZInboundPolicy:()=>Or,OpenIdJwtInboundPolicy:()=>we,OutboundPolicy:()=>je,ProblemResponseFormatter:()=>Je,PropelAuthJwtInboundPolicy:()=>$u,QuotaInboundPolicy:()=>wr,RateLimitInboundPolicy:()=>Ai,ReadmeMetricsInboundPolicy:()=>Ju,RemoveHeadersInboundPolicy:()=>Qu,RemoveHeadersOutboundPolicy:()=>Yu,RemoveQueryParamsInboundPolicy:()=>Xu,ReplaceStringOutboundPolicy:()=>ec,RequestSizeLimitInboundPolicy:()=>nc,RequestValidationInboundPolicy:()=>ki,RequireOriginInboundPolicy:()=>lc,ResponseSendingEvent:()=>Rt,ResponseSentEvent:()=>Pt,Router:()=>Ot,RuntimeError:()=>L,SYSTEM_LOGGER:()=>Kt,SchemaBasedRequestValidation:()=>cc,SemanticAttributes:()=>Le,ServiceProviderImpl:()=>_r,SetBodyInboundPolicy:()=>dc,SetHeadersInboundPolicy:()=>pc,SetHeadersOutboundPolicy:()=>mc,SetQueryParamsInboundPolicy:()=>gc,SetStatusOutboundPolicy:()=>fc,SleepInboundPolicy:()=>hc,StripeMonetizationPlugin:()=>gi,StripeWebhookVerificationInboundPolicy:()=>At,SumoLogicLoggingPlugin:()=>tr,SupabaseJwtInboundPolicy:()=>yc,SystemRouteName:()=>Me,TelemetryPlugin:()=>bt,UpstreamAzureAdServiceAuthInboundPolicy:()=>bc,UpstreamFirebaseAdminAuthInboundPolicy:()=>Rc,UpstreamFirebaseUserAuthInboundPolicy:()=>Pc,UpstreamGcpFederatedAuthInboundPolicy:()=>Sr,UpstreamGcpJwtInboundPolicy:()=>Tc,UpstreamGcpServiceAuthInboundPolicy:()=>Oc,VMWareLogInsightLoggingPlugin:()=>nr,ValidateJsonSchemaInbound:()=>vc,XmlToJsonOutboundPolicy:()=>Ar,ZoneCache:()=>yt,ZuploRequest:()=>oe,ZuploServices:()=>jt,awsLambdaHandler:()=>Da,environment:()=>Ee,getIdForParameterSchema:()=>vr,getIdForRefSchema:()=>oc,getIdForRequestBodySchema:()=>Cr,getRawOperationDataIdentifierName:()=>rc,httpStatuses:()=>Cn,openApiSpecHandler:()=>Ma,redirectHandler:()=>Ua,sanitizedIdentifierName:()=>it,serialize:()=>On,setMoesifContext:()=>Au,trackFeature:()=>y,urlForwardHandler:()=>qa,urlRewriteHandler:()=>Za,webSocketHandler:()=>Ha,webSocketPipelineHandler:()=>ja});module.exports=Uc(im);var ds=ze(He());var Q=class extends Error{static{i(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},L=class extends Error{static{i(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},f=class extends L{static{i(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}},wn=class extends L{static{i(this,"FeatureNotEnabledError")}constructor(e,t){super(e,t),this.name="FeatureNotEnabledError"}};function Bl(n){if(n.length>=255)throw new TypeError("Alphabet too long");let e=new Uint8Array(256);for(let l=0;l<e.length;l++)e[l]=255;for(let l=0;l<n.length;l++){let d=n.charAt(l),p=d.charCodeAt(0);if(e[p]!==255)throw new TypeError(d+" is ambiguous");e[p]=l}let t=n.length,r=n.charAt(0),o=Math.log(t)/Math.log(256),s=Math.log(256)/Math.log(t);function a(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";let d=0,p=0,g=0,h=l.length;for(;g!==h&&l[g]===0;)g++,d++;let v=(h-g)*s+1>>>0,b=new Uint8Array(v);for(;g!==h;){let A=l[g],$=0;for(let N=v-1;(A!==0||$<p)&&N!==-1;N--,$++)A+=256*b[N]>>>0,b[N]=A%t>>>0,A=A/t>>>0;if(A!==0)throw new Error("Non-zero carry");p=$,g++}let I=v-p;for(;I!==v&&b[I]===0;)I++;let D=r.repeat(d);for(;I<v;++I)D+=n.charAt(b[I]);return D}i(a,"encode");function u(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let d=0,p=0,g=0;for(;l[d]===r;)p++,d++;let h=(l.length-d)*o+1>>>0,v=new Uint8Array(h);for(;l[d];){let A=e[l.charCodeAt(d)];if(A===255)return;let $=0;for(let N=h-1;(A!==0||$<g)&&N!==-1;N--,$++)A+=t*v[N]>>>0,v[N]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");g=$,d++}let b=h-g;for(;b!==h&&v[b]===0;)b++;let I=new Uint8Array(p+(h-b)),D=p;for(;b!==h;)I[D++]=v[b++];return I}i(u,"decodeUnsafe");function c(l){let d=u(l);if(d)return d;throw new Error("Non-base"+t+" character")}return i(c,"decode"),{encode:a,decodeUnsafe:u,decode:c}}i(Bl,"base");var ss=Bl;var zl="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",as=ss(zl);var Wr="2024-03-14",us=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 cs(){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:us[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(cs,"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=cs()),this.#e}constructor({build:e,runtime:t}){let r;try{if(t.__ZUPLO_CONFIG){let o=atob(t.__ZUPLO_CONFIG);r=JSON.parse(o)}if(t.ZUPLO_SYSTEM_CONFIGURATIONS){let o=new TextDecoder().decode(as.decode(t.ZUPLO_SYSTEM_CONFIGURATIONS)),s=JSON.parse(o);for(let a of Object.keys(s))t[a]=s[a]}}catch(o){console.error("Failed to parse runtime configuration",o)}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,ds.debug)("zuplo:runtime:external-service");function Gl(){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(Gl,"getServiceAuth");async function ps(n,e){let t=Gl();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 Vl(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw at("Cannot use sha256 service routing, missing build variables"),new L("Failed to generate fully qualified tunnel url.")}let c=new URL(`${u}${r.pathname}${r.search}`);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 L("Could not connect to secure tunnel.");return l}else throw at("Cannot call external service with Request object"),new L("Currently, we only support fetch(<some_string>, ...).");else throw at("There is no external service auth configured for this zup."),new L("There are no external services configured for this zup.")}i(ps,"externalServiceHandler");async function Vl(n,e,t,r){let o=n.toLowerCase(),s=e.toLowerCase(),a=t.toLowerCase(),u=Wl(r);at(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await ls(`${s}-${o}`),l=await ls(`${s}-${a}-${u}`);return`${c}.${l}`}i(Vl,"hashServiceName");async function ls(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(ls,"hashSegment");function Wl(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(Wl,"sanitizeEnvironmentType");var gs=new Map;gs.set("service:",ps);var ms=globalThis.fetch;function Kr(n,e){let t=Kl(e);if(typeof n=="string"){let r=new URL(n),o=gs.get(r.protocol);return o?o(n,t):ms(n,t)}else return ms(n,t)}i(Kr,"internalFetch");globalThis.fetch=Kr;var Kl=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 Jl={fetch:Kr},F=Jl;Function.prototype.toString=function(){return"[native code]"};var Rn=globalThis,fs=Rn.caches;if(fs){let n=fs.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 hs=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=hs.get(e);r||(r=new Jr(t),hs.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 ys="zuplo-request-id",ut="zp-rid",Yr="zp-body-removed",ct="cf-ray",bs="x-real-ip",Xr="cf-ipcity",eo="cf-ipcontinent",to="cf-ipcountry",no="cf-iplongitude",ro="cf-iplatitude",ws="cf-region",Rs="cf-region-code",Ps="cf-metro-code",Is="cf-postal-code",Es="cf-timezone",Ts="zp-ipcity",xs="zp-ipcontinent",Os="zp-ipcountry",vs="zp-iplongitude",Cs="zp-iplatitude",Ss="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",As=[Xr,eo,to,no,ro,oo,io,so,ao,uo,co,lo,po],_s=["zp-","cf-"],Ls=[ut,ct,Yr];var Vt=Symbol("zuplo_meters"),Wt=Symbol("zuplo_dynamic_meters"),Kt="system-logger";var wa=require("@opentelemetry/api"),Ra=ze(He());var vn=require("@opentelemetry/api");var Qe=require("@opentelemetry/api");var ks=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function Ns(n){ks=n}i(Ns,"setTelemetryInitFunction");var Ds=i(n=>ks(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,Ms=new Set;function y(n){Ms.has(n)||(Ms.add(n),In.add(n))}i(y,"trackFeature");function Us(){let n=[...In];return In.clear(),n}i(Us,"getUnsentFeatures");function qs(n){for(let e of n)In.add(e)}i(qs,"restoreFeatures");var Jt=class n{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=i(async e=>{let t=e.problem,r=JSON.stringify(t,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})},"problemResponseFormat");static setProblemResponseFormat(e){e&&(y("runtime.problem-response-formatter"),n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(s){throw new L("Error in custom 'problemResponseFormat'",{cause:s})}})}},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)}},Hs=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 f(`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"),Fs=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 f(`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"),$s=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"),Zs=!1;async function js(n){if(!Zs){n&&(y("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});Ns(t)}for(let e of $e)e instanceof Fe&&await e.initialize(Tn);Jt.setProblemResponseFormat(Tn.problemResponseFormat),Zs=!0}}i(js,"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=i((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()}}),"#errorWrappedHandler");#t=i(({processors:e,gateway:t,handler:r})=>async(o,s)=>{let a=[...e],u=i(async b=>{let I=a.pop();return I?I(o,s,t,u):await this.#e(async $=>{let N=await r($,s);return Ql(N)},t)(b,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 g=Pe.getContextExtensions(s),h=g.latestRequest,v;try{v=await p.mutableResponse}catch(b){return s.log.error(b),t.errorHandler(o,s,b)}try{v=await g.onResponseSending(v,h,s)}catch(b){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),t.errorHandler(o,s,b)}try{v=await Fs(v,h,s)}catch(b){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),t.errorHandler(o,s,b)}s.dispatchEvent(new Pt(o,v));try{await g.onResponseSendingFinal(l,h,s)}catch(b){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}try{await $s(l,h,s)}catch(b){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}return v},"#toZuploPipeline")};function Ql(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(On(n),{headers:{"content-type":"application/json"}})}i(Ql,"resultToResponse");var Yt=(R=>(R[R.CONTINUE=100]="CONTINUE",R[R.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",R[R.PROCESSING=102]="PROCESSING",R[R.EARLY_HINTS=103]="EARLY_HINTS",R[R.OK=200]="OK",R[R.CREATED=201]="CREATED",R[R.ACCEPTED=202]="ACCEPTED",R[R.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",R[R.NO_CONTENT=204]="NO_CONTENT",R[R.RESET_CONTENT=205]="RESET_CONTENT",R[R.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",R[R.MULTI_STATUS=207]="MULTI_STATUS",R[R.ALREADY_REPORTED=208]="ALREADY_REPORTED",R[R.IM_USED=226]="IM_USED",R[R.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",R[R.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",R[R.FOUND=302]="FOUND",R[R.SEE_OTHER=303]="SEE_OTHER",R[R.NOT_MODIFIED=304]="NOT_MODIFIED",R[R.USE_PROXY=305]="USE_PROXY",R[R.SWITCH_PROXY=306]="SWITCH_PROXY",R[R.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",R[R.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",R[R.BAD_REQUEST=400]="BAD_REQUEST",R[R.UNAUTHORIZED=401]="UNAUTHORIZED",R[R.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",R[R.FORBIDDEN=403]="FORBIDDEN",R[R.NOT_FOUND=404]="NOT_FOUND",R[R.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",R[R.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",R[R.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",R[R.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",R[R.CONFLICT=409]="CONFLICT",R[R.GONE=410]="GONE",R[R.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",R[R.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",R[R.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",R[R.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",R[R.URI_TOO_LONG=414]="URI_TOO_LONG",R[R.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",R[R.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",R[R.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",R[R.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",R[R.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",R[R.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",R[R.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",R[R.LOCKED=423]="LOCKED",R[R.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",R[R.TOO_EARLY=425]="TOO_EARLY",R[R.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",R[R.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",R[R.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",R[R.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",R[R.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",R[R.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",R[R.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",R[R.BAD_GATEWAY=502]="BAD_GATEWAY",R[R.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",R[R.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",R[R.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",R[R.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",R[R.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",R[R.LOOP_DETECTED=508]="LOOP_DETECTED",R[R.NOT_EXTENDED=510]="NOT_EXTENDED",R[R.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",R))(Yt||{}),Bs={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 Yl={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=Yl;function Xl(n){return`${new URL(n.url).pathname}`}i(Xl,"instance");function ed(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(ed,"trace");var td=i((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:Xl(e),trace:ed(e,t),...r},additionalHeaders:o,statusText:Cn[n.status]}),"merge"),ho=class{static{i(this,"HttpProblemsBase")}static format=i((e,t,r)=>"problem"in e?Je.format(e,t,r):Je.format({problem:e},t,r),"format");static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:Bs[e],...t}}},x=class extends ho{static{i(this,"HttpProblems")}static#e(e,t,r,o,s){let a=td(this.getProblemFromStatus(e),t,r,o,s);return Je.format(a,t,r)}static continue=i((e,t,r,o)=>this.#e(200,e,t,r,o),"continue");static switchingProtocols=i((e,t,r,o)=>this.#e(101,e,t,r,o),"switchingProtocols");static processing=i((e,t,r,o)=>this.#e(102,e,t,r,o),"processing");static earlyHints=i((e,t,r,o)=>this.#e(103,e,t,r,o),"earlyHints");static ok=i((e,t,r,o)=>this.#e(200,e,t,r,o),"ok");static created=i((e,t,r,o)=>this.#e(201,e,t,r,o),"created");static accepted=i((e,t,r,o)=>this.#e(202,e,t,r,o),"accepted");static nonAuthoritativeInformation=i((e,t,r,o)=>this.#e(203,e,t,r,o),"nonAuthoritativeInformation");static noContent=i((e,t,r,o)=>this.#e(204,e,t,r,o),"noContent");static resetContent=i((e,t,r,o)=>this.#e(205,e,t,r,o),"resetContent");static partialContent=i((e,t,r,o)=>this.#e(206,e,t,r,o),"partialContent");static multiStatus=i((e,t,r,o)=>this.#e(207,e,t,r,o),"multiStatus");static alreadyReported=i((e,t,r,o)=>this.#e(208,e,t,r,o),"alreadyReported");static imUsed=i((e,t,r,o)=>this.#e(226,e,t,r,o),"imUsed");static multipleChoices=i((e,t,r,o)=>this.#e(300,e,t,r,o),"multipleChoices");static movedPermanently=i((e,t,r,o)=>this.#e(301,e,t,r,o),"movedPermanently");static found=i((e,t,r,o)=>this.#e(302,e,t,r,o),"found");static seeOther=i((e,t,r,o)=>this.#e(303,e,t,r,o),"seeOther");static notModified=i((e,t,r,o)=>this.#e(304,e,t,r,o),"notModified");static useProxy=i((e,t,r,o)=>this.#e(305,e,t,r,o),"useProxy");static switchProxy=i((e,t,r,o)=>this.#e(306,e,t,r,o),"switchProxy");static temporaryRedirect=i((e,t,r,o)=>this.#e(307,e,t,r,o),"temporaryRedirect");static permanentRedirect=i((e,t,r,o)=>this.#e(308,e,t,r,o),"permanentRedirect");static badRequest=i((e,t,r,o)=>this.#e(400,e,t,r,o),"badRequest");static unauthorized=i((e,t,r,o)=>this.#e(401,e,t,r,o),"unauthorized");static paymentRequired=i((e,t,r,o)=>this.#e(402,e,t,r,o),"paymentRequired");static forbidden=i((e,t,r,o)=>this.#e(403,e,t,r,o),"forbidden");static notFound=i((e,t,r,o)=>this.#e(404,e,t,r,o),"notFound");static methodNotAllowed=i((e,t,r,o)=>this.#e(405,e,t,r,o),"methodNotAllowed");static notAcceptable=i((e,t,r,o)=>this.#e(406,e,t,r,o),"notAcceptable");static proxyAuthenticationRequired=i((e,t,r,o)=>this.#e(407,e,t,r,o),"proxyAuthenticationRequired");static requestTimeout=i((e,t,r,o)=>this.#e(408,e,t,r,o),"requestTimeout");static conflict=i((e,t,r,o)=>this.#e(409,e,t,r,o),"conflict");static gone=i((e,t,r,o)=>this.#e(410,e,t,r,o),"gone");static lengthRequired=i((e,t,r,o)=>this.#e(411,e,t,r,o),"lengthRequired");static preconditionFailed=i((e,t,r,o)=>this.#e(412,e,t,r,o),"preconditionFailed");static contentTooLarge=i((e,t,r,o)=>this.#e(413,e,t,r,o),"contentTooLarge");static uriTooLong=i((e,t,r,o)=>this.#e(414,e,t,r,o),"uriTooLong");static unsupportedMediaType=i((e,t,r,o)=>this.#e(415,e,t,r,o),"unsupportedMediaType");static rangeNotSatisfiable=i((e,t,r,o)=>this.#e(416,e,t,r,o),"rangeNotSatisfiable");static expectationFailed=i((e,t,r,o)=>this.#e(417,e,t,r,o),"expectationFailed");static imATeapot=i((e,t,r,o)=>this.#e(418,e,t,r,o),"imATeapot");static misdirectedRequest=i((e,t,r,o)=>this.#e(421,e,t,r,o),"misdirectedRequest");static unprocessableContent=i((e,t,r,o)=>this.#e(422,e,t,r,o),"unprocessableContent");static locked=i((e,t,r,o)=>this.#e(423,e,t,r,o),"locked");static failedDependency=i((e,t,r,o)=>this.#e(424,e,t,r,o),"failedDependency");static tooEarly=i((e,t,r,o)=>this.#e(425,e,t,r,o),"tooEarly");static upgradeRequired=i((e,t,r,o)=>this.#e(426,e,t,r,o),"upgradeRequired");static preconditionRequired=i((e,t,r,o)=>this.#e(428,e,t,r,o),"preconditionRequired");static tooManyRequests=i((e,t,r,o)=>this.#e(429,e,t,r,o),"tooManyRequests");static requestHeaderFieldsTooLarge=i((e,t,r,o)=>this.#e(431,e,t,r,o),"requestHeaderFieldsTooLarge");static unavailableForLegalReasons=i((e,t,r,o)=>this.#e(451,e,t,r,o),"unavailableForLegalReasons");static internalServerError=i((e,t,r,o)=>this.#e(500,e,t,r,o),"internalServerError");static notImplemented=i((e,t,r,o)=>this.#e(501,e,t,r,o),"notImplemented");static badGateway=i((e,t,r,o)=>this.#e(502,e,t,r,o),"badGateway");static serviceUnavailable=i((e,t,r,o)=>this.#e(503,e,t,r,o),"serviceUnavailable");static gatewayTimeout=i((e,t,r,o)=>this.#e(504,e,t,r,o),"gatewayTimeout");static httpVersionNotSupported=i((e,t,r,o)=>this.#e(505,e,t,r,o),"httpVersionNotSupported");static variantAlsoNegotiates=i((e,t,r,o)=>this.#e(506,e,t,r,o),"variantAlsoNegotiates");static insufficientStorage=i((e,t,r,o)=>this.#e(507,e,t,r,o),"insufficientStorage");static loopDetected=i((e,t,r,o)=>this.#e(508,e,t,r,o),"loopDetected");static notExtended=i((e,t,r,o)=>this.#e(510,e,t,r,o),"notExtended");static networkAuthenticationRequired=i((e,t,r,o)=>this.#e(511,e,t,r,o),"networkAuthenticationRequired")};var 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=i(e=>{this.#o.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{t()})}},this.#i)}))},"enqueue");waitUntilFlushed=i(async()=>{if(this.#e)return this.#e},"waitUntilFlushed")};var Sn=class{static{i(this,"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=i(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=Us(),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),qs(u)}},"dispatchFunction")};var pe=class{static{i(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:r,systemRouteName:o,corsPolicy:s="none"}){this.label=e,this.path=t,this.methods=r,this.corsPolicy=s,this.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(Ss)??void 0,l=e.incomingRequestProperties,d;e.route instanceof pe&&(d=e.route.systemRouteName);let p=Pe.getContextExtensions(e).latestRequest,g={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},h=[];return h.push(new Sn(e)),$e.forEach(v=>{if(v instanceof Ye){let b=v.getTransport();h.push(b)}}),h.forEach(v=>{v.pushMetrics(g,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 x.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:nd}=Object.prototype,{propertyIsEnumerable:rd}=Object.prototype;function bo(n){return nd.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 zs(n){return bo(n)==="[object RegExp]"}i(zs,"isRegexp");function Gs(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>rd.call(n,e))]}i(Gs,"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 Vs(n){return typeof n>"u"}i(Vs,"isUndefined");function Ws(n){return Vs(n)||n===null}i(Ws,"isUndefinedOrNull");function en(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(en,"isErrorLike");var Ks=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=Ks.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 Ks.set(n,r),r}i(Xe,"statusCodesStringToNumberArray");function dt(n,e,t){if(!e.startsWith("."))throw new f(`Invalid ${t} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=n;return r.forEach(s=>{if(o===void 0)throw new L(`Error applying ${t} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i(dt,"getValueFromRequestUser");function pt(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new f("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 f(`Expected type of string, received type '${typeof n}'`)}i(pt,"parseValueToStringArray");function Js(n){if(n==null)return[];if(!Array.isArray(n))throw new f(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!lt(t))throw new f(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!It(t.name))throw new f("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!wo(t.maxAge))throw new f(`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 f("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 f(`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(Js,"parseCorsPolicies");function Po(n,e){let t;if(n[e]!==void 0)try{t=pt(n[e])}catch(r){throw new f(`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 x.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let g=n.lookup(l,c);if(!g)return x.notFound(a,u);let h=g.routeConfiguration,v=od(l,d,p,h,t);return v.isValid?new Response(void 0,{status:200,statusText:"OK",headers:v.headers}):(v.error&&u.log.warn(v.error),x.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"),od=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 f(`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 Qs=i((n,e)=>{let t=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new he({processors:[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"}),Ys=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 x.notFound(o,s)},"notFoundHandler"),r=new he({processors:[Ie],handler:t,gateway:e});n.addRoute(Eo,r.execute)},"registerNotMatchedHandler");var id=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Xs=i(n=>{id.forEach(e=>n.delete(e))},"stripCorsHeaders"),Ln=i(async(n,e,t,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await r(n),p=new Headers(d.headers);return Xs(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await r(n);if(!(s instanceof Response))throw new Q(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=sd(o,t.routeData.corsPolicies),u=ad(n,a),c=new Headers(s.headers);return Xs(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(s.body,{status:s.status,statusText:s.statusText,headers:c,webSocket:s.webSocket})},"corsProcessor"),sd=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 f(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),ad=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 L(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},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 f(`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 f(`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 f(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new f(`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 f(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new f(`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 L("Internal error. Policy not found in cache.");return a})}i(tn,"getInboundPolicyInstances");var Oo=new Map;function ud(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 f(`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 f(`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 f(`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 f(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new f(`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 L("Internal error. Policy not found in cache.");return s})}i(ud,"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 g=new f(`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(g),g}});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"),cd=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 g=new f(`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(g),g}}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=ud(e.route,t.routeData.policies);return ta({request:n,context:e,inboundPolicies:o,outboundPolicies:s,gateway:t,next:r})},"policyProcessor");function ea({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>ta({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(ea,"createInternalPolicyProcessor");async function ta({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:s}){let a=So(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await s(u),l=cd(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(ta,"executePolicyProcessor");function na(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||ld,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]=dd(l,o)}s=u+1}return t}i(na,"parse");function ld(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}i(ld,"decode");function dd(n,e){try{return e(n)}catch{return n}}i(dd,"tryDecode");function ra(n,e){try{let t=/v\d+(-\d+)?/g,o=na(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}i(ra,"devPortalBaseURL");var oa="/__zuplo/dev-portal",pd="dev-portal-id",md="dev-portal-host",gd="zp-account",fd="zp-project",hd="dev-portal-build",yd=`
35
+ `)+" "+t[1]:t[0]+e+" "+n.join(", ")+" "+t[1]}i(Ml,"reduceToSingleString")});var os=Bt(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.format=void 0;var Ul=Qi(),ql=rs(),Zl=i((n,...e)=>(0,Ul.format)(ql.inspect,n,e),"format");hn.format=Zl});var He=Bt(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.debug=Ve.withoutEnv=Ve.Debugger=void 0;var Hl=Ji(),Fl=os(),yn=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=(0,Hl.generateColor)(t),this.last=0,this.enabled=e.enabled.some(r=>r.test(t))}log(...e){if(!this.enabled)return;let t,r=e[0];typeof r=="function"?t=r():t=String(r);let o=Date.now()-(this.last||Date.now());t=(0,Fl.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 $l(n){n||(n=[]),typeof n=="string"&&(n=is(n)),Gt=new bn(n)}i($l,"withoutEnv");Ve.withoutEnv=$l;function jl(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(jl,"debug");Ve.debug=jl});var im={};Mc(im,{AWSLoggingPlugin:()=>rr,AmberfloMeteringInboundPolicy:()=>eu,AmberfloMeteringPolicy:()=>lr,ApiAuthKeyInboundPolicy:()=>ru,ApiKeyInboundPolicy:()=>dr,AuditLogDataStaxProvider:()=>sr,AuditLogPlugin:()=>ar,Auth0JwtInboundPolicy:()=>su,AwsLambdaHandlerExtensions:()=>Na,AxiomaticsAuthZInboundPolicy:()=>gr,BackgroundDispatcher:()=>Lr,BackgroundLoader:()=>kr,BasicAuthInboundPolicy:()=>au,BasicRateLimitInboundPolicy:()=>Ai,BatchDispatch:()=>ee,BrownoutInboundPolicy:()=>yr,CachingInboundPolicy:()=>cu,ChangeMethodInboundPolicy:()=>lu,ClearHeadersInboundPolicy:()=>pu,ClearHeadersOutboundPolicy:()=>mu,ClerkJwtInboundPolicy:()=>gu,CognitoJwtInboundPolicy:()=>fu,ComplexRateLimitInboundPolicy:()=>Rr,CompositeInboundPolicy:()=>bu,ConfigurationError:()=>f,ContentTypes:()=>xn,ContextData:()=>ue,CryptoBeta:()=>Dr,CurityPhantomTokenInboundPolicy:()=>wu,DataDogLoggingPlugin:()=>zn,DataDogMetricsPlugin:()=>or,DynaTraceLoggingPlugin:()=>Xn,DynatraceMetricsPlugin:()=>ir,FirebaseJwtInboundPolicy:()=>Ru,FormDataToJsonInboundPolicy:()=>Pu,GeoFilterInboundPolicy:()=>Iu,GoogleCloudLoggingPlugin:()=>Fn,Handler:()=>Qn,HttpProblems:()=>x,HttpStatusCode:()=>Yt,InboundPolicy:()=>le,JWTScopeValidationInboundPolicy:()=>Eu,KeyValueStore:()=>Ur,LokiLoggingPlugin:()=>er,LookupResult:()=>xt,MemoryZoneReadThroughCache:()=>se,MockApiInboundPolicy:()=>xu,MoesifInboundPolicy:()=>_u,MonetizationInboundPolicy:()=>Ir,OktaFGAAuthZInboundPolicy:()=>xr,OktaJwtInboundPolicy:()=>Hu,OpenFGAAuthZInboundPolicy:()=>Or,OpenIdJwtInboundPolicy:()=>we,OutboundPolicy:()=>je,ProblemResponseFormatter:()=>Je,PropelAuthJwtInboundPolicy:()=>$u,QuotaInboundPolicy:()=>wr,RateLimitInboundPolicy:()=>Ai,ReadmeMetricsInboundPolicy:()=>Ju,RemoveHeadersInboundPolicy:()=>Qu,RemoveHeadersOutboundPolicy:()=>Yu,RemoveQueryParamsInboundPolicy:()=>Xu,ReplaceStringOutboundPolicy:()=>ec,RequestSizeLimitInboundPolicy:()=>nc,RequestValidationInboundPolicy:()=>ki,RequireOriginInboundPolicy:()=>lc,ResponseSendingEvent:()=>Rt,ResponseSentEvent:()=>Pt,Router:()=>Ot,RuntimeError:()=>L,SYSTEM_LOGGER:()=>Kt,SchemaBasedRequestValidation:()=>cc,SemanticAttributes:()=>Le,ServiceProviderImpl:()=>_r,SetBodyInboundPolicy:()=>dc,SetHeadersInboundPolicy:()=>pc,SetHeadersOutboundPolicy:()=>mc,SetQueryParamsInboundPolicy:()=>gc,SetStatusOutboundPolicy:()=>fc,SleepInboundPolicy:()=>hc,StripeMonetizationPlugin:()=>gi,StripeWebhookVerificationInboundPolicy:()=>At,SumoLogicLoggingPlugin:()=>tr,SupabaseJwtInboundPolicy:()=>yc,SystemRouteName:()=>Me,TelemetryPlugin:()=>bt,UpstreamAzureAdServiceAuthInboundPolicy:()=>bc,UpstreamFirebaseAdminAuthInboundPolicy:()=>Rc,UpstreamFirebaseUserAuthInboundPolicy:()=>Pc,UpstreamGcpFederatedAuthInboundPolicy:()=>Sr,UpstreamGcpJwtInboundPolicy:()=>Tc,UpstreamGcpServiceAuthInboundPolicy:()=>Oc,VMWareLogInsightLoggingPlugin:()=>nr,ValidateJsonSchemaInbound:()=>vc,XmlToJsonOutboundPolicy:()=>Ar,ZoneCache:()=>yt,ZuploRequest:()=>oe,ZuploServices:()=>jt,awsLambdaHandler:()=>Da,environment:()=>Ee,getIdForParameterSchema:()=>vr,getIdForRefSchema:()=>oc,getIdForRequestBodySchema:()=>Cr,getRawOperationDataIdentifierName:()=>rc,httpStatuses:()=>Cn,openApiSpecHandler:()=>Ma,redirectHandler:()=>Ua,sanitizedIdentifierName:()=>it,serialize:()=>On,setMoesifContext:()=>Au,trackFeature:()=>y,urlForwardHandler:()=>qa,urlRewriteHandler:()=>Za,webSocketHandler:()=>Ha,webSocketPipelineHandler:()=>ja});module.exports=Uc(im);var ds=Be(He());var Q=class extends Error{static{i(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},L=class extends Error{static{i(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},f=class extends L{static{i(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}},wn=class extends L{static{i(this,"FeatureNotEnabledError")}constructor(e,t){super(e,t),this.name="FeatureNotEnabledError"}};function zl(n){if(n.length>=255)throw new TypeError("Alphabet too long");let e=new Uint8Array(256);for(let l=0;l<e.length;l++)e[l]=255;for(let l=0;l<n.length;l++){let d=n.charAt(l),p=d.charCodeAt(0);if(e[p]!==255)throw new TypeError(d+" is ambiguous");e[p]=l}let t=n.length,r=n.charAt(0),o=Math.log(t)/Math.log(256),s=Math.log(256)/Math.log(t);function a(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";let d=0,p=0,g=0,h=l.length;for(;g!==h&&l[g]===0;)g++,d++;let v=(h-g)*s+1>>>0,b=new Uint8Array(v);for(;g!==h;){let A=l[g],$=0;for(let N=v-1;(A!==0||$<p)&&N!==-1;N--,$++)A+=256*b[N]>>>0,b[N]=A%t>>>0,A=A/t>>>0;if(A!==0)throw new Error("Non-zero carry");p=$,g++}let I=v-p;for(;I!==v&&b[I]===0;)I++;let D=r.repeat(d);for(;I<v;++I)D+=n.charAt(b[I]);return D}i(a,"encode");function u(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let d=0,p=0,g=0;for(;l[d]===r;)p++,d++;let h=(l.length-d)*o+1>>>0,v=new Uint8Array(h);for(;l[d];){let A=e[l.charCodeAt(d)];if(A===255)return;let $=0;for(let N=h-1;(A!==0||$<g)&&N!==-1;N--,$++)A+=t*v[N]>>>0,v[N]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");g=$,d++}let b=h-g;for(;b!==h&&v[b]===0;)b++;let I=new Uint8Array(p+(h-b)),D=p;for(;b!==h;)I[D++]=v[b++];return I}i(u,"decodeUnsafe");function c(l){let d=u(l);if(d)return d;throw new Error("Non-base"+t+" character")}return i(c,"decode"),{encode:a,decodeUnsafe:u,decode:c}}i(zl,"base");var ss=zl;var Bl="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",as=ss(Bl);var Wr="2024-03-14",us=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 cs(){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:us[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(cs,"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=cs()),this.#e}constructor({build:e,runtime:t}){let r;try{if(t.__ZUPLO_CONFIG){let o=atob(t.__ZUPLO_CONFIG);r=JSON.parse(o)}if(t.ZUPLO_SYSTEM_CONFIGURATIONS){let o=new TextDecoder().decode(as.decode(t.ZUPLO_SYSTEM_CONFIGURATIONS)),s=JSON.parse(o);for(let a of Object.keys(s))t[a]=s[a]}}catch(o){console.error("Failed to parse runtime configuration",o)}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,ds.debug)("zuplo:runtime:external-service");function Gl(){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(Gl,"getServiceAuth");async function ps(n,e){let t=Gl();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 Vl(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw at("Cannot use sha256 service routing, missing build variables"),new L("Failed to generate fully qualified tunnel url.")}let c=new URL(`${u}${r.pathname}${r.search}`);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 L("Could not connect to secure tunnel.");return l}else throw at("Cannot call external service with Request object"),new L("Currently, we only support fetch(<some_string>, ...).");else throw at("There is no external service auth configured for this zup."),new L("There are no external services configured for this zup.")}i(ps,"externalServiceHandler");async function Vl(n,e,t,r){let o=n.toLowerCase(),s=e.toLowerCase(),a=t.toLowerCase(),u=Wl(r);at(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await ls(`${s}-${o}`),l=await ls(`${s}-${a}-${u}`);return`${c}.${l}`}i(Vl,"hashServiceName");async function ls(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(ls,"hashSegment");function Wl(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(Wl,"sanitizeEnvironmentType");var gs=new Map;gs.set("service:",ps);var ms=globalThis.fetch;function Kr(n,e){let t=Kl(e);if(typeof n=="string"){let r=new URL(n),o=gs.get(r.protocol);return o?o(n,t):ms(n,t)}else return ms(n,t)}i(Kr,"internalFetch");globalThis.fetch=Kr;var Kl=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 Jl={fetch:Kr},F=Jl;Function.prototype.toString=function(){return"[native code]"};var Rn=globalThis,fs=Rn.caches;if(fs){let n=fs.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 hs=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=hs.get(e);r||(r=new Jr(t),hs.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 ys="zuplo-request-id",ut="zp-rid",Yr="zp-body-removed",ct="cf-ray",bs="x-real-ip",Xr="cf-ipcity",eo="cf-ipcontinent",to="cf-ipcountry",no="cf-iplongitude",ro="cf-iplatitude",ws="cf-region",Rs="cf-region-code",Ps="cf-metro-code",Is="cf-postal-code",Es="cf-timezone",Ts="zp-ipcity",xs="zp-ipcontinent",Os="zp-ipcountry",vs="zp-iplongitude",Cs="zp-iplatitude",Ss="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",As=[Xr,eo,to,no,ro,oo,io,so,ao,uo,co,lo,po],_s=["zp-","cf-"],Ls=[ut,ct,Yr];var Vt=Symbol("zuplo_meters"),Wt=Symbol("zuplo_dynamic_meters"),Kt="system-logger";var wa=require("@opentelemetry/api"),Ra=Be(He());var vn=require("@opentelemetry/api");var Qe=require("@opentelemetry/api");var ks=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function Ns(n){ks=n}i(Ns,"setTelemetryInitFunction");var Ds=i(n=>ks(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,Ms=new Set;function y(n){Ms.has(n)||(Ms.add(n),In.add(n))}i(y,"trackFeature");function Us(){let n=[...In];return In.clear(),n}i(Us,"getUnsentFeatures");function qs(n){for(let e of n)In.add(e)}i(qs,"restoreFeatures");var Jt=class n{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=i(async e=>{let t=e.problem,r=JSON.stringify(t,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})},"problemResponseFormat");static setProblemResponseFormat(e){e&&(y("runtime.problem-response-formatter"),n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(s){throw new L("Error in custom 'problemResponseFormat'",{cause:s})}})}},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)}},Hs=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 f(`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"),Fs=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 f(`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"),$s=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"),Zs=!1;async function js(n){if(!Zs){n&&(y("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});Ns(t)}for(let e of $e)e instanceof Fe&&await e.initialize(Tn);Jt.setProblemResponseFormat(Tn.problemResponseFormat),Zs=!0}}i(js,"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=i((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()}}),"#errorWrappedHandler");#t=i(({processors:e,gateway:t,handler:r})=>async(o,s)=>{let a=[...e],u=i(async b=>{let I=a.pop();return I?I(o,s,t,u):await this.#e(async $=>{let N=await r($,s);return Ql(N)},t)(b,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 g=Pe.getContextExtensions(s),h=g.latestRequest,v;try{v=await p.mutableResponse}catch(b){return s.log.error(b),t.errorHandler(o,s,b)}try{v=await g.onResponseSending(v,h,s)}catch(b){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),t.errorHandler(o,s,b)}try{v=await Fs(v,h,s)}catch(b){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),t.errorHandler(o,s,b)}s.dispatchEvent(new Pt(o,v));try{await g.onResponseSendingFinal(l,h,s)}catch(b){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}try{await $s(l,h,s)}catch(b){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}return v},"#toZuploPipeline")};function Ql(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(On(n),{headers:{"content-type":"application/json"}})}i(Ql,"resultToResponse");var Yt=(R=>(R[R.CONTINUE=100]="CONTINUE",R[R.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",R[R.PROCESSING=102]="PROCESSING",R[R.EARLY_HINTS=103]="EARLY_HINTS",R[R.OK=200]="OK",R[R.CREATED=201]="CREATED",R[R.ACCEPTED=202]="ACCEPTED",R[R.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",R[R.NO_CONTENT=204]="NO_CONTENT",R[R.RESET_CONTENT=205]="RESET_CONTENT",R[R.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",R[R.MULTI_STATUS=207]="MULTI_STATUS",R[R.ALREADY_REPORTED=208]="ALREADY_REPORTED",R[R.IM_USED=226]="IM_USED",R[R.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",R[R.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",R[R.FOUND=302]="FOUND",R[R.SEE_OTHER=303]="SEE_OTHER",R[R.NOT_MODIFIED=304]="NOT_MODIFIED",R[R.USE_PROXY=305]="USE_PROXY",R[R.SWITCH_PROXY=306]="SWITCH_PROXY",R[R.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",R[R.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",R[R.BAD_REQUEST=400]="BAD_REQUEST",R[R.UNAUTHORIZED=401]="UNAUTHORIZED",R[R.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",R[R.FORBIDDEN=403]="FORBIDDEN",R[R.NOT_FOUND=404]="NOT_FOUND",R[R.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",R[R.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",R[R.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",R[R.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",R[R.CONFLICT=409]="CONFLICT",R[R.GONE=410]="GONE",R[R.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",R[R.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",R[R.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",R[R.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",R[R.URI_TOO_LONG=414]="URI_TOO_LONG",R[R.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",R[R.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",R[R.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",R[R.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",R[R.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",R[R.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",R[R.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",R[R.LOCKED=423]="LOCKED",R[R.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",R[R.TOO_EARLY=425]="TOO_EARLY",R[R.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",R[R.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",R[R.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",R[R.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",R[R.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",R[R.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",R[R.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",R[R.BAD_GATEWAY=502]="BAD_GATEWAY",R[R.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",R[R.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",R[R.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",R[R.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",R[R.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",R[R.LOOP_DETECTED=508]="LOOP_DETECTED",R[R.NOT_EXTENDED=510]="NOT_EXTENDED",R[R.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",R))(Yt||{}),zs={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Content Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Content",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};var Yl={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=Yl;function Xl(n){return`${new URL(n.url).pathname}`}i(Xl,"instance");function ed(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(ed,"trace");var td=i((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:Xl(e),trace:ed(e,t),...r},additionalHeaders:o,statusText:Cn[n.status]}),"merge"),ho=class{static{i(this,"HttpProblemsBase")}static format=i((e,t,r)=>"problem"in e?Je.format(e,t,r):Je.format({problem:e},t,r),"format");static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:zs[e],...t}}},x=class extends ho{static{i(this,"HttpProblems")}static#e(e,t,r,o,s){let a=td(this.getProblemFromStatus(e),t,r,o,s);return Je.format(a,t,r)}static continue=i((e,t,r,o)=>this.#e(200,e,t,r,o),"continue");static switchingProtocols=i((e,t,r,o)=>this.#e(101,e,t,r,o),"switchingProtocols");static processing=i((e,t,r,o)=>this.#e(102,e,t,r,o),"processing");static earlyHints=i((e,t,r,o)=>this.#e(103,e,t,r,o),"earlyHints");static ok=i((e,t,r,o)=>this.#e(200,e,t,r,o),"ok");static created=i((e,t,r,o)=>this.#e(201,e,t,r,o),"created");static accepted=i((e,t,r,o)=>this.#e(202,e,t,r,o),"accepted");static nonAuthoritativeInformation=i((e,t,r,o)=>this.#e(203,e,t,r,o),"nonAuthoritativeInformation");static noContent=i((e,t,r,o)=>this.#e(204,e,t,r,o),"noContent");static resetContent=i((e,t,r,o)=>this.#e(205,e,t,r,o),"resetContent");static partialContent=i((e,t,r,o)=>this.#e(206,e,t,r,o),"partialContent");static multiStatus=i((e,t,r,o)=>this.#e(207,e,t,r,o),"multiStatus");static alreadyReported=i((e,t,r,o)=>this.#e(208,e,t,r,o),"alreadyReported");static imUsed=i((e,t,r,o)=>this.#e(226,e,t,r,o),"imUsed");static multipleChoices=i((e,t,r,o)=>this.#e(300,e,t,r,o),"multipleChoices");static movedPermanently=i((e,t,r,o)=>this.#e(301,e,t,r,o),"movedPermanently");static found=i((e,t,r,o)=>this.#e(302,e,t,r,o),"found");static seeOther=i((e,t,r,o)=>this.#e(303,e,t,r,o),"seeOther");static notModified=i((e,t,r,o)=>this.#e(304,e,t,r,o),"notModified");static useProxy=i((e,t,r,o)=>this.#e(305,e,t,r,o),"useProxy");static switchProxy=i((e,t,r,o)=>this.#e(306,e,t,r,o),"switchProxy");static temporaryRedirect=i((e,t,r,o)=>this.#e(307,e,t,r,o),"temporaryRedirect");static permanentRedirect=i((e,t,r,o)=>this.#e(308,e,t,r,o),"permanentRedirect");static badRequest=i((e,t,r,o)=>this.#e(400,e,t,r,o),"badRequest");static unauthorized=i((e,t,r,o)=>this.#e(401,e,t,r,o),"unauthorized");static paymentRequired=i((e,t,r,o)=>this.#e(402,e,t,r,o),"paymentRequired");static forbidden=i((e,t,r,o)=>this.#e(403,e,t,r,o),"forbidden");static notFound=i((e,t,r,o)=>this.#e(404,e,t,r,o),"notFound");static methodNotAllowed=i((e,t,r,o)=>this.#e(405,e,t,r,o),"methodNotAllowed");static notAcceptable=i((e,t,r,o)=>this.#e(406,e,t,r,o),"notAcceptable");static proxyAuthenticationRequired=i((e,t,r,o)=>this.#e(407,e,t,r,o),"proxyAuthenticationRequired");static requestTimeout=i((e,t,r,o)=>this.#e(408,e,t,r,o),"requestTimeout");static conflict=i((e,t,r,o)=>this.#e(409,e,t,r,o),"conflict");static gone=i((e,t,r,o)=>this.#e(410,e,t,r,o),"gone");static lengthRequired=i((e,t,r,o)=>this.#e(411,e,t,r,o),"lengthRequired");static preconditionFailed=i((e,t,r,o)=>this.#e(412,e,t,r,o),"preconditionFailed");static contentTooLarge=i((e,t,r,o)=>this.#e(413,e,t,r,o),"contentTooLarge");static uriTooLong=i((e,t,r,o)=>this.#e(414,e,t,r,o),"uriTooLong");static unsupportedMediaType=i((e,t,r,o)=>this.#e(415,e,t,r,o),"unsupportedMediaType");static rangeNotSatisfiable=i((e,t,r,o)=>this.#e(416,e,t,r,o),"rangeNotSatisfiable");static expectationFailed=i((e,t,r,o)=>this.#e(417,e,t,r,o),"expectationFailed");static imATeapot=i((e,t,r,o)=>this.#e(418,e,t,r,o),"imATeapot");static misdirectedRequest=i((e,t,r,o)=>this.#e(421,e,t,r,o),"misdirectedRequest");static unprocessableContent=i((e,t,r,o)=>this.#e(422,e,t,r,o),"unprocessableContent");static locked=i((e,t,r,o)=>this.#e(423,e,t,r,o),"locked");static failedDependency=i((e,t,r,o)=>this.#e(424,e,t,r,o),"failedDependency");static tooEarly=i((e,t,r,o)=>this.#e(425,e,t,r,o),"tooEarly");static upgradeRequired=i((e,t,r,o)=>this.#e(426,e,t,r,o),"upgradeRequired");static preconditionRequired=i((e,t,r,o)=>this.#e(428,e,t,r,o),"preconditionRequired");static tooManyRequests=i((e,t,r,o)=>this.#e(429,e,t,r,o),"tooManyRequests");static requestHeaderFieldsTooLarge=i((e,t,r,o)=>this.#e(431,e,t,r,o),"requestHeaderFieldsTooLarge");static unavailableForLegalReasons=i((e,t,r,o)=>this.#e(451,e,t,r,o),"unavailableForLegalReasons");static internalServerError=i((e,t,r,o)=>this.#e(500,e,t,r,o),"internalServerError");static notImplemented=i((e,t,r,o)=>this.#e(501,e,t,r,o),"notImplemented");static badGateway=i((e,t,r,o)=>this.#e(502,e,t,r,o),"badGateway");static serviceUnavailable=i((e,t,r,o)=>this.#e(503,e,t,r,o),"serviceUnavailable");static gatewayTimeout=i((e,t,r,o)=>this.#e(504,e,t,r,o),"gatewayTimeout");static httpVersionNotSupported=i((e,t,r,o)=>this.#e(505,e,t,r,o),"httpVersionNotSupported");static variantAlsoNegotiates=i((e,t,r,o)=>this.#e(506,e,t,r,o),"variantAlsoNegotiates");static insufficientStorage=i((e,t,r,o)=>this.#e(507,e,t,r,o),"insufficientStorage");static loopDetected=i((e,t,r,o)=>this.#e(508,e,t,r,o),"loopDetected");static notExtended=i((e,t,r,o)=>this.#e(510,e,t,r,o),"notExtended");static networkAuthenticationRequired=i((e,t,r,o)=>this.#e(511,e,t,r,o),"networkAuthenticationRequired")};var 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=i(e=>{this.#o.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{t()})}},this.#i)}))},"enqueue");waitUntilFlushed=i(async()=>{if(this.#e)return this.#e},"waitUntilFlushed")};var Sn=class{static{i(this,"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=i(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=Us(),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),qs(u)}},"dispatchFunction")};var pe=class{static{i(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:r,systemRouteName:o,corsPolicy:s="none"}){this.label=e,this.path=t,this.methods=r,this.corsPolicy=s,this.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(Ss)??void 0,l=e.incomingRequestProperties,d;e.route instanceof pe&&(d=e.route.systemRouteName);let p=Pe.getContextExtensions(e).latestRequest,g={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},h=[];return h.push(new Sn(e)),$e.forEach(v=>{if(v instanceof Ye){let b=v.getTransport();h.push(b)}}),h.forEach(v=>{v.pushMetrics(g,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 x.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:nd}=Object.prototype,{propertyIsEnumerable:rd}=Object.prototype;function bo(n){return nd.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 Bs(n){return bo(n)==="[object RegExp]"}i(Bs,"isRegexp");function Gs(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>rd.call(n,e))]}i(Gs,"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 Vs(n){return typeof n>"u"}i(Vs,"isUndefined");function Ws(n){return Vs(n)||n===null}i(Ws,"isUndefinedOrNull");function en(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(en,"isErrorLike");var Ks=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=Ks.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 Ks.set(n,r),r}i(Xe,"statusCodesStringToNumberArray");function dt(n,e,t){if(!e.startsWith("."))throw new f(`Invalid ${t} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=n;return r.forEach(s=>{if(o===void 0)throw new L(`Error applying ${t} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i(dt,"getValueFromRequestUser");function pt(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new f("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 f(`Expected type of string, received type '${typeof n}'`)}i(pt,"parseValueToStringArray");function Js(n){if(n==null)return[];if(!Array.isArray(n))throw new f(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!lt(t))throw new f(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!It(t.name))throw new f("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!wo(t.maxAge))throw new f(`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 f("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 f(`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(Js,"parseCorsPolicies");function Po(n,e){let t;if(n[e]!==void 0)try{t=pt(n[e])}catch(r){throw new f(`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 x.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let g=n.lookup(l,c);if(!g)return x.notFound(a,u);let h=g.routeConfiguration,v=od(l,d,p,h,t);return v.isValid?new Response(void 0,{status:200,statusText:"OK",headers:v.headers}):(v.error&&u.log.warn(v.error),x.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"),od=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 f(`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 Qs=i((n,e)=>{let t=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new he({processors:[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"}),Ys=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 x.notFound(o,s)},"notFoundHandler"),r=new he({processors:[Ie],handler:t,gateway:e});n.addRoute(Eo,r.execute)},"registerNotMatchedHandler");var id=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Xs=i(n=>{id.forEach(e=>n.delete(e))},"stripCorsHeaders"),Ln=i(async(n,e,t,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await r(n),p=new Headers(d.headers);return Xs(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await r(n);if(!(s instanceof Response))throw new Q(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=sd(o,t.routeData.corsPolicies),u=ad(n,a),c=new Headers(s.headers);return Xs(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(s.body,{status:s.status,statusText:s.statusText,headers:c,webSocket:s.webSocket})},"corsProcessor"),sd=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 f(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),ad=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 L(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},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 f(`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 f(`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 f(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new f(`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 f(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new f(`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 L("Internal error. Policy not found in cache.");return a})}i(tn,"getInboundPolicyInstances");var Oo=new Map;function ud(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 f(`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 f(`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 f(`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 f(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new f(`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 L("Internal error. Policy not found in cache.");return s})}i(ud,"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 g=new f(`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(g),g}});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"),cd=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 g=new f(`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(g),g}}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=ud(e.route,t.routeData.policies);return ta({request:n,context:e,inboundPolicies:o,outboundPolicies:s,gateway:t,next:r})},"policyProcessor");function ea({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>ta({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(ea,"createInternalPolicyProcessor");async function ta({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:s}){let a=So(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await s(u),l=cd(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(ta,"executePolicyProcessor");function na(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||ld,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]=dd(l,o)}s=u+1}return t}i(na,"parse");function ld(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}i(ld,"decode");function dd(n,e){try{return e(n)}catch{return n}}i(dd,"tryDecode");function ra(n,e){try{let t=/v\d+(-\d+)?/g,o=na(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}i(ra,"devPortalBaseURL");var oa="/__zuplo/dev-portal",pd="dev-portal-id",md="dev-portal-host",gd="zp-account",fd="zp-project",hd="dev-portal-build",yd=`
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
- `,ia=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(yd,{headers:{"content-type":"text/html"}});if(!r)return x.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=ra(o,c.headers),g=new URL(`${d.pathname}${d.search}`,p),{headers:h,method:v,body:b}=c;return m.instance.build.ACCOUNT_NAME&&h.set(gd,m.instance.build.ACCOUNT_NAME),m.instance.build.PROJECT_NAME&&h.set(fd,m.instance.build.PROJECT_NAME),h.set(pd,r),h.set(md,d.host),h.set(hd,m.instance.build.BUILD_ID),await F.fetch(g.toString(),{headers:h,method:v,body:b,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"),sa=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(oa.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:`${oa}(.*)`,systemRouteName:"developer-portal-legacy"});n.addRoute(s,o.execute)},"registerDevPortalLegacyRedirectRoute");var ha=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=i(e=>{let t=["error","warn","info","debug"],r=!1,o=i(()=>{},"emptyFunction"),s=i((a,u)=>{this.#i.forEach(c=>{c.log(a,u)})},"pushFunction");t.forEach(a=>{this.#t[a]=r?o:s,a==e&&(r=!0)})},"#setupMethods");#t={};#n;#r;#o;#i;log(e,t,r,o,s,a){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=i(e=>{this.#e.waitUntil(e)},"waitUntil")};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=i((...e)=>{this.#r.log("debug",this.#e,this.#t,this.#n,e,this.#o)},"debug");info=i((...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)},"info");log=i((...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)},"log");warn=i((...e)=>{this.#r.log("warn",this.#e,this.#t,this.#n,e,this.#o)},"warn");error=i((...e)=>{this.#r.log("error",this.#e,this.#t,this.#n,e,this.#o)},"error")};var bd=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(n=>[n.name,n]),wd=new Map(bd);var Rd=[{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"),Pd=i(n=>{n[_o]=!0;let e=n.toJSON();return delete n[_o],e},"toJSON"),Id=i(n=>wd.get(n)??Error,"getErrorConstructor"),aa=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=Id(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 Pd(n);let c=i(l=>aa({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 Rd)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?aa({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 Ed=/file:\/\/\/(.*?)\/dist\//g,Td="at async Event.respondWith";function ua(n){return typeof n!="string"?n:n.split(`
49
+ `,ia=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(yd,{headers:{"content-type":"text/html"}});if(!r)return x.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=ra(o,c.headers),g=new URL(`${d.pathname}${d.search}`,p),{headers:h,method:v,body:b}=c;return m.instance.build.ACCOUNT_NAME&&h.set(gd,m.instance.build.ACCOUNT_NAME),m.instance.build.PROJECT_NAME&&h.set(fd,m.instance.build.PROJECT_NAME),h.set(pd,r),h.set(md,d.host),h.set(hd,m.instance.build.BUILD_ID),await F.fetch(g.toString(),{headers:h,method:v,body:b,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"),sa=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(oa.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:`${oa}(.*)`,systemRouteName:"developer-portal-legacy"});n.addRoute(s,o.execute)},"registerDevPortalLegacyRedirectRoute");var ha=Be(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=i(e=>{let t=["error","warn","info","debug"],r=!1,o=i(()=>{},"emptyFunction"),s=i((a,u)=>{this.#i.forEach(c=>{c.log(a,u)})},"pushFunction");t.forEach(a=>{this.#t[a]=r?o:s,a==e&&(r=!0)})},"#setupMethods");#t={};#n;#r;#o;#i;log(e,t,r,o,s,a){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=i(e=>{this.#e.waitUntil(e)},"waitUntil")};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=i((...e)=>{this.#r.log("debug",this.#e,this.#t,this.#n,e,this.#o)},"debug");info=i((...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)},"info");log=i((...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)},"log");warn=i((...e)=>{this.#r.log("warn",this.#e,this.#t,this.#n,e,this.#o)},"warn");error=i((...e)=>{this.#r.log("error",this.#e,this.#t,this.#n,e,this.#o)},"error")};var bd=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(n=>[n.name,n]),wd=new Map(bd);var Rd=[{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"),Pd=i(n=>{n[_o]=!0;let e=n.toJSON();return delete n[_o],e},"toJSON"),Id=i(n=>wd.get(n)??Error,"getErrorConstructor"),aa=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=Id(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 Pd(n);let c=i(l=>aa({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 Rd)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?aa({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 Ed=/file:\/\/\/(.*?)\/dist\//g,Td="at async Event.respondWith";function ua(n){return typeof n!="string"?n:n.split(`
50
50
  `).filter(e=>!e.trim().startsWith("at async file")).map((e,t)=>{let r=e.replaceAll(Ed,"").replaceAll(Td,"").trim();return t===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
51
51
  `)}i(ua,"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
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 g=i(h=>{if(u.inlineCharacterLimit===void 0)return h;let v=h.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return v.length<=u.inlineCharacterLimit?v:h.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
54
- `).replace(new RegExp(p.pad,"g"),c).replace(new RegExp(p.indent,"g"),c+d)},"expandWhiteSpace");if(r.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||zs(a))return String(a);if(a instanceof Date)return`new Date('${a.toISOString()}')`;if(l>o)return"...";if(Array.isArray(a)){if(a.length===0)return"[]";r.push(a);let h="["+p.newline+a.map((v,b)=>{let I=a.length-1===b?p.newline:","+p.newlineOrSpace,D=s(v,u,c+d,l+1);return u.transform&&(D=u.transform(a,b,D)),p.indent+D+I}).join("")+p.pad+"]";return r.pop(),g(h)}if(lt(a)){let h=Gs(a);if(u.filter&&(h=h.filter(b=>u.filter?.(a,b))),h.length===0)return"{}";r.push(a);let v="{"+p.newline+h.map((b,I)=>{let D=h.length-1===I?p.newline:","+p.newlineOrSpace,A=typeof b=="symbol",$=!A&&/^[a-z$_][$\w]*$/i.test(b),N=A||$?b:s(b,u,"",l+1),j=s(a[b],u,c+d,l+1);return u.transform&&(j=u.transform(a,b,j)),p.indent+String(N)+": "+j+D}).join("")+p.pad+"}";return r.pop(),g(v)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,h=>h===`
55
- `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}i(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 ca(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(ca,"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 f("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 la(n,e,t){if(!n.startsWith("projects/"))throw new f(`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(la,"exchangeIDTokenForGcpWorkloadToken");async function da({serviceAccountEmailOrIdentifier:n,audience:e,accessToken:t},r){let o={audience:e,includeEmail:!0};return ma(`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(da,"generateServiceAccountIDToken");async function pa(n,e,t){return ko(n,{token:e,returnSecureToken:!0},t)}i(pa,"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 ma(n,r,t)}i(ko,"fetchTokenFromBody");async function ma(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 L({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(ma,"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 ga({loggingUrl:m.instance.remoteLogURL,loggingId:m.instance.loggingId,loggingToken:m.instance.remoteLogToken},[e])}catch(e){console.error(e)}}i(me,"sendRemoteGlobalLog");async function ga({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(ga,"sendRemoteLogs");var xd=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 ga({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,xd(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)}},Od="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,y("logging.google-cloud")}#e;#t;#n;#r;#o;#i;async init(){this.#t=await ve.init(this.#e)}log(e,t){if(!this.#t)throw new 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=i(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(Od,{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."]})}},"dispatchFunction");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"),vd=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){y("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(h=>h[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(h=>h[Mo]!==void 0);l>-1&&(Object.assign(u,s[l][Mo]),s.splice(l,1));let d=et(s),g={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:vd(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(g,u),this.batcher.enqueue(g),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(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."]})}},"dispatchFunction");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 Cd={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},fa=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:Cd[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var Sd=i(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let s=fa(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,Sd(e)))}async log(e,t){zn.enqueue(e),t.waitUntil(zn.waitUntilFlushed())}};var qo=(0,ha.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&&(y("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){y("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 f(`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 ya(n){Fo=n}i(ya,"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 ba({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);_s.includes(o.toLowerCase())&&!Ls.includes(r.toLowerCase())&&t.delete(r)}t.delete(bs)}else As.forEach(r=>{t.delete(r)});return t}i(ba,"normalizeIncomingRequestHeaders");var qe=(0,Ra.debug)("zuplo:runtime"),Ad=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:Js(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=i(()=>{qe("Gateway.setupRoutes");let e=this.routeData,t=Ad(e.versions),r=new Ot(t);if(e.routes.length===0)return yo(r,this),To(r,this),Io(r,this),Qs(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(sa(r,this),ia(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 f(`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)}),Ys(r,this),r},"setupRoutes");setupErrorHandler=i(()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new f("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},"setupErrorHandler");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 L&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let s=Te(r.cause);"stack"in s&&(s.stack=ua(s.stack)),o={cause:s}}}return x.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t,r){let{requestId:o,rayId:s}=t;ya(r);let a=ba({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 $=new Headers(u.headers);$.set(Yr,"true"),u=new Request(u,{headers:$,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(o,s,r,c,u),p=new URL(u.url),g=p.pathname,h=this.#n.lookup(u.method,g);if(!h)throw new Q(`Invalid state - no route match - should have been picked up by the not found handler, path: '${g}'`);let v=new Kn(e.headers),b=new oe(u,{params:h.params}),I=new Jn({logger:l,route:h.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:v}),D=h.routeConfiguration.raw();wa.trace.getActiveSpan()?.setAttributes({"http.route":I.route.path??I.route.pathPattern,"cloud.region":I.incomingRequestProperties.colo,[Le.RoutePathPattern]:I.route.pathPattern,[Le.RouteOperationId]:D.operationId,[Le.RouteTrace]:D["x-zuplo-trace"],[Le.RouteSystem]:wt(p)?!0:void 0});let A=Pe.initialize(I,b);if(h.routeConfiguration===Eo&&Qt.value?.notFoundHandler!==void 0){let $=this.#n.lookupByPathOnly(g);A.pathOnlyMatches=$.map(N=>N.routeConfiguration).filter(N=>N instanceof mt)}try{if(te.addLogger(I,d),m.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!wt(p):!p.pathname.startsWith("/__zuplo")){let T=await Hs(b,I);if(T instanceof Response)return T;{let Z=Pe.getContextExtensions(I);b=T,Z.latestRequest=b}}wt(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:h.routeConfiguration.path});let $=h.executableHandler;_d($,h,u),qe("Gateway.handleRequest - call user handler");let N=await $(b,I);if(qe("Gateway.handleRequest - user handler"),!(N instanceof Response))throw new L(`Invalid Response type from the request handler: ${typeof N}`);if(N.bodyUsed)throw new L("The response object has already been used. Return a new response instead.");let j;if(N.headers.get(ut)===null&&!N.webSocket){let T=new Headers(N.headers);T.set(ut,o),j=new Response(N.body,{status:N.status,statusText:N.statusText,headers:T,cf:N.cf})}else j=N;return j}catch($){return qe("Gateway - error executing handler",$),$ instanceof L?(l.error($),d.warn($)):d.error($),await this.#i(b,I,$)}}};function _d(n,e,t){if(qe("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new f(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new f(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}i(_d,"checkHandler");var Pa=i(async(n,e,t)=>{let r=Re.instance.routeData.policies,o=tn([n],r);if(o.length===0)throw new L(`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(Ts)??void 0}get continent(){return this.#e.get(eo)??this.#e.get(xs)??void 0}get country(){return this.#e.get(to)??this.#e.get(Os)??void 0}get latitude(){return this.#e.get(ro)??this.#e.get(Cs)??void 0}get longitude(){return this.#e.get(no)??this.#e.get(vs)??void 0}get colo(){return this.#e.get(so)??void 0}get postalCode(){return this.#e.get(Is)??this.#e.get(ao)??void 0}get metroCode(){return this.#e.get(Ps)??this.#e.get(uo)??void 0}get region(){return this.#e.get(ws)??this.#e.get(co)??void 0}get regionCode(){return this.#e.get(Rs)??this.#e.get(lo)??void 0}get timezone(){return this.#e.get(Es)??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 L(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=i(async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)},"onResponseSendingFinal");onResponseSending=i(async(e,t,r)=>{let o=e;for(let s of this.#n)o=await s(e,t,r);return o},"onResponseSending")},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)=>Pa(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 Ld=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function kd(n){return n.startsWith("__ZUPLO")||n.startsWith("ZUPLO_")?!Ld.includes(n)&&!n.startsWith("ZUPLO_PUBLIC_"):!1}i(kd,"isRestrictedEnvVariableName");function Nd(n){return!!n.startsWith("ZUPLO_")}i(Nd,"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(!(kd(t)&&!Nd(t)))return m.instance.runtime[t]}});var Ia=require("node:async_hooks");var Ea={request:new Ia.AsyncLocalStorage};var Dd="Error initializing gateway. Check your configuration for errors or contact support.",Md="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=i(async(e,t,r)=>{let o=e.headers.get(ut)??e.headers.get(ys)??crypto.randomUUID(),s=e.headers.get(ct),a={requestId:o,rayId:s};return Ea.request.run(a,async()=>{m.initialize({build:this.buildEnvironment,runtime:t});try{await js(this.runtimeInit)}catch(c){this.handleError(c,Md,e)}return Ds(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,Dd,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,r)})},"requestHandler");handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof f&&(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 La=ze(He());function Ud(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(Ud,"lexer");function $o(n,e){e===void 0&&(e={});for(var t=Ud(n),r=e.prefixes,o=r===void 0?"./":r,s="[^".concat(Zd(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=i(function(T){if(c<t.length&&t[c].type===T)return t[c++].value},"tryConsume"),p=i(function(T){var Z=d(T);if(Z!==void 0)return Z;var V=t[c],W=V.type,S=V.index;throw new TypeError("Unexpected ".concat(W," at ").concat(S,", expected ").concat(T))},"mustConsume"),g=i(function(){for(var T="",Z;Z=d("CHAR")||d("ESCAPED_CHAR");)T+=Z;return T},"consumeText");c<t.length;){var h=d("CHAR"),v=d("NAME"),b=d("PATTERN");if(v||b){var I=h||"";o.indexOf(I)===-1&&(l+=I,I=""),l&&(a.push(l),l=""),a.push({name:v||u++,prefix:I,suffix:"",pattern:b||s,modifier:d("MODIFIER")||""});continue}var D=h||d("ESCAPED_CHAR");if(D){l+=D;continue}l&&(a.push(l),l="");var A=d("OPEN");if(A){var I=g(),$=d("NAME")||"",N=d("PATTERN")||"",j=g();p("CLOSE"),a.push({name:$||(N?u++:""),pattern:$&&!N?s:N,prefix:I,suffix:j,modifier:d("MODIFIER")||""});continue}p("END")}return a}i($o,"parse");function Ta(n,e){return qd($o(n,e),e)}i(Ta,"compile");function qd(n,e){e===void 0&&(e={});var t=Hd(e),r=e.encode,o=r===void 0?function(c){return c}:r,s=e.validate,a=s===void 0?!0:s,u=n.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var g=c?c[p.name]:void 0,h=p.modifier==="?"||p.modifier==="*",v=p.modifier==="*"||p.modifier==="+";if(Array.isArray(g)){if(!v)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(g.length===0){if(h)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var b=0;b<g.length;b++){var I=o(g[b],p);if(a&&!u[d].test(I))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(I,'"'));l+=p.prefix+I+p.suffix}continue}if(typeof g=="string"||typeof g=="number"){var I=o(String(g),p);if(a&&!u[d].test(I))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(I,'"'));l+=p.prefix+I+p.suffix;continue}if(!h){var D=v?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(D))}}return l}}i(qd,"tokensToFunction");function Zd(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(Zd,"escapeString");function Hd(n){return n&&n.sensitive?"":"i"}i(Hd,"flags");var Ca=ze(He());var Fd=(0,Ca.debug)("zuplo:runtime"),Bo=new TextEncoder,xa={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"},$d=["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){Fd("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,t),a=F.fetch(o,s);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new f("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:g,appendSessionToken:h,allHeaders:v,singleEncode:b}){if(t==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let I,D;(!c||!l)&&([I,D]=jd(this.url,this.headers)),this.service=c||I||"",this.region=l||D||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=g,this.appendSessionToken=h||this.service==="iotdevicegateway",this.headers.delete("Host");let A=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"),A.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&A.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(N=>v||!$d.includes(N)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(N=>N+":"+(N==="host"?this.url.host:(this.headers.get(N)||"").replace(/\s+/g," "))).join(`
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"||Bs(a))return String(a);if(a instanceof Date)return`new Date('${a.toISOString()}')`;if(l>o)return"...";if(Array.isArray(a)){if(a.length===0)return"[]";r.push(a);let h="["+p.newline+a.map((v,b)=>{let I=a.length-1===b?p.newline:","+p.newlineOrSpace,D=s(v,u,c+d,l+1);return u.transform&&(D=u.transform(a,b,D)),p.indent+D+I}).join("")+p.pad+"]";return r.pop(),g(h)}if(lt(a)){let h=Gs(a);if(u.filter&&(h=h.filter(b=>u.filter?.(a,b))),h.length===0)return"{}";r.push(a);let v="{"+p.newline+h.map((b,I)=>{let D=h.length-1===I?p.newline:","+p.newlineOrSpace,A=typeof b=="symbol",$=!A&&/^[a-z$_][$\w]*$/i.test(b),N=A||$?b:s(b,u,"",l+1),j=s(a[b],u,c+d,l+1);return u.transform&&(j=u.transform(a,b,j)),p.indent+String(N)+": "+j+D}).join("")+p.pad+"}";return r.pop(),g(v)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,h=>h===`
55
+ `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}i(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:ze(Te(e))}i(Tt,"extractBestMessage");function ca(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(ca,"messagesToMultilineText");function ze(n){return typeof n=="string"?n:JSON.stringify(n)}i(ze,"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 f("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 la(n,e,t){if(!n.startsWith("projects/"))throw new f(`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(la,"exchangeIDTokenForGcpWorkloadToken");async function da({serviceAccountEmailOrIdentifier:n,audience:e,accessToken:t},r){let o={audience:e,includeEmail:!0};return ma(`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(da,"generateServiceAccountIDToken");async function pa(n,e,t){return ko(n,{token:e,returnSecureToken:!0},t)}i(pa,"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 ma(n,r,t)}i(ko,"fetchTokenFromBody");async function ma(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 L({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(ma,"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 ga({loggingUrl:m.instance.remoteLogURL,loggingId:m.instance.loggingId,loggingToken:m.instance.remoteLogToken},[e])}catch(e){console.error(e)}}i(me,"sendRemoteGlobalLog");async function ga({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(ga,"sendRemoteLogs");var xd=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 ga({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,xd(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)}},Od="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,y("logging.google-cloud")}#e;#t;#n;#r;#o;#i;async init(){this.#t=await ve.init(this.#e)}log(e,t){if(!this.#t)throw new 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=i(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(Od,{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."]})}},"dispatchFunction");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 zn=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"),vd=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){y("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(h=>h[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(h=>h[Mo]!==void 0);l>-1&&(Object.assign(u,s[l][Mo]),s.splice(l,1));let d=et(s),g={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:vd(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(g,u),this.batcher.enqueue(g),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(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."]})}},"dispatchFunction");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 Cd={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},fa=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:Cd[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var Sd=i(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let s=fa(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"),Bn,Gn=class{static{i(this,"UnifiedLogTransport")}constructor(e){Bn||(Bn=new ee("unified-log-transport",1,Sd(e)))}async log(e,t){Bn.enqueue(e),t.waitUntil(Bn.waitUntilFlushed())}};var qo=(0,ha.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&&(y("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){y("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 f(`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 ya(n){Fo=n}i(ya,"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 ba({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);_s.includes(o.toLowerCase())&&!Ls.includes(r.toLowerCase())&&t.delete(r)}t.delete(bs)}else As.forEach(r=>{t.delete(r)});return t}i(ba,"normalizeIncomingRequestHeaders");var qe=(0,Ra.debug)("zuplo:runtime"),Ad=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:Js(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=i(()=>{qe("Gateway.setupRoutes");let e=this.routeData,t=Ad(e.versions),r=new Ot(t);if(e.routes.length===0)return yo(r,this),To(r,this),Io(r,this),Qs(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(sa(r,this),ia(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 f(`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)}),Ys(r,this),r},"setupRoutes");setupErrorHandler=i(()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new f("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},"setupErrorHandler");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 L&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let s=Te(r.cause);"stack"in s&&(s.stack=ua(s.stack)),o={cause:s}}}return x.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t,r){let{requestId:o,rayId:s}=t;ya(r);let a=ba({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 $=new Headers(u.headers);$.set(Yr,"true"),u=new Request(u,{headers:$,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(o,s,r,c,u),p=new URL(u.url),g=p.pathname,h=this.#n.lookup(u.method,g);if(!h)throw new Q(`Invalid state - no route match - should have been picked up by the not found handler, path: '${g}'`);let v=new Kn(e.headers),b=new oe(u,{params:h.params}),I=new Jn({logger:l,route:h.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:v}),D=h.routeConfiguration.raw();wa.trace.getActiveSpan()?.setAttributes({"http.route":I.route.path??I.route.pathPattern,"cloud.region":I.incomingRequestProperties.colo,[Le.RoutePathPattern]:I.route.pathPattern,[Le.RouteOperationId]:D.operationId,[Le.RouteTrace]:D["x-zuplo-trace"],[Le.RouteSystem]:wt(p)?!0:void 0});let A=Pe.initialize(I,b);if(h.routeConfiguration===Eo&&Qt.value?.notFoundHandler!==void 0){let $=this.#n.lookupByPathOnly(g);A.pathOnlyMatches=$.map(N=>N.routeConfiguration).filter(N=>N instanceof mt)}try{if(te.addLogger(I,d),m.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!wt(p):!p.pathname.startsWith("/__zuplo")){let T=await Hs(b,I);if(T instanceof Response)return T;{let Z=Pe.getContextExtensions(I);b=T,Z.latestRequest=b}}wt(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:h.routeConfiguration.path});let $=h.executableHandler;_d($,h,u),qe("Gateway.handleRequest - call user handler");let N=await $(b,I);if(qe("Gateway.handleRequest - user handler"),!(N instanceof Response))throw new L(`Invalid Response type from the request handler: ${typeof N}`);if(N.bodyUsed)throw new L("The response object has already been used. Return a new response instead.");let j;if(N.headers.get(ut)===null&&!N.webSocket){let T=new Headers(N.headers);T.set(ut,o),j=new Response(N.body,{status:N.status,statusText:N.statusText,headers:T,cf:N.cf})}else j=N;return j}catch($){return qe("Gateway - error executing handler",$),$ instanceof L?(l.error($),d.warn($)):d.error($),await this.#i(b,I,$)}}};function _d(n,e,t){if(qe("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new f(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new f(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}i(_d,"checkHandler");var Pa=i(async(n,e,t)=>{let r=Re.instance.routeData.policies,o=tn([n],r);if(o.length===0)throw new L(`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(Ts)??void 0}get continent(){return this.#e.get(eo)??this.#e.get(xs)??void 0}get country(){return this.#e.get(to)??this.#e.get(Os)??void 0}get latitude(){return this.#e.get(ro)??this.#e.get(Cs)??void 0}get longitude(){return this.#e.get(no)??this.#e.get(vs)??void 0}get colo(){return this.#e.get(so)??void 0}get postalCode(){return this.#e.get(Is)??this.#e.get(ao)??void 0}get metroCode(){return this.#e.get(Ps)??this.#e.get(uo)??void 0}get region(){return this.#e.get(ws)??this.#e.get(co)??void 0}get regionCode(){return this.#e.get(Rs)??this.#e.get(lo)??void 0}get timezone(){return this.#e.get(Es)??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 L(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=i(async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)},"onResponseSendingFinal");onResponseSending=i(async(e,t,r)=>{let o=e;for(let s of this.#n)o=await s(e,t,r);return o},"onResponseSending")},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)=>Pa(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 Ld=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function kd(n){return n.startsWith("__ZUPLO")||n.startsWith("ZUPLO_")?!Ld.includes(n)&&!n.startsWith("ZUPLO_PUBLIC_"):!1}i(kd,"isRestrictedEnvVariableName");function Nd(n){return!!n.startsWith("ZUPLO_")}i(Nd,"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(!(kd(t)&&!Nd(t)))return m.instance.runtime[t]}});var Ia=require("node:async_hooks");var Ea={request:new Ia.AsyncLocalStorage};var Dd="Error initializing gateway. Check your configuration for errors or contact support.",Md="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=i(async(e,t,r)=>{let o=e.headers.get(ut)??e.headers.get(ys)??crypto.randomUUID(),s=e.headers.get(ct),a={requestId:o,rayId:s};return Ea.request.run(a,async()=>{m.initialize({build:this.buildEnvironment,runtime:t});try{await js(this.runtimeInit)}catch(c){this.handleError(c,Md,e)}return Ds(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,Dd,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,r)})},"requestHandler");handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof f&&(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 La=Be(He());function Ud(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(Ud,"lexer");function $o(n,e){e===void 0&&(e={});for(var t=Ud(n),r=e.prefixes,o=r===void 0?"./":r,s="[^".concat(Zd(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=i(function(T){if(c<t.length&&t[c].type===T)return t[c++].value},"tryConsume"),p=i(function(T){var Z=d(T);if(Z!==void 0)return Z;var V=t[c],W=V.type,S=V.index;throw new TypeError("Unexpected ".concat(W," at ").concat(S,", expected ").concat(T))},"mustConsume"),g=i(function(){for(var T="",Z;Z=d("CHAR")||d("ESCAPED_CHAR");)T+=Z;return T},"consumeText");c<t.length;){var h=d("CHAR"),v=d("NAME"),b=d("PATTERN");if(v||b){var I=h||"";o.indexOf(I)===-1&&(l+=I,I=""),l&&(a.push(l),l=""),a.push({name:v||u++,prefix:I,suffix:"",pattern:b||s,modifier:d("MODIFIER")||""});continue}var D=h||d("ESCAPED_CHAR");if(D){l+=D;continue}l&&(a.push(l),l="");var A=d("OPEN");if(A){var I=g(),$=d("NAME")||"",N=d("PATTERN")||"",j=g();p("CLOSE"),a.push({name:$||(N?u++:""),pattern:$&&!N?s:N,prefix:I,suffix:j,modifier:d("MODIFIER")||""});continue}p("END")}return a}i($o,"parse");function Ta(n,e){return qd($o(n,e),e)}i(Ta,"compile");function qd(n,e){e===void 0&&(e={});var t=Hd(e),r=e.encode,o=r===void 0?function(c){return c}:r,s=e.validate,a=s===void 0?!0:s,u=n.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var g=c?c[p.name]:void 0,h=p.modifier==="?"||p.modifier==="*",v=p.modifier==="*"||p.modifier==="+";if(Array.isArray(g)){if(!v)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(g.length===0){if(h)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var b=0;b<g.length;b++){var I=o(g[b],p);if(a&&!u[d].test(I))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(I,'"'));l+=p.prefix+I+p.suffix}continue}if(typeof g=="string"||typeof g=="number"){var I=o(String(g),p);if(a&&!u[d].test(I))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(I,'"'));l+=p.prefix+I+p.suffix;continue}if(!h){var D=v?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(D))}}return l}}i(qd,"tokensToFunction");function Zd(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(Zd,"escapeString");function Hd(n){return n&&n.sensitive?"":"i"}i(Hd,"flags");var Ca=Be(He());var Fd=(0,Ca.debug)("zuplo:runtime"),zo=new TextEncoder,xa={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"},$d=["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 Bo(Object.assign({url:e},t,this,t&&t.aws)),o=Object.assign({},t,await r.sign());return delete o.aws,{url:o.url.toString(),request:o}}async fetch(e,t){Fd("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,t),a=F.fetch(o,s);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new f("An unknown error occurred, ensure retries is not negative")}},Bo=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:g,appendSessionToken:h,allHeaders:v,singleEncode:b}){if(t==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let I,D;(!c||!l)&&([I,D]=jd(this.url,this.headers)),this.service=c||I||"",this.region=l||D||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=g,this.appendSessionToken=h||this.service==="iotdevicegateway",this.headers.delete("Host");let A=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"),A.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&A.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(N=>v||!$d.includes(N)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(N=>N+":"+(N==="host"?this.url.host:(this.headers.get(N)||"").replace(/\s+/g," "))).join(`
57
57
  `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!A.has("X-Amz-Expires")&&A.set("X-Amz-Expires","86400"),A.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),A.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),A.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");b||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=va(this.encodedPath);let $=new Set;this.encodedSearch=[...this.url.searchParams].filter(([N])=>{if(!N)return!1;if(this.service==="s3"){if($.has(N))return!1;$.add(N)}return!0}).map(N=>N.map(j=>va(encodeURIComponent(j)))).sort(([N,j],[T,Z])=>N<T?-1:N>T?1:j<Z?-1:j>Z?1:0).map(N=>N.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 Oa(await this.canonicalString()))].join(`
58
58
  `)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
59
59
  `,this.signedHeaders,await this.hexBodyHash()].join(`
60
- `)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new L("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=jo(await Oa(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 Oa(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?Bo.encode(n):n)}i(Oa,"hash");function jo(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}i(jo,"buf2hex");function va(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(va,"encodeRfc3986");function jd(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 xa?[xa[s],a]:[s,a]}i(jd,"guessServiceRegion");function Bd(n){return n>64&&n<91?n-65:n>96&&n<123?n-71:n>47&&n<58?n+4:n===43?62:n===47?63:0}i(Bd,"b64ToUint6");function Sa(n,e){let t=n.replace(/[^A-Za-z0-9+/]/g,""),r=t.length,o=e?Math.ceil((r*3+1>>2)/e)*e:r*3+1>>2,s=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=Bd(t.charCodeAt(d))<<6*(3-u),u===3||r-d===1){for(a=0;a<3&&l<o;)s[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return s}i(Sa,"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 Aa(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(Aa,"base64Encode");function Ct(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}i(Ct,"numberToString");function zd(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(zd,"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=zd(n);return`${t}/${r}/${o}:${s}:${a}:${u} ${c}`}i(Go,"toCLFDate");var _a=(0,La.debug)("zuplo:runtime"),Gd="X-Amzn-Trace-Id",Vd="x-amzn-errortype",ka=[],Wd=i(async(n,e,t)=>{let r=t;for await(let o of ka)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),Ce=class extends L{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(Gd)??void 0,this.errorType=t.get(Vd)??void 0}},Na={addSendingAwsLambdaEventHook:i(n=>{ka.push(n)},"addSendingAwsLambdaEventHook")};async function Da(n,e){y("handler.aws-lambda");let{accessKeyId:t,secretAccessKey:r,region:o,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!t)throw new f("awsAccessKeyId is not set in the handler options");if(!r)throw new f("secretAccessKey is not set in the handler options");if(!o)throw new f("region is not set in the handler options");if(!s)throw new f("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(_a(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,g]=await Yd(n,{binaryMediaTypes:c}),{options:h}=e.route.handler,v;h&&typeof h=="object"&&"payloadFormatVersion"in h&&h.payloadFormatVersion==="2.0"?v=Qd(n,e):v=await Jd(n,e,{useAwsResourcePathStyle:u}),_a("Calling onSendingAwsLambdaEvent hook");let b=await Wd(n,e,v);b.body=p,b.isBase64Encoded=g;let I=await l.fetch(d,{body:JSON.stringify(b)});try{return Kd(I)}catch(D){if(D instanceof Ce){let A=h&&typeof h=="object"&&"returnAmazonTraceIdHeader"in h&&h.returnAmazonTraceIdHeader&&D.traceId?{AMZN_TRACE_ID_HEADER:D.traceId}:void 0;return x.internalServerError(n,e,void 0,A)}throw D}}i(Da,"awsLambdaHandler");async function Kd(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=Sa(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(Kd,"getResponse");async function Jd(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:ep(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}i(Jd,"buildEventVersion1");function Qd(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(Qd,"buildEventVersion2");async function Yd(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&&Xd(e,o)){let s=await n.arrayBuffer();t=Aa(new Uint8Array(s)),r=!0}else t=await n.clone().text();return[t,r]}i(Yd,"getBodyResult");function Xd(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}i(Xd,"matchesContentType");function ep(n,e=!1){if(!e)return n;let t=$o(n),r=Ta(n),o={};return t.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),r(o)}i(ep,"getResourcePath");var tp=[502,503,504];async function St(n,e){if(tp.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 Ma(n,e){y("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 f("Open API Spec Handler must have 'openApiFilePath' specified");let a=np(s);if(!a.isValid)throw new f(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 x.notFound(n,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return St(l,e),l}i(Ma,"openApiSpecHandler");var np=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 Ua(n,e){y("handler.redirect");let t=e.route.handler.options;if(!t.location)throw new f("Redirect Handler must have 'location' specified");let r=t.status??302;return new Response(null,{status:r,headers:{location:t.location}})}i(Ua,"redirectHandler");function rp(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(rp,"join");async function qa(n,e){y("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 f("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=rp(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}),g=Date.now()-d;return t(`URL Forward received response ${p.status} - ${p.statusText} in ${g}ms`),St(p,e),p}i(qa,"urlForwardHandler");var op=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 Za(n,e){y("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 f("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?op(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(Za,"urlRewriteHandler");async function Ha(n,e){y("handler.websocket");let t=e.route.handler.options,r=tt(e);if(!t||!t.rewritePattern)throw new f("WebSocket Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return x.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new f("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 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 f(`${a} - Websocket policy must be a valid function (${u})`)}return s}),"getWebSocketPolicyFunctions"),Fa=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 $a(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 Fa(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($a,"wireUpListeners");async function ja(n,e){y("handler.websocket-pipeline");let t=e.route.handler.options,r=tt(e);if(!t||!t.rewritePattern)throw new f("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return x.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new f("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 I=await c.text(),D=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${I}'`;throw new Error(D)}let l=new WebSocketPair,[d,p]=Object.values(l),g=Date.now()-u;r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${g}ms`);let h=c.webSocket;h.accept(),p.accept();let v=t.policies&&t.policies.inbound?Wo(t.policies.inbound,"inbound"):[],b=t.policies&&t.policies.outbound?Wo(t.policies.outbound,"outbound"):[];return $a(p,h,n,e,v),$a(h,p,n,e,b),new Response(null,{status:101,webSocket:d})}i(ja,"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){y("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=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."]})}},"#dispatchFunction");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=i(e=>this.level===e.level&&this.requestId===e.requestId,"equals")};function ip(n,e){return btoa(`${n}:${e}`)}i(ip,"createBasicDigest");var Qo=class{static{i(this,"LokiTransport")}constructor(e){y("logging.loki"),this.#n=e.url,this.#r=ip(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=i(e=>{let t={streams:[]};return e.forEach(r=>{let o=t.streams.find(s=>s.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},t.streams.push(o)),o.values.push(this.#e>1?[r.nanoSecondEpoch,r.message,{requestId:r.requestId,rayId:r.rayId,atomicCounter:JSON.stringify(r.atomicCounter)}]:[r.nanoSecondEpoch,r.message])}),t},"#convertToLokiStreamsBatch");#u=i(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."]})}},"#dispatchFunction");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){y("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=i(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."]})}},"#dispatchFunction");batcher=new ee("sumo-logic-log-transport",10,this.#s)};var sp="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){y("logging.vmware-loginsight");let t;try{t=new URL(e.url),t.pathname==="/"&&(t.pathname=`/api/v1/events/ingest/${e.agentId??sp}`)}catch{throw new f(`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=ca(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=i(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."]})}},"#dispatchFunction");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}){y("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,ap={tags:[]},or=class extends Ye{constructor(t){super();this.options=t;y("metrics.datadog")}static{i(this,"DataDogMetricsPlugin")}getTransport(){return new ni(this.options)}static setContext(t,r){let o=ti.get(t);o||(o=ap);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=i(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())},"dispatchFunction")},ri=class n extends Error{static{i(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var oi=new WeakMap,up={dimensions:[]},ir=class extends Ye{constructor(t){super();this.options=t;y("metrics.dynatrace")}static{i(this,"DynatraceMetricsPlugin")}getTransport(){return new ii(this.options)}static setContext(t,r){let o=oi.get(t);o||(o=up);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=i(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())},"dispatchFunction")},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,y("audit-logs.datastax")}#e;writeLogBatch=i(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)})}))},"writeLogBatch")};var ar=class extends Fe{static{i(this,"AuditLogPlugin")}constructor(e,t){super(),this.#e=e,this.#t=t,y("audit-logs")}#e;#t;async initialize(e){new ai(e,this.#e,this.#t)}},Ba=i(n=>{let e={};return n.forEach((t,r)=>{e[r]=t}),e},"serializableHeaders"),cp={requestFilter:i(async()=>!0,"requestFilter"),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={...cp};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=i(async e=>{await this.#t.writeLogBatch(e)},"#dispatch");#o=i(async(e,t,r,o,s,a)=>{try{let u={timestamp:o,durationMs:s,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:t.url,method:t.method,headers:this.#e.include?.request?.headers?Ba(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?Ba(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(u),r.waitUntil(this.#n.waitUntilFlushed())}catch(u){r.log.error(u)}},"#asyncPrepLogs");#i=i(async(e,t)=>{try{if(!await this.#e.requestFilter(e,t))return e;let o=new Date,s=Date.now(),a=e.clone();return t.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#o(d,a,t,o,l-s,c.user?.sub).catch(g=>{t.log.error(g)});t.waitUntil(p)}),e}catch(r){return t.log.error(r),e}},"#auditHook")};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 lp="v1",dp=300;async function za(n,e,t,r=dp,o){return await mp(n,e,t,r,o),n instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(n)):JSON.parse(n)}i(za,"constructEventAsync");function pp(n,e){return`${e.timestamp}.${n}`}i(pp,"makeHMACContent");async function mp(n,e,t,r,o){let{decodedHeader:s,decodedPayload:a,details:u,suspectPayloadType:c}=gp(n,e,lp),l=/\s/.test(t),d=await bp(pp(a,u),t);return fp(a,s,u,d,r,c,l,o)}i(mp,"verifyHeaderAsync");function gp(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=hp(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(gp,"parseEventDetails");function fp(n,e,t,r,o,s,a,u){let c=!!t.signatures.filter(g=>yp(g,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 L("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=jo(await Oa(this.body||""))}return e}};async function cn(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?zo.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,zo.encode(e))}i(cn,"hmac");async function Oa(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?zo.encode(n):n)}i(Oa,"hash");function jo(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}i(jo,"buf2hex");function va(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(va,"encodeRfc3986");function jd(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 xa?[xa[s],a]:[s,a]}i(jd,"guessServiceRegion");function zd(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(zd,"b64ToUint6");function Sa(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|=zd(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(Sa,"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 Aa(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(Aa,"base64Encode");function Ct(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}i(Ct,"numberToString");function Bd(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(Bd,"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=Bd(n);return`${t}/${r}/${o}:${s}:${a}:${u} ${c}`}i(Go,"toCLFDate");var _a=(0,La.debug)("zuplo:runtime"),Gd="X-Amzn-Trace-Id",Vd="x-amzn-errortype",ka=[],Wd=i(async(n,e,t)=>{let r=t;for await(let o of ka)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),Ce=class extends L{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(Gd)??void 0,this.errorType=t.get(Vd)??void 0}},Na={addSendingAwsLambdaEventHook:i(n=>{ka.push(n)},"addSendingAwsLambdaEventHook")};async function Da(n,e){y("handler.aws-lambda");let{accessKeyId:t,secretAccessKey:r,region:o,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!t)throw new f("awsAccessKeyId is not set in the handler options");if(!r)throw new f("secretAccessKey is not set in the handler options");if(!o)throw new f("region is not set in the handler options");if(!s)throw new f("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(_a(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,g]=await Yd(n,{binaryMediaTypes:c}),{options:h}=e.route.handler,v;h&&typeof h=="object"&&"payloadFormatVersion"in h&&h.payloadFormatVersion==="2.0"?v=Qd(n,e):v=await Jd(n,e,{useAwsResourcePathStyle:u}),_a("Calling onSendingAwsLambdaEvent hook");let b=await Wd(n,e,v);b.body=p,b.isBase64Encoded=g;let I=await l.fetch(d,{body:JSON.stringify(b)});try{return Kd(I)}catch(D){if(D instanceof Ce){let A=h&&typeof h=="object"&&"returnAmazonTraceIdHeader"in h&&h.returnAmazonTraceIdHeader&&D.traceId?{AMZN_TRACE_ID_HEADER:D.traceId}:void 0;return x.internalServerError(n,e,void 0,A)}throw D}}i(Da,"awsLambdaHandler");async function Kd(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=Sa(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(Kd,"getResponse");async function Jd(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:ep(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}i(Jd,"buildEventVersion1");function Qd(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(Qd,"buildEventVersion2");async function Yd(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&&Xd(e,o)){let s=await n.arrayBuffer();t=Aa(new Uint8Array(s)),r=!0}else t=await n.clone().text();return[t,r]}i(Yd,"getBodyResult");function Xd(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}i(Xd,"matchesContentType");function ep(n,e=!1){if(!e)return n;let t=$o(n),r=Ta(n),o={};return t.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),r(o)}i(ep,"getResourcePath");var tp=[502,503,504];async function St(n,e){if(tp.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 Ma(n,e){y("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 f("Open API Spec Handler must have 'openApiFilePath' specified");let a=np(s);if(!a.isValid)throw new f(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 x.notFound(n,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return St(l,e),l}i(Ma,"openApiSpecHandler");var np=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 Ua(n,e){y("handler.redirect");let t=e.route.handler.options;if(!t.location)throw new f("Redirect Handler must have 'location' specified");let r=t.status??302;return new Response(null,{status:r,headers:{location:t.location}})}i(Ua,"redirectHandler");function rp(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(rp,"join");async function qa(n,e){y("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 f("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=rp(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}),g=Date.now()-d;return t(`URL Forward received response ${p.status} - ${p.statusText} in ${g}ms`),St(p,e),p}i(qa,"urlForwardHandler");var op=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 Za(n,e){y("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 f("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?op(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(Za,"urlRewriteHandler");async function Ha(n,e){y("handler.websocket");let t=e.route.handler.options,r=tt(e);if(!t||!t.rewritePattern)throw new f("WebSocket Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return x.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new f("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 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 f(`${a} - Websocket policy must be a valid function (${u})`)}return s}),"getWebSocketPolicyFunctions"),Fa=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 $a(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 Fa(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($a,"wireUpListeners");async function ja(n,e){y("handler.websocket-pipeline");let t=e.route.handler.options,r=tt(e);if(!t||!t.rewritePattern)throw new f("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return x.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new f("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 I=await c.text(),D=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${I}'`;throw new Error(D)}let l=new WebSocketPair,[d,p]=Object.values(l),g=Date.now()-u;r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${g}ms`);let h=c.webSocket;h.accept(),p.accept();let v=t.policies&&t.policies.inbound?Wo(t.policies.inbound,"inbound"):[],b=t.policies&&t.policies.outbound?Wo(t.policies.outbound,"outbound"):[];return $a(p,h,n,e,v),$a(h,p,n,e,b),new Response(null,{status:101,webSocket:d})}i(ja,"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){y("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=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."]})}},"#dispatchFunction");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=i(e=>this.level===e.level&&this.requestId===e.requestId,"equals")};function ip(n,e){return btoa(`${n}:${e}`)}i(ip,"createBasicDigest");var Qo=class{static{i(this,"LokiTransport")}constructor(e){y("logging.loki"),this.#n=e.url,this.#r=ip(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:ze(Te(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(s)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=i(e=>{let t={streams:[]};return e.forEach(r=>{let o=t.streams.find(s=>s.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},t.streams.push(o)),o.values.push(this.#e>1?[r.nanoSecondEpoch,r.message,{requestId:r.requestId,rayId:r.rayId,atomicCounter:JSON.stringify(r.atomicCounter)}]:[r.nanoSecondEpoch,r.message])}),t},"#convertToLokiStreamsBatch");#u=i(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."]})}},"#dispatchFunction");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){y("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=i(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."]})}},"#dispatchFunction");batcher=new ee("sumo-logic-log-transport",10,this.#s)};var sp="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){y("logging.vmware-loginsight");let t;try{t=new URL(e.url),t.pathname==="/"&&(t.pathname=`/api/v1/events/ingest/${e.agentId??sp}`)}catch{throw new f(`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=ca(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=i(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."]})}},"#dispatchFunction");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}){y("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: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 ti=new WeakMap,ap={tags:[]},or=class extends Ye{constructor(t){super();this.options=t;y("metrics.datadog")}static{i(this,"DataDogMetricsPlugin")}getTransport(){return new ni(this.options)}static setContext(t,r){let o=ti.get(t);o||(o=ap);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=i(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())},"dispatchFunction")},ri=class n extends Error{static{i(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var oi=new WeakMap,up={dimensions:[]},ir=class extends Ye{constructor(t){super();this.options=t;y("metrics.dynatrace")}static{i(this,"DynatraceMetricsPlugin")}getTransport(){return new ii(this.options)}static setContext(t,r){let o=oi.get(t);o||(o=up);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=i(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())},"dispatchFunction")},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,y("audit-logs.datastax")}#e;writeLogBatch=i(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)})}))},"writeLogBatch")};var ar=class extends Fe{static{i(this,"AuditLogPlugin")}constructor(e,t){super(),this.#e=e,this.#t=t,y("audit-logs")}#e;#t;async initialize(e){new ai(e,this.#e,this.#t)}},za=i(n=>{let e={};return n.forEach((t,r)=>{e[r]=t}),e},"serializableHeaders"),cp={requestFilter:i(async()=>!0,"requestFilter"),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={...cp};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=i(async e=>{await this.#t.writeLogBatch(e)},"#dispatch");#o=i(async(e,t,r,o,s,a)=>{try{let u={timestamp:o,durationMs:s,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:t.url,method:t.method,headers:this.#e.include?.request?.headers?za(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?za(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(u),r.waitUntil(this.#n.waitUntilFlushed())}catch(u){r.log.error(u)}},"#asyncPrepLogs");#i=i(async(e,t)=>{try{if(!await this.#e.requestFilter(e,t))return e;let o=new Date,s=Date.now(),a=e.clone();return t.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#o(d,a,t,o,l-s,c.user?.sub).catch(g=>{t.log.error(g)});t.waitUntil(p)}),e}catch(r){return t.log.error(r),e}},"#auditHook")};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 lp="v1",dp=300;async function Ba(n,e,t,r=dp,o){return await mp(n,e,t,r,o),n instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(n)):JSON.parse(n)}i(Ba,"constructEventAsync");function pp(n,e){return`${e.timestamp}.${n}`}i(pp,"makeHMACContent");async function mp(n,e,t,r,o){let{decodedHeader:s,decodedPayload:a,details:u,suspectPayloadType:c}=gp(n,e,lp),l=/\s/.test(t),d=await bp(pp(a,u),t);return fp(a,s,u,d,r,c,l,o)}i(mp,"verifyHeaderAsync");function gp(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=hp(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(gp,"parseEventDetails");function fp(n,e,t,r,o,s,a,u){let c=!!t.signatures.filter(g=>yp(g,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,9 +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(fp,"validateComputedSignature");function hp(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(hp,"parseHeader");function yp(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(yp,"secureCompare");async function bp(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(bp,"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 f(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let s=i((c,l,d)=>{let p=n[c],g=r?`${r}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new f(`Value of '${g}' 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 f(`Value of '${g}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new f(`Value of '${g}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new f(`Value of '${g}' 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 f(`Value of '${g}' 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),y("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 za(o,r,this.options.signingSecret)}catch(o){let s=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a,s.startsWith("No signatures found matching the expected signature for payload")&&(s="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",s),x.badRequest(e,t,{title:"Webhook Error",detail:s})}return e}};function Ga(n){return n!==null&&typeof n=="object"&&"id"in n&&Oe(n.id)&&"type"in n&&Oe(n.type)}i(Ga,"isStripeWebhookEvent");var wp={getSubscription:i(async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving subscription from Stripe API.";throw t.error(s,o),new L(s)}return o},"getSubscription"),getCustomer:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer from Stripe API.";throw t.error(s,o),new L(s)}return o},"getCustomer"),getUpcomingInvoice:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(s,o),new L(s)}return o},"getUpcomingInvoice")},ur=wp;var li="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Va="My API Key";async function Wa({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=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:Va,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)}),g=await p.json();if(p.status!==200){let h="Error creating API Key Consumer";throw a.log.error(h,g),new L(h)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(Wa,"createConsumer");async function Ka({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:Va,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 g="Error creating API Key Consumer";throw s.log.error(g,p),new L(g)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(Ka,"createConsumerInvite");async function Ja({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 L(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(Ja,"deleteConsumer");async function Qa({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:r,meteringBucketId:o,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[t],customerKey:r,customerExternalId:a,metadata:c,trialEndDate:l?l.trialEndDate:void 0,trialStartDate:l?l.trialStartDate:void 0,trialEndStatus:l?l.trialEndStatus:void 0},{authApiJWT:p,meteringServiceUrl:g}=m.instance;if(!It(p))throw new Q("No Zuplo JWT token set.");let h=await be({retryDelayMs:5,retries:2,logger:te.getLogger(n)},`${g}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!h.ok){let v=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,b,I="";try{b=await h.json(),I=b.detail??b.title}catch{b={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:h.status,detail:h.statusText}}throw n.log.error(v,b),new L(`${v} ${I}`)}n.log.info("Successfully created monetization subscription.",d)}i(Qa,"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 L(`${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 L(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(c),new L(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(c),new L(c)}return u.data[0]}i(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.`),x.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.`),x.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}'`),x.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}'.`),x.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 Wa({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.`),x.ok(n,e,{title:ae,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Ka({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}}catch(p){return e.log.warn(`Failed to create API Key Consumer. Error: ${p.message}`),x.ok(n,e,{title:ae,detail:p.message})}if(!c)return x.ok(n,e,{title:ae,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=cr(t.data.object.status),g;l&&d&&(g={subscriber:{sub:d,email:l}});let h;t.data.object.trial_end!==null&&t.data.object.trial_start!==null&&t.data.object.trial_settings&&t.data.object.trial_settings.end_behavior&&(t.data.object.trial_settings.end_behavior.missing_payment_method==="cancel"||t.data.object.trial_settings.end_behavior.missing_payment_method==="pause")&&(h={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:gt(t.data.object.trial_end),trialStartDate:gt(t.data.object.trial_start)}),await Qa({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:g,trial:h})}catch(p){return await Ja({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),x.ok(n,e,{title:ae,detail:p.message})}return x.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.`),x.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}'`),x.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}'.`),x.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 x.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 x.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.`),x.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}'`),x.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}'.`),x.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 x.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 x.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(g=>g.proration&&g.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 x.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 x.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 x.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 x.ok(n,e,{title:nt})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),x.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;y("monetization.stripe")}static{i(this,"StripeMonetizationPlugin")}registerRoutes(t,r){let o=i(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(Ee.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Ee.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new f("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 f("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 g=this.options.primaryDataRegion??"us-central1";if(!Rp(g))throw new f(`StripeMonetizationPlugin - The value '${g}' on the property 'primaryDataRegion' is invalid.`);let h=await c.json();if(!Ga(h))return x.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 '${h.type}' with ID '${h.id}'.`),h.type){case"customer.subscription.created":return await di(c,l,h,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:g,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await mi(c,l,h,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:g,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await pi(c,l,h,{meteringBucketId:d});default:return x.ok(c,l,{title:ae,detail:`Event '${h.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+xe})}},"stripeWebhookHandler"),s=ea({inboundPolicies:[new 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 Rp(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}i(Rp,"isMetricsRegion");var Xa=new WeakMap,Ya={},lr=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){Xa.set(e,t)}};async function eu(n,e,t,r){if(y("policy.inbound.amberflo-metering"),!t.statusCodes)throw new f(`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=Xa.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new L(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=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)},g=Ya[t.apiKey];if(!g){let h=t.apiKey,v=n.headers.get("zm-test-id")??"";g=new ee("amberflo-ingest-meter",10,async b=>{try{let I=t.url??"https://app.amberflo.io/ingest",D=await F.fetch(I,{method:"POST",body:JSON.stringify(b),headers:{"content-type":"application/json","x-api-key":h,"zm-test-id":v}});D.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${D.status}: ${await D.text()}`)}catch(I){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${I.message}`),I}}),Ya[h]=g}g.enqueue(p),e.waitUntil(g.waitUntilFlushed())}}),n}i(eu,"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 tu=new Map;async function ce(n,e,t){let r,o=`${n}-${e}`,s=tu.get(o);return s!==void 0?r=s:(r=`zuplo-policy-${await ft(JSON.stringify({policyName:n,options:t}))}`,tu.set(n,r)),r}i(ce,"getPolicyCacheName");var nu="key-metadata-cache-type";function Pp(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}i(Pp,"getKeyValue");async function dr(n,e,t,r){if(y("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 f(`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 f(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let s=i(I=>o.allowUnauthenticatedRequests?n:x.unauthorized(n,e,{detail:I}),"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=Pp(a,o);if(!u||u==="")return s("No key present");let c=await Ip(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!==nu&&te.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let g={key:u},h=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(g)});if(h.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(h.status!==200){try{let I=await h.text(),D=JSON.parse(I);e.log.error("Unexpected response from key service",D)}catch{e.log.error("Invalid response from key service")}throw new L(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${h.status}`)}let v=await h.json(),b={isValid:!0,typeId:nu,user:{sub:v.name,data:v.metadata}};return n.user=b.user,d.put(c,b,o.cacheTtlSeconds),n}i(dr,"ApiKeyInboundPolicy");async function Ip(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(Ip,"hashValue");var ru=dr;var ln=require("jose");var ou=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,ou.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 iu(n,e,t){let r=new fi(n,e,t);return async(o,s)=>r.getKey(o,s)}i(iu,"createRemoteJWKSet");var kt=class extends L{static{i(this,"JWKSError")}},hi=class extends kt{static{i(this,"JWKSNoMatchingKey")}},yi=class extends kt{static{i(this,"JWKSTimeout")}};var pr={},Ep=i((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new f("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]=iu(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"),Tp=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)=>{y("policy.inbound.open-id-jwt-auth");let o=n.headers.get("Authorization"),s="bearer ",a=i(g=>x.unauthorized(n,e,{detail:g}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=t.jwkUrl?Ep(r,e):Tp,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 g=o.substring(s.length);if(!g||g.length===0)return a("No bearer token on authorization header");try{return await u(g,t)}catch(h){let v=new URL(n.url);return"code"in h&&h.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${v.pathname} `,h):e.log.warn(`Invalid token on: ${n.method} ${v.pathname}`,h),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return t.allowUnauthenticatedRequests===!0?n:l;let d=t.subPropertyName??"sub",p=l[d];return p?(n.user={sub:p,data:l},n):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var su=i(async(n,e,t,r)=>(y("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),y("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:x.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),x.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 au=i(async(n,e,t)=>{y("policy.inbound.basic-auth");let r=n.headers.get("Authorization"),o="basic ",s=i(l=>x.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!r)return await s("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await s("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let g=d.substring(0,p),h=d.substring(p+1),v=t.accounts.find(b=>b.username===g&&b.password===h);return v||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 uu(n,e){return new Date(n,e+1,0).getDate()}i(uu,"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=uu(t,r),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return o>s?e==="next"?void 0:s:o;let c;a&&(c=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),c!==void 0&&c>s&&(c=void 0));let l;if(u){let d=new Date(t,r,o).getDay(),p=e==="next"?this.weekdays.find(g=>g>=d)??this.weekdays[0]:this.reversed.weekdays.find(g=>g<=d)??this.reversed.weekdays[0];if(p!==void 0){let g=e==="next"?bi(d,p):bi(p,d);l=e==="next"?o+g:o-g,(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 g=this.findAllowedTime("next",t);if(g!==void 0)return new Date(u,c,d,g.hour,g.minute,g.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 g=this.findAllowedTime("prev",t);if(g!==void 0)return new Date(u,c,d,g.hour,g.minute,g.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 xp={min:0,max:59},Op={min:0,max:59},vp={min:0,max:23},Cp={min:1,max:31},Sp={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"}},Ap={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},_p={"@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(g=>t.add(g))}),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=_p[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,xp),minutes:ht(r,Op),hours:ht(o,vp),days:ht(s,Cp),months:new Set(Array.from(ht(a,Sp)).map(c=>c-1)),weekdays:new Set(Array.from(ht(u,Ap)).map(c=>c%7))})}i(wi,"parseCronExpression");var yr=class extends le{static{i(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),y("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 f(`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=x.getProblemFromStatus(this.options.problem?.status??400,{detail:"This API is performing a scheduled brownout in advance of its pending deprecation. Please upgrade to a later version.",...this.options.problem});return x.format(s,e,t)}return e}};var Lp=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function kp(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(kp,"digestMessage");var Np=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 kp(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 cu(n,e,t,r){y("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 Np(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 g=t?.expirationSecondsTtl??60,h=new Response(p.body,p);Lp.forEach(v=>h.headers.delete(v)),h.headers.set("cache-control",`s-maxage=${g}`),e.waitUntil(s.put(u,h))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}i(cu,"CachingInboundPolicy");var lu=i(async(n,e,t,r)=>{if(y("policy.inbound.change-method"),!t.method)throw new f(`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 Dp(n,e){if(Ws(n))throw new Ri(e)}i(Dp,"throwIfUndefinedOrNull");function du(n,e){if(Dp(n,e),!Oe(n))throw new Pi(e,"string")}i(du,"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}){du(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),y("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=Mp(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=Up(l.key,this.policyName);r&&t.log.debug(`QuotaInboundPolicy: key - '${d}'`);let p=ot(this.policyName,o),g=await p.getQuota(d,t.requestId);r&&t.log.debug("QuotaInboundPolicy: quotaResult",g),c&&new Date(g.anchorDate)!==c&&t.log.warn(`QuotaInboundPolicy '${this.policyName}' provided anchorDate ('${c}') did not match the stored, immutable anchorDate ('${g.anchorDate}')`);let h=Object.assign({},s.defaultAllowances);Object.assign(h,l.allowances);let v=[],b="";if(Object.entries(h).forEach(([I,D])=>{r&&(b+=`${I} - allowed: ${D} value: ${g.meters[I]??0}
72
- `),(g.meters[I]??0)>=D&&v.push(I)}),r&&t.log.debug("QuotaInboundPolicy: debugTable",b),v.length>0)return x.tooManyRequests(e,t,{detail:`Quota exceeded for meters '${v.join(", ")}'`});t.addResponseSendingFinalHook(async(I,D,A)=>{if(r&&A.log.debug(`QuotaInboundPolicy: backend response - ${I.status}: ${I.statusText}`),!s.quotaOnStatusCodes.includes(I.status))return;let $=ue.get(A,Ti),N={config:{period:s.period,anchorDate:c?.toISOString()??""},increments:$};r&&A.log.debug("QuotaInboundPolicy: setQuotaDetails",N);let j=p.setQuota(d,N,A.requestId);A.waitUntil(j)})}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 Mp(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 f(`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 f(`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(Mp,"validateAndParseOptions");function Up(n,e){return encodeURIComponent(`${e}-${n}`)}i(Up,"processKey");var pu=i(async(n,e,t)=>{y("policy.inbound.clear-headers");let r=[...t.exclude??[]],o=new Headers;return r.forEach(a=>{let u=n.headers.get(a);u&&o.set(a,u)}),new oe(n,{headers:o})},"ClearHeadersInboundPolicy");var mu=i(async(n,e,t,r)=>{y("policy.outbound.clear-headers");let o=[...r.exclude??[]],s=new Headers;return o.forEach(u=>{let c=n.headers.get(u);c&&s.set(u,c)}),new Response(n.body,{headers:s,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var gu=i(async(n,e,t,r)=>{y("policy.inbound.clerk-jwt-auth");let o=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),s=new URL(o);return s.pathname="/.well-known/jwks.json",we(n,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var fu=i(async(n,e,t,r)=>{if(y("policy.inbound.cognito-jwt-auth"),!t.userPoolId)throw new f("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new f("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 yu=ze(He());var qp=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:$p(e,"RateLimitInboundPolicy",n),user:Hp,ip:Zp,all:Fp}[e.rateLimitBy??"ip"]}i(Nt,"getRateLimitByFunctions");var Zp=i(async n=>({key:`ip-${qp(n)}`}),"getIP"),Hp=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),Fp=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll");function $p(n,e,t){let r;if(n.rateLimitBy==="function"){if(!n.identifier)throw new f(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new f(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new f(`${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 f(`${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(l)}if(!("key"in c)){let l=`${e} '${u}' - Custom rate limit function must return a valid key property.`;throw a.log.error(l,c),new L(l)}if(typeof c.key!="string"){let l=`${e} '${u}' - Custom rate limit function must return a valid key property of type string. Received type '${typeof c.key}'`;throw a.log.error(l),new L(l)}return c},"outerFunction")}i($p,"wrapUserFunction");var Dt="Retry-After";var hu=(0,yu.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),y("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 f(`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()),x.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),g=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;t.addResponseSendingFinalHook(async()=>{try{let I=n.getIncrements(t);hu(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(I)}`);let D=Object.entries(p).map(([$])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${$}`,ttlSeconds:g,increment:I[$]??0})),A=s.multiIncrement(D,t.requestId);t.waitUntil(A),await A}catch(I){o.error(I),t.log.error(I)}});let h=Object.entries(p).map(([I,D])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${I}`,ttlSeconds:g,limit:D})),v=await s.multiCount(h,t.requestId);return jp(v,h).length>0?u(this.options.headerMode??"retry-after",g):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-r;hu(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function jp(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(jp,"findOverLimits");var bu=i(async(n,e,t,r)=>{if(y("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new f(`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 wu=i(async(n,e,t,r)=>{y("policy.inbound.curity-phantom-token-auth");let o=n.headers.get("Authorization");if(!o)return x.unauthorized(n,e,{detail:"No authorization header"});let s=Bp(o);if(!s)return x.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}'`),x.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):x.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function Bp(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(Bp,"getToken");var Ru=i(async(n,e,t,r)=>(y("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 Pu=i(async(n,e,t)=>{y("policy.inbound.form-data-to-json");let r="application/x-www-form-urlencoded",o="multipart/form-data",s=n.headers.get("content-type")?.toLowerCase();if(!s||![o,r].includes(s))return t&&t.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):n;let a=await n.formData();if(t&&t.optionalHoneypotName&&a.get(t.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(n.headers);return c.set("content-type","application/json"),c.delete("content-length"),new oe(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var Mt="__unknown__",Iu=i(async(n,e,t,r)=>{y("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,g=o.allow.regionCodes,h=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||g.length>0&&!g.includes(a)&&!l||h.length>0&&!h.includes(u)&&!d)return Ut(n,e,r,s,a,u);let v=o.block.countries,b=o.block.regionCodes,I=o.block.asns;return v.length>0&&v.includes(s)&&!c||b.length>0&&b.includes(a)&&!l||I.length>0&&I.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}')`),x.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 f(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}i(qt,"toLowerStringArray");var Eu=i(async(n,e,t)=>{y("policy.inbound.jwt-scope-validation");let r=n.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(r,t.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var xu=i(async(n,e,t,r)=>{y("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(g=>{a.push({responseName:u,contentName:l,exampleName:g,exampleValue:d[g]})})})}),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 Tu(a[u])}else return a.length>0?Tu(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 Tu(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(Tu,"generateResponse");var Oi=i((n,e,t,r)=>{let o=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${r}`;return x.internalServerError(e,t,{detail:o})},"getProblemDetailResponse");var zp="Incoming",Gp={logRequestBody:!0,logResponseBody:!0};function Ou(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}i(Ou,"headersToObject");function vu(){return new Date().toISOString()}i(vu,"timestamp");var vi=new WeakMap,Vp={};function Au(n,e){let t=vi.get(n);t||(t=Vp);let r=Object.assign({...t},e);vi.set(n,r)}i(Au,"setMoesifContext");async function Cu(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(Cu,"readBody");var Wp={},Ci;function Su(){if(!Ci)throw new L("Invalid State - no _lastLogger");return Ci}i(Su,"getLastLogger");function Kp(n){let e=Wp[n];return e||(e=new ee("moesif-inbound",100,async t=>{let r=JSON.stringify(t);Su().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||Su().error({status:o.status,body:await o.text()})})),e}i(Kp,"getDispatcher");async function _u(n,e,t,r){y("policy.inbound.moesif-analytics"),Ci=e.log;let o=vu(),s=Object.assign(Gp,t);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await Cu(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Kp(s.applicationId),d=n.headers.get("true-client-ip"),p=vi.get(e)??{},g={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Ou(n.headers)},h=s.logResponseBody?await Cu(u,e):void 0,v={time:vu(),status:u.status,headers:Ou(u.headers),body:h},b={request:g,response:v,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:zp};l.enqueue(b),e.waitUntil(l.waitUntilFlushed())}),n}i(_u,"MoesifInboundPolicy");async function Lu(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(Lu,"loadSubscription");async function ku(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(ku,"consumeSubcriptionQuotas");var Jp=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 f(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 f?new f(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}i(Pr,"validateMeters");function Nu(n,e){if(n)try{if(n.length===0)throw new f("Must set valid subscription statuses");let t=pt(n),r=[];for(let o of t)Jp.has(o)||r.push(o);if(r.length>0)throw new f(`Found the following invalid statuses: ${r.join(", ")}`);return n}catch(t){throw t instanceof f?new f(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}i(Nu,"parseAllowedSubscriptionStatuses");function Du(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(Du,"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),y("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=Nu(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(b,I,D)=>{let A=ue.get(D,Vt);if((this.options.allowRequestsWithoutSubscription??!1)&&!A){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 f(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let N=ue.get(D,Wt),j={...this.options.meters,...N};if(Pr(j,this.policyName),o.includes(b.status)&&A&&j){D.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${A.id}' with meters '${JSON.stringify(j)} on response status '${b.status}'`);let{metersInSubscription:T,metersNotInSubscription:Z}=Du(A.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 ku(D,A.id,this.policyName,this.options.bucketId,T)}});let l=e.user;if(!l)return u?e:x.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(Ee.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Ee.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new f(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await Lu(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:x.unauthorized(e,t,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return t.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),x.unauthorized(e,t,{detail:"No valid subscription found"});c.includes(p.status)&&(t.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),ue.set(t,Vt,p));let g=ue.get(t,Vt);if(!g)return u?e:(t.log.warn("Subscription is not available for user"),x.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(g&&Object.keys(g.meters).length===0)return t.log.error(`Quota is not set up for subscription '${g.id}'`),x.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let v=Object.keys(a).filter(b=>!Object.keys(g.meters).includes(b));if(v.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${v.join(", ")}`),x.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${v.join(", ")}`,title:"Quota Exceeded"});for(let b of Object.keys(a))if(g.meters[b].available<=0&&!r)return x.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${b}'`,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 L("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 L("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 Mu="X-OpenFGA-Client-Method",Uu="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,Mu,"BatchCheck"),dn(r,Uu,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,Mu,"ListRelations"),dn(c,Uu,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 qu=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,qu,r)}constructor(e,t){if(super(e,t),Y(e,t).required("apiUrl","string").optional("storeId","string").optional("authorizationModelId","string"),!e.credentials)throw new f(`${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 f(`${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:x.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=ue.get(t,qu);if(!o||o.length===0)throw new L(`${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),x.internalServerError(e,t)}}getAuthorizer(e){if(e.method==="none")return async()=>({});if(e.method==="header")return async t=>{let r=e.headerName??"Authorization",o=t.headers.get(r);if(!o)throw new 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 L("Invalid state for credentials method is not valid. This should not happen.")}};var Zu=["us1","eu1","au1"],xr=class extends Ht{static{i(this,"OktaFGAAuthZInboundPolicy")}constructor(e,t){if(!Zu.includes(e.region))throw new f(`OktaFGAAuthZInboundPolicy '${t}' - The 'region' option is invalid. Must be one of ${Zu.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),y("policy.inbound.oktafga-authz")}};var Hu=i(async(n,e,t,r)=>(y("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),y("policy.inbound.openfga-authz")}};var Fu=require("jose");var Si,$u=i(async(n,e,t,r)=>{if(y("policy.inbound.propel-auth-jwt-auth"),!Si)try{Si=await(0,Fu.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 Vu=ze(He());var Bu=ze(He());var ju=(0,Bu.debug)("zuplo:policies:RateLimitInboundPolicy"),zu=i(async(n,e,t,r)=>{let o=te.getLogger(e),s=i((j,T)=>{let Z={};return(!j||j==="retry-after")&&(Z[Dt]=T.toString()),x.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",g=ot(r,o),v=`rate-limit${m.instance.isTestMode?m.instance.build.BUILD_ID:""}/${r}/${c}`,b=await ce(r,void 0,t),I=new se(b,e),D=g.getCountAndUpdateExpiry(v,d,e.requestId),A;i(async()=>{let j=await D;if(j.count>l){let T=Date.now()+j.ttlSeconds*1e3;I.put(v,T,j.ttlSeconds),ju(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${v}' (async mode)`),A=s(p,j.ttlSeconds)}},"asyncCheck")();let N=await I.get(v);if(N!==void 0&&N>Date.now()){ju(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${v}' (async mode)`);let j=Math.round((N-Date.now())/1e3);return s(p,j)}return e.addResponseSendingHook(async j=>A??j),n},"AsyncRateLimitInboundPolicyImpl");var Gu=(0,Vu.debug)("zuplo:policies:RateLimitInboundPolicy"),Qp="strict",Ai=i(async(n,e,t,r)=>{if(y("policy.inbound.rate-limit"),(t.mode??Qp)==="async")return zu(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()),x.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await Nt(r,t)(n,e,r),p=d.key,g=d.requestsAllowed??t.requestsAllowed,h=d.timeWindowMinutes??t.timeWindowMinutes,v=t.headerMode??"retry-after",b=ot(r,a),D=`rate-limit${m.instance.isTestMode||m.instance.isWorkingCopy?m.instance.build.BUILD_ID:""}/${r}/${p}`,A=await b.getCountAndUpdateExpiry(D,h,e.requestId);return A.count>g?(Gu(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${D}' (strict mode)`),c(v,A.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-s;Gu(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var _i;function Wu(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}i(Wu,"headersToNameValuePairs");function Yp(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}i(Yp,"queryToNameValueParis");function Xp(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}i(Xp,"parseIntOrUndefined");var Ku={};async function Ju(n,e,t,r){y("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:Wu(n.headers),queryString:Yp(n.query)},response:{status:a.status,statusText:a.statusText,headers:Wu(a.headers),content:{size:Xp(n.headers.get("content-length"))}}}]}}},d=Ku[t.apiKey];if(!d){let p=t.apiKey;d=new ee("readme-metering-inbound-policy",10,async g=>{try{let h=t.url??"https://metrics.readme.io/request",v=await F.fetch(h,{method:"POST",body:JSON.stringify(g),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});v.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${v.status}: '${await v.text()}'`)}catch(h){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${h.message}'`),h}}),Ku[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}i(Ju,"ReadmeMetricsInboundPolicy");var Qu=i(async(n,e,t,r)=>{y("policy.inbound.remove-headers");let o=t?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new f(`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)=>{y("policy.outbound.remove-headers");let s=r?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new f(`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)=>{y("policy.inbound.remove-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length===0)throw new f(`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 ec=i(async(n,e,t,r)=>{y("policy.outbound.replace-string");let o=await n.text(),s=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(s,r.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var tc=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),nc=i(async(n,e,t)=>{y("policy.inbound.request-size-limit");let r=t.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(n.method))return n;let o=n.headers.get("content-length"),s=o!==null?parseInt(o):void 0;return s&&!isNaN(s)&&s>t.maxSizeInBytes?tc():s&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?tc():n},"RequestSizeLimitInboundPolicy");function rc(n,e,t){return`_${it(n+"_"+e+"_"+t)}`}i(rc,"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 oc(n,e){return`_${it(n)}__${it(e)}`}i(oc,"getIdForRefSchema");function it(n){let e=[];for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122?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],g=p(e[c.name]),h=Li(p.errors);g||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${h.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),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 ic(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(h){let v=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,b=x.badRequest(e,n,{detail:`${v}, see errors property for more details`,errors:`${h}`});if(Ne(t.validateBody)&&ke(n,t.logLevel??"info",v,[r],h),De(t.validateBody))return b}if(!e.headers.get("Content-Type")){let h=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,v=x.badRequest(e,n,{detail:h});return Ne(t.validateBody)&&ke(n,t.logLevel??"info",h,[r],[h]),De(t.validateBody)?v: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 h=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,v=x.badRequest(e,n,{detail:h});return Ne(t.validateBody)&&ke(n,t.logLevel??"info",h,[r],[h]),De(t.validateBody)?v:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Li(l),g=x.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 g}i(ic,"handleBodyValidation");function sc(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=x.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(sc,"handleHeadersValidation");function ac(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=x.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(ac,"handlePathParameterValidation");function uc(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=x.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(uc,"handleQueryParameterValidation");var ki=i(async(n,e,t)=>{y("policy.inbound.request-validation");let r=uc(e,n,t);if(r!==void 0||(r=ac(e,n,t),r!==void 0)||(r=sc(e,n,t),r!==void 0))return r;let o=await ic(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),cc=ki;var lc=i(async(n,e,t,r)=>{if(y("policy.inbound.require-origin"),t.origins===void 0||t.origins.length===0)throw new f(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof t.origins=="string"?t.origins.split(","):t.origins;o=o.map(a=>a.trim());let s=n.headers.get("origin");if(!s||!o.includes(s)){let a=t.failureDetail??"Forbidden";return x.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var dc=i(async(n,e,t)=>(y("policy.inbound.set-body"),new oe(n,{body:t.body})),"SetBodyInboundPolicy");var pc=i(async(n,e,t,r)=>{y("policy.inbound.set-headers");let o=t.headers;if(!o||!Array.isArray(o)||o.length==0)throw new f(`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 f(`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 mc=i(async(n,e,t,r,o)=>{y("policy.outbound.set-headers");let s=r.headers;if(!s||!Array.isArray(s)||s.length==0)throw new f(`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 f(`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 gc=i(async(n,e,t,r)=>{y("policy.inbound.set-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length==0)throw new f(`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 f(`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 fc=i(async(n,e,t,r,o)=>{if(y("policy.outbound.set-status"),!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(n.body,{headers:n.headers,status:r.status,statusText:r.statusText??n.statusText})},"SetStatusOutboundPolicy");var em=i(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),hc=i(async(n,e,t,r)=>{if(y("policy.inbound.sleep"),!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new f(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await em(t.sleepInMs),n},"SleepInboundPolicy");var yc=i(async(n,e,t,r)=>{y("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 L(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?x.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var bc=i(async(n,e,t,r)=>{y("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 tm(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 tm(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 L("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new L("Response returned from Azure AD is not in the expected format.")}i(tm,"getAccessToken");var wc="https://accounts.google.com/o/oauth2/token",Ni,Rc=i(async(n,e,t,r)=>{y("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:wc,payload:o}),l=await qn(wc,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new L("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var nm="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",rm=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Di,Pc=i(async(n,e,t,r)=>{if(y("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 f(`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(rm.indexOf(p)!==-1)throw new f(`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 L("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new L(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=dt(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new L(`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:nm,payload:c}),g=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,h=await pa(g,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!h.idToken)throw new L("Invalid token response from Firebase");d=h.idToken,u.put(l,d,(h.expiresIn?parseInt(h.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var 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 L("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 Ic="workload-access-token",Ec="service-account-id-token",Sr=class extends le{static{i(this,"UpstreamGcpFederatedAuthInboundPolicy")}cacheName;normalizedWorkloadIdentityProvider;constructor(e,t){super(e,t),y("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(Ic);if(!o){let a=`https://iam.googleapis.com/${this.normalizedWorkloadIdentityProvider}`,u=await jt.getIDToken(t,{audience:a}),c=await la(this.normalizedWorkloadIdentityProvider,u,{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!c.access_token||!c.expires_in)throw new L("Invalid token response from GCP");o=c.access_token,r.put(Ic,o,c.expires_in-(this.options.expirationOffsetSeconds??300))}let s=await r.get(Ec);if(!s){let a=await da({serviceAccountEmailOrIdentifier:this.options.serviceAccountEmail,audience:this.options.audience,accessToken:o},{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!a.token)throw new L("Invalid token response from GCP");s=a.token,r.put(Ec,o,3600-(this.options.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${s}`),e}};var Mi,Tc=i(async(n,e,t,r)=>{y("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 xc="https://www.googleapis.com/oauth2/v4/token",Ui,Oc=i(async(n,e,t,r)=>{y("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 f("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 f?new f(`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:xc,payload:o}),l=await qn(xc,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new L("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new L("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var vc=i(async(n,e,t)=>{y("policy.inbound.validate-json-schema");let r=n.clone(),o;try{o=await r.json()}catch{return x.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator(o))return n;let{errors:a}=t.validator;if(!a)throw new 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 x.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var Cc=i(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=i((b,I)=>e(b,"name",{value:I,configurable:!0}),"__name"),o=i((b,I)=>i(function(){return I||(0,b[t(b)[0]])((I={exports:{}}).exports,I),I.exports},"__require"),"__commonJS"),s=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(b){var I={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:i(function(A,$){return $},"tagValueProcessor"),attributeValueProcessor:i(function(A,$){return $},"attributeValueProcessor"),stopNodes:[],alwaysCreateTextNode:!1,isArray:i(()=>!1,"isArray"),commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:i(function(A,$,N){return A},"updateTag")},D=r(function(A){return Object.assign({},I,A)},"buildOptions");b.buildOptions=D,b.defaultOptions=I}}),a=o({"node_modules/fast-xml-parser/src/util.js"(b){"use strict";var I=":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=I+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",A="["+I+"]["+D+"]*",$=new RegExp("^"+A+"$"),N=r(function(T,Z){let V=[],W=Z.exec(T);for(;W;){let S=[];S.startIndex=Z.lastIndex-W[0].length;let O=W.length;for(let H=0;H<O;H++)S.push(W[H]);V.push(S),W=Z.exec(T)}return V},"getAllMatches"),j=r(function(T){let Z=$.exec(T);return!(Z===null||typeof Z>"u")},"isName");b.isExist=function(T){return typeof T<"u"},b.isEmptyObject=function(T){return Object.keys(T).length===0},b.merge=function(T,Z,V){if(Z){let W=Object.keys(Z),S=W.length;for(let O=0;O<S;O++)V==="strict"?T[W[O]]=[Z[W[O]]]:T[W[O]]=Z[W[O]]}},b.getValue=function(T){return b.isExist(T)?T:""},b.isName=j,b.getAllMatches=N,b.nameRegexp=A}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(b,I){"use strict";var D=class{static{i(this,"XmlNode")}static{r(this,"XmlNode")}constructor(A){this.tagname=A,this.child=[],this[":@"]={}}add(A,$){A==="__proto__"&&(A="#__proto__"),this.child.push({[A]:$})}addChild(A){A.tagname==="__proto__"&&(A.tagname="#__proto__"),A[":@"]&&Object.keys(A[":@"]).length>0?this.child.push({[A.tagname]:A.child,":@":A[":@"]}):this.child.push({[A.tagname]:A.child})}};I.exports=D}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(b,I){var D=a();function A(S,O){let H={};if(S[O+3]==="O"&&S[O+4]==="C"&&S[O+5]==="T"&&S[O+6]==="Y"&&S[O+7]==="P"&&S[O+8]==="E"){O=O+9;let ge=1,X=!1,ne=!1,Se="";for(;O<S.length;O++)if(S[O]==="<"&&!ne){if(X&&j(S,O))O+=7,[entityName,val,O]=$(S,O+1),val.indexOf("&")===-1&&(H[W(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(X&&T(S,O))O+=8;else if(X&&Z(S,O))O+=8;else if(X&&V(S,O))O+=9;else if(N)ne=!0;else throw new Error("Invalid DOCTYPE");ge++,Se=""}else if(S[O]===">"){if(ne?S[O-1]==="-"&&S[O-2]==="-"&&(ne=!1,ge--):ge--,ge===0)break}else S[O]==="["?X=!0:Se+=S[O];if(ge!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:H,i:O}}i(A,"readDocType"),r(A,"readDocType");function $(S,O){let H="";for(;O<S.length&&S[O]!=="'"&&S[O]!=='"';O++)H+=S[O];if(H=H.trim(),H.indexOf(" ")!==-1)throw new Error("External entites are not supported");let ge=S[O++],X="";for(;O<S.length&&S[O]!==ge;O++)X+=S[O];return[H,X,O]}i($,"readEntityExp"),r($,"readEntityExp");function N(S,O){return S[O+1]==="!"&&S[O+2]==="-"&&S[O+3]==="-"}i(N,"isComment"),r(N,"isComment");function j(S,O){return S[O+1]==="!"&&S[O+2]==="E"&&S[O+3]==="N"&&S[O+4]==="T"&&S[O+5]==="I"&&S[O+6]==="T"&&S[O+7]==="Y"}i(j,"isEntity"),r(j,"isEntity");function T(S,O){return S[O+1]==="!"&&S[O+2]==="E"&&S[O+3]==="L"&&S[O+4]==="E"&&S[O+5]==="M"&&S[O+6]==="E"&&S[O+7]==="N"&&S[O+8]==="T"}i(T,"isElement"),r(T,"isElement");function Z(S,O){return S[O+1]==="!"&&S[O+2]==="A"&&S[O+3]==="T"&&S[O+4]==="T"&&S[O+5]==="L"&&S[O+6]==="I"&&S[O+7]==="S"&&S[O+8]==="T"}i(Z,"isAttlist"),r(Z,"isAttlist");function V(S,O){return S[O+1]==="!"&&S[O+2]==="N"&&S[O+3]==="O"&&S[O+4]==="T"&&S[O+5]==="A"&&S[O+6]==="T"&&S[O+7]==="I"&&S[O+8]==="O"&&S[O+9]==="N"}i(V,"isNotation"),r(V,"isNotation");function W(S){if(D.isName(S))return S;throw new Error(`Invalid entity name ${S}`)}i(W,"validateEntityName"),r(W,"validateEntityName"),I.exports=A}}),l=o({"../../node_modules/strnum/strnum.js"(b,I){var D=/^[-+]?0x[a-fA-F0-9]+$/,A=/^([\-\+])?(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 $={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function N(T,Z={}){if(Z=Object.assign({},$,Z),!T||typeof T!="string")return T;let V=T.trim();if(Z.skipLike!==void 0&&Z.skipLike.test(V))return T;if(Z.hex&&D.test(V))return Number.parseInt(V,16);{let W=A.exec(V);if(W){let S=W[1],O=W[2],H=j(W[3]),ge=W[4]||W[6];if(!Z.leadingZeros&&O.length>0&&S&&V[2]!==".")return T;if(!Z.leadingZeros&&O.length>0&&!S&&V[1]!==".")return T;{let X=Number(V),ne=""+X;return ne.search(/[eE]/)!==-1||ge?Z.eNotation?X:T:V.indexOf(".")!==-1?ne==="0"&&H===""||ne===H||S&&ne==="-"+H?X:T:O?H===ne||S+H===ne?X:T:V===ne||V===S+ne?X:T}}else return T}}i(N,"toNumber"),r(N,"toNumber");function j(T){return T&&T.indexOf(".")!==-1&&(T=T.replace(/0+$/,""),T==="."?T="0":T[0]==="."?T="0"+T:T[T.length-1]==="."&&(T=T.substr(0,T.length-1))),T}i(j,"trimZeros"),r(j,"trimZeros"),I.exports=N}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(b,I){"use strict";var D=a(),A=u(),$=c(),N=l(),j=class{static{i(this,"OrderedObjParser")}static{r(this,"OrderedObjParser")}constructor(P){this.options=P,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:i((E,k)=>String.fromCharCode(Number.parseInt(k,10)),"val")},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:i((E,k)=>String.fromCharCode(Number.parseInt(k,16)),"val")}},this.addExternalEntities=T,this.parseXml=O,this.parseTextData=Z,this.resolveNameSpace=V,this.buildAttributesMap=S,this.isItStopNode=ne,this.replaceEntitiesValue=ge,this.readStopNodeData=G,this.saveTextToParentTag=X,this.addChild=H}};function T(P){let E=Object.keys(P);for(let k=0;k<E.length;k++){let z=E[k];this.lastEntities[z]={regex:new RegExp("&"+z+";","g"),val:P[z]}}}i(T,"addExternalEntities"),r(T,"addExternalEntities");function Z(P,E,k,z,M,U,re){if(P!==void 0&&(this.options.trimValues&&!z&&(P=P.trim()),P.length>0)){re||(P=this.replaceEntitiesValue(P));let B=this.options.tagValueProcessor(E,P,k,M,U);return B==null?P:typeof B!=typeof P||B!==P?B:this.options.trimValues?fe(P,this.options.parseTagValue,this.options.numberParseOptions):P.trim()===P?fe(P,this.options.parseTagValue,this.options.numberParseOptions):P}}i(Z,"parseTextData"),r(Z,"parseTextData");function V(P){if(this.options.removeNSPrefix){let E=P.split(":"),k=P.charAt(0)==="/"?"/":"";if(E[0]==="xmlns")return"";E.length===2&&(P=k+E[1])}return P}i(V,"resolveNameSpace"),r(V,"resolveNameSpace");var W=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function S(P,E,k){if(!this.options.ignoreAttributes&&typeof P=="string"){let z=D.getAllMatches(P,W),M=z.length,U={};for(let re=0;re<M;re++){let B=this.resolveNameSpace(z[re][1]),q=z[re][4],de=this.options.attributeNamePrefix+B;if(B.length)if(this.options.transformAttributeName&&(de=this.options.transformAttributeName(de)),de==="__proto__"&&(de="#__proto__"),q!==void 0){this.options.trimValues&&(q=q.trim()),q=this.replaceEntitiesValue(q);let ie=this.options.attributeValueProcessor(B,q,E);ie==null?U[de]=q:typeof ie!=typeof q||ie!==q?U[de]=ie:U[de]=fe(q,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(U[de]=!0)}if(!Object.keys(U).length)return;if(this.options.attributesGroupName){let re={};return re[this.options.attributesGroupName]=U,re}return U}}i(S,"buildAttributesMap"),r(S,"buildAttributesMap");var O=r(function(P){P=P.replace(/\r\n?/g,`
73
- `);let E=new A("!xml"),k=E,z="",M="";for(let U=0;U<P.length;U++)if(P[U]==="<")if(P[U+1]==="/"){let B=w(P,">",U,"Closing Tag is not closed."),q=P.substring(U+2,B).trim();if(this.options.removeNSPrefix){let _e=q.indexOf(":");_e!==-1&&(q=q.substr(_e+1))}this.options.transformTagName&&(q=this.options.transformTagName(q)),k&&(z=this.saveTextToParentTag(z,k,M));let de=M.substring(M.lastIndexOf(".")+1);if(q&&this.options.unpairedTags.indexOf(q)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${q}>`);let ie=0;de&&this.options.unpairedTags.indexOf(de)!==-1?(ie=M.lastIndexOf(".",M.lastIndexOf(".")-1),this.tagsNodeStack.pop()):ie=M.lastIndexOf("."),M=M.substring(0,ie),k=this.tagsNodeStack.pop(),z="",U=B}else if(P[U+1]==="?"){let B=_(P,U,!1,"?>");if(!B)throw new Error("Pi Tag is not closed.");if(z=this.saveTextToParentTag(z,k,M),!(this.options.ignoreDeclaration&&B.tagName==="?xml"||this.options.ignorePiTags)){let q=new A(B.tagName);q.add(this.options.textNodeName,""),B.tagName!==B.tagExp&&B.attrExpPresent&&(q[":@"]=this.buildAttributesMap(B.tagExp,M,B.tagName)),this.addChild(k,q,M)}U=B.closeIndex+1}else if(P.substr(U+1,3)==="!--"){let B=w(P,"-->",U+4,"Comment is not closed.");if(this.options.commentPropName){let q=P.substring(U+4,B-2);z=this.saveTextToParentTag(z,k,M),k.add(this.options.commentPropName,[{[this.options.textNodeName]:q}])}U=B}else if(P.substr(U+1,2)==="!D"){let B=$(P,U);this.docTypeEntities=B.entities,U=B.i}else if(P.substr(U+1,2)==="!["){let B=w(P,"]]>",U,"CDATA is not closed.")-2,q=P.substring(U+9,B);z=this.saveTextToParentTag(z,k,M);let de=this.parseTextData(q,k.tagname,M,!0,!1,!0,!0);de==null&&(de=""),this.options.cdataPropName?k.add(this.options.cdataPropName,[{[this.options.textNodeName]:q}]):k.add(this.options.textNodeName,de),U=B+2}else{let B=_(P,U,this.options.removeNSPrefix),q=B.tagName,de=B.rawTagName,ie=B.tagExp,_e=B.attrExpPresent,Zi=B.closeIndex;this.options.transformTagName&&(q=this.options.transformTagName(q)),k&&z&&k.tagname!=="!xml"&&(z=this.saveTextToParentTag(z,k,M,!1));let Hi=k;if(Hi&&this.options.unpairedTags.indexOf(Hi.tagname)!==-1&&(k=this.tagsNodeStack.pop(),M=M.substring(0,M.lastIndexOf("."))),q!==E.tagname&&(M+=M?"."+q:q),this.isItStopNode(this.options.stopNodes,M,q)){let Ae="";if(ie.length>0&&ie.lastIndexOf("/")===ie.length-1)U=B.closeIndex;else if(this.options.unpairedTags.indexOf(q)!==-1)U=B.closeIndex;else{let Zr=this.readStopNodeData(P,de,Zi+1);if(!Zr)throw new Error(`Unexpected end of ${de}`);U=Zr.i,Ae=Zr.tagContent}let qr=new A(q);q!==ie&&_e&&(qr[":@"]=this.buildAttributesMap(ie,M,q)),Ae&&(Ae=this.parseTextData(Ae,q,M,!0,_e,!0,!0)),M=M.substr(0,M.lastIndexOf(".")),qr.add(this.options.textNodeName,Ae),this.addChild(k,qr,M)}else{if(ie.length>0&&ie.lastIndexOf("/")===ie.length-1){q[q.length-1]==="/"?(q=q.substr(0,q.length-1),M=M.substr(0,M.length-1),ie=q):ie=ie.substr(0,ie.length-1),this.options.transformTagName&&(q=this.options.transformTagName(q));let Ae=new A(q);q!==ie&&_e&&(Ae[":@"]=this.buildAttributesMap(ie,M,q)),this.addChild(k,Ae,M),M=M.substr(0,M.lastIndexOf("."))}else{let Ae=new A(q);this.tagsNodeStack.push(k),q!==ie&&_e&&(Ae[":@"]=this.buildAttributesMap(ie,M,q)),this.addChild(k,Ae,M),k=Ae}z="",U=Zi}}else z+=P[U];return E.child},"parseXml");function H(P,E,k){let z=this.options.updateTag(E.tagname,k,E[":@"]);z===!1||(typeof z=="string"&&(E.tagname=z),P.addChild(E))}i(H,"addChild"),r(H,"addChild");var ge=r(function(P){if(this.options.processEntities){for(let E in this.docTypeEntities){let k=this.docTypeEntities[E];P=P.replace(k.regx,k.val)}for(let E in this.lastEntities){let k=this.lastEntities[E];P=P.replace(k.regex,k.val)}if(this.options.htmlEntities)for(let E in this.htmlEntities){let k=this.htmlEntities[E];P=P.replace(k.regex,k.val)}P=P.replace(this.ampEntity.regex,this.ampEntity.val)}return P},"replaceEntitiesValue");function X(P,E,k,z){return P&&(z===void 0&&(z=Object.keys(E.child).length===0),P=this.parseTextData(P,E.tagname,k,!1,E[":@"]?Object.keys(E[":@"]).length!==0:!1,z),P!==void 0&&P!==""&&E.add(this.options.textNodeName,P),P=""),P}i(X,"saveTextToParentTag"),r(X,"saveTextToParentTag");function ne(P,E,k){let z="*."+k;for(let M in P){let U=P[M];if(z===U||E===U)return!0}return!1}i(ne,"isItStopNode"),r(ne,"isItStopNode");function Se(P,E,k=">"){let z,M="";for(let U=E;U<P.length;U++){let re=P[U];if(z)re===z&&(z="");else if(re==='"'||re==="'")z=re;else if(re===k[0])if(k[1]){if(P[U+1]===k[1])return{data:M,index:U}}else return{data:M,index:U};else re===" "&&(re=" ");M+=re}}i(Se,"tagExpWithClosingIndex"),r(Se,"tagExpWithClosingIndex");function w(P,E,k,z){let M=P.indexOf(E,k);if(M===-1)throw new Error(z);return M+E.length-1}i(w,"findClosingIndex"),r(w,"findClosingIndex");function _(P,E,k,z=">"){let M=Se(P,E+1,z);if(!M)return;let U=M.data,re=M.index,B=U.search(/\s/),q=U,de=!0;B!==-1&&(q=U.substring(0,B),U=U.substring(B+1).trimStart());let ie=q;if(k){let _e=q.indexOf(":");_e!==-1&&(q=q.substr(_e+1),de=q!==M.data.substr(_e+1))}return{tagName:q,tagExp:U,closeIndex:re,attrExpPresent:de,rawTagName:ie}}i(_,"readTagExp"),r(_,"readTagExp");function G(P,E,k){let z=k,M=1;for(;k<P.length;k++)if(P[k]==="<")if(P[k+1]==="/"){let U=w(P,">",k,`${E} is not closed`);if(P.substring(k+2,U).trim()===E&&(M--,M===0))return{tagContent:P.substring(z,k),i:U};k=U}else if(P[k+1]==="?")k=w(P,"?>",k+1,"StopNode is not closed.");else if(P.substr(k+1,3)==="!--")k=w(P,"-->",k+3,"StopNode is not closed.");else if(P.substr(k+1,2)==="![")k=w(P,"]]>",k,"StopNode is not closed.")-2;else{let U=_(P,k,">");U&&((U&&U.tagName)===E&&U.tagExp[U.tagExp.length-1]!=="/"&&M++,k=U.closeIndex)}}i(G,"readStopNodeData"),r(G,"readStopNodeData");function fe(P,E,k){if(E&&typeof P=="string"){let z=P.trim();return z==="true"?!0:z==="false"?!1:N(P,k)}else return D.isExist(P)?P:""}i(fe,"parseValue"),r(fe,"parseValue"),I.exports=j}}),p=o({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(b){"use strict";function I(j,T){return D(j,T)}i(I,"prettify"),r(I,"prettify");function D(j,T,Z){let V,W={};for(let S=0;S<j.length;S++){let O=j[S],H=A(O),ge="";if(Z===void 0?ge=H:ge=Z+"."+H,H===T.textNodeName)V===void 0?V=O[H]:V+=""+O[H];else{if(H===void 0)continue;if(O[H]){let X=D(O[H],T,ge),ne=N(X,T);O[":@"]?$(X,O[":@"],ge,T):Object.keys(X).length===1&&X[T.textNodeName]!==void 0&&!T.alwaysCreateTextNode?X=X[T.textNodeName]:Object.keys(X).length===0&&(T.alwaysCreateTextNode?X[T.textNodeName]="":X=""),W[H]!==void 0&&W.hasOwnProperty(H)?(Array.isArray(W[H])||(W[H]=[W[H]]),W[H].push(X)):T.isArray(H,ge,ne)?W[H]=[X]:W[H]=X}}}return typeof V=="string"?V.length>0&&(W[T.textNodeName]=V):V!==void 0&&(W[T.textNodeName]=V),W}i(D,"compress"),r(D,"compress");function A(j){let T=Object.keys(j);for(let Z=0;Z<T.length;Z++){let V=T[Z];if(V!==":@")return V}}i(A,"propName"),r(A,"propName");function $(j,T,Z,V){if(T){let W=Object.keys(T),S=W.length;for(let O=0;O<S;O++){let H=W[O];V.isArray(H,Z+"."+H,!0,!0)?j[H]=[T[H]]:j[H]=T[H]}}}i($,"assignAttributes"),r($,"assignAttributes");function N(j,T){let{textNodeName:Z}=T,V=Object.keys(j).length;return!!(V===0||V===1&&(j[Z]||typeof j[Z]=="boolean"||j[Z]===0))}i(N,"isLeafTag"),r(N,"isLeafTag"),b.prettify=I}}),g=o({"node_modules/fast-xml-parser/src/validator.js"(b){"use strict";var I=a(),D={allowBooleanAttributes:!1,unpairedTags:[]};b.validate=function(w,_){_=Object.assign({},D,_);let G=[],fe=!1,P=!1;w[0]==="\uFEFF"&&(w=w.substr(1));for(let E=0;E<w.length;E++)if(w[E]==="<"&&w[E+1]==="?"){if(E+=2,E=$(w,E),E.err)return E}else if(w[E]==="<"){let k=E;if(E++,w[E]==="!"){E=N(w,E);continue}else{let z=!1;w[E]==="/"&&(z=!0,E++);let M="";for(;E<w.length&&w[E]!==">"&&w[E]!==" "&&w[E]!==" "&&w[E]!==`
74
- `&&w[E]!=="\r";E++)M+=w[E];if(M=M.trim(),M[M.length-1]==="/"&&(M=M.substring(0,M.length-1),E--),!X(M)){let B;return M.trim().length===0?B="Invalid space after '<'.":B="Tag '"+M+"' is an invalid name.",H("InvalidTag",B,ne(w,E))}let U=Z(w,E);if(U===!1)return H("InvalidAttr","Attributes for '"+M+"' have open quote.",ne(w,E));let re=U.value;if(E=U.index,re[re.length-1]==="/"){let B=E-re.length;re=re.substring(0,re.length-1);let q=W(re,_);if(q===!0)fe=!0;else return H(q.err.code,q.err.msg,ne(w,B+q.err.line))}else if(z)if(U.tagClosed){if(re.trim().length>0)return H("InvalidTag","Closing tag '"+M+"' can't have attributes or invalid starting.",ne(w,k));{let B=G.pop();if(M!==B.tagName){let q=ne(w,B.tagStartPos);return H("InvalidTag","Expected closing tag '"+B.tagName+"' (opened in line "+q.line+", col "+q.col+") instead of closing tag '"+M+"'.",ne(w,k))}G.length==0&&(P=!0)}}else return H("InvalidTag","Closing tag '"+M+"' doesn't have proper closing.",ne(w,E));else{let B=W(re,_);if(B!==!0)return H(B.err.code,B.err.msg,ne(w,E-re.length+B.err.line));if(P===!0)return H("InvalidXml","Multiple possible root nodes found.",ne(w,E));_.unpairedTags.indexOf(M)!==-1||G.push({tagName:M,tagStartPos:k}),fe=!0}for(E++;E<w.length;E++)if(w[E]==="<")if(w[E+1]==="!"){E++,E=N(w,E);continue}else if(w[E+1]==="?"){if(E=$(w,++E),E.err)return E}else break;else if(w[E]==="&"){let B=O(w,E);if(B==-1)return H("InvalidChar","char '&' is not expected.",ne(w,E));E=B}else if(P===!0&&!A(w[E]))return H("InvalidXml","Extra text at the end",ne(w,E));w[E]==="<"&&E--}}else{if(A(w[E]))continue;return H("InvalidChar","char '"+w[E]+"' is not expected.",ne(w,E))}if(fe){if(G.length==1)return H("InvalidTag","Unclosed tag '"+G[0].tagName+"'.",ne(w,G[0].tagStartPos));if(G.length>0)return H("InvalidXml","Invalid '"+JSON.stringify(G.map(E=>E.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return H("InvalidXml","Start tag expected.",1);return!0};function A(w){return w===" "||w===" "||w===`
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(fp,"validateComputedSignature");function hp(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(hp,"parseHeader");function yp(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(yp,"secureCompare");async function bp(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(bp,"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 f(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let s=i((c,l,d)=>{let p=n[c],g=r?`${r}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new f(`Value of '${g}' 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 f(`Value of '${g}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new f(`Value of '${g}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new f(`Value of '${g}' 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 f(`Value of '${g}' 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),y("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 Ba(o,r,this.options.signingSecret)}catch(o){let s=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a,s.startsWith("No signatures found matching the expected signature for payload")&&(s="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",s),x.badRequest(e,t,{title:"Webhook Error",detail:s})}return e}};function Ga(n){return n!==null&&typeof n=="object"&&"id"in n&&Oe(n.id)&&"type"in n&&Oe(n.type)}i(Ga,"isStripeWebhookEvent");var wp={getSubscription:i(async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving subscription from Stripe API.";throw t.error(s,o),new L(s)}return o},"getSubscription"),getCustomer:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer from Stripe API.";throw t.error(s,o),new L(s)}return o},"getCustomer"),getUpcomingInvoice:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(s,o),new L(s)}return o},"getUpcomingInvoice")},ur=wp;var li="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Va="My API Key";async function Wa({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=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:Va,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)}),g=await p.json();if(p.status!==200){let h="Error creating API Key Consumer";throw a.log.error(h,g),new L(h)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(Wa,"createConsumer");async function Ka({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:Va,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 g="Error creating API Key Consumer";throw s.log.error(g,p),new L(g)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(Ka,"createConsumerInvite");async function Ja({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 L(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(Ja,"deleteConsumer");async function Qa({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:r,meteringBucketId:o,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[t],customerKey:r,customerExternalId:a,metadata:c,trialEndDate:l?l.trialEndDate:void 0,trialStartDate:l?l.trialStartDate:void 0,trialEndStatus:l?l.trialEndStatus:void 0},{authApiJWT:p,meteringServiceUrl:g}=m.instance;if(!It(p))throw new Q("No Zuplo JWT token set.");let h=await be({retryDelayMs:5,retries:2,logger:te.getLogger(n)},`${g}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!h.ok){let v=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,b,I="";try{b=await h.json(),I=b.detail??b.title}catch{b={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:h.status,detail:h.statusText}}throw n.log.error(v,b),new L(`${v} ${I}`)}n.log.info("Successfully created monetization subscription.",d)}i(Qa,"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 L(`${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 L(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(c),new L(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(c),new L(c)}return u.data[0]}i(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.`),x.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.`),x.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}'`),x.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}'.`),x.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 Wa({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.`),x.ok(n,e,{title:ae,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Ka({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}}catch(p){return e.log.warn(`Failed to create API Key Consumer. Error: ${p.message}`),x.ok(n,e,{title:ae,detail:p.message})}if(!c)return x.ok(n,e,{title:ae,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=cr(t.data.object.status),g;l&&d&&(g={subscriber:{sub:d,email:l}});let h;t.data.object.trial_end!==null&&t.data.object.trial_start!==null&&t.data.object.trial_settings&&t.data.object.trial_settings.end_behavior&&(t.data.object.trial_settings.end_behavior.missing_payment_method==="cancel"||t.data.object.trial_settings.end_behavior.missing_payment_method==="pause")&&(h={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:gt(t.data.object.trial_end),trialStartDate:gt(t.data.object.trial_start)}),await Qa({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:g,trial:h})}catch(p){return await Ja({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),x.ok(n,e,{title:ae,detail:p.message})}return x.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.`),x.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}'`),x.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}'.`),x.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 x.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 x.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.`),x.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}'`),x.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}'.`),x.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 x.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 x.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(g=>g.proration&&g.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 x.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 x.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 x.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 x.ok(n,e,{title:nt})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),x.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;y("monetization.stripe")}static{i(this,"StripeMonetizationPlugin")}registerRoutes(t,r){let o=i(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(Ee.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Ee.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new f("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 f("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 g=this.options.primaryDataRegion??"us-central1";if(!Rp(g))throw new f(`StripeMonetizationPlugin - The value '${g}' on the property 'primaryDataRegion' is invalid.`);let h=await c.json();if(!Ga(h))return x.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 '${h.type}' with ID '${h.id}'.`),h.type){case"customer.subscription.created":return await di(c,l,h,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:g,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await mi(c,l,h,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:g,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await pi(c,l,h,{meteringBucketId:d});default:return x.ok(c,l,{title:ae,detail:`Event '${h.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+xe})}},"stripeWebhookHandler"),s=ea({inboundPolicies:[new 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 Rp(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}i(Rp,"isMetricsRegion");var Xa=new WeakMap,Ya={},lr=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){Xa.set(e,t)}};async function eu(n,e,t,r){if(y("policy.inbound.amberflo-metering"),!t.statusCodes)throw new f(`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=Xa.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new L(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=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)},g=Ya[t.apiKey];if(!g){let h=t.apiKey,v=n.headers.get("zm-test-id")??"";g=new ee("amberflo-ingest-meter",10,async b=>{try{let I=t.url??"https://app.amberflo.io/ingest",D=await F.fetch(I,{method:"POST",body:JSON.stringify(b),headers:{"content-type":"application/json","x-api-key":h,"zm-test-id":v}});D.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${D.status}: ${await D.text()}`)}catch(I){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${I.message}`),I}}),Ya[h]=g}g.enqueue(p),e.waitUntil(g.waitUntilFlushed())}}),n}i(eu,"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 tu=new Map;async function ce(n,e,t){let r,o=`${n}-${e}`,s=tu.get(o);return s!==void 0?r=s:(r=`zuplo-policy-${await ft(JSON.stringify({policyName:n,options:t}))}`,tu.set(n,r)),r}i(ce,"getPolicyCacheName");var nu="key-metadata-cache-type";function Pp(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}i(Pp,"getKeyValue");async function dr(n,e,t,r){if(y("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 f(`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 f(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let s=i(I=>o.allowUnauthenticatedRequests?n:x.unauthorized(n,e,{detail:I}),"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=Pp(a,o);if(!u||u==="")return s("No key present");let c=await Ip(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!==nu&&te.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let g={key:u},h=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(g)});if(h.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(h.status!==200){try{let I=await h.text(),D=JSON.parse(I);e.log.error("Unexpected response from key service",D)}catch{e.log.error("Invalid response from key service")}throw new L(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${h.status}`)}let v=await h.json(),b={isValid:!0,typeId:nu,user:{sub:v.name,data:v.metadata}};return n.user=b.user,d.put(c,b,o.cacheTtlSeconds),n}i(dr,"ApiKeyInboundPolicy");async function Ip(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(Ip,"hashValue");var ru=dr;var ln=require("jose");var ou=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,ou.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 iu(n,e,t){let r=new fi(n,e,t);return async(o,s)=>r.getKey(o,s)}i(iu,"createRemoteJWKSet");var kt=class extends L{static{i(this,"JWKSError")}},hi=class extends kt{static{i(this,"JWKSNoMatchingKey")}},yi=class extends kt{static{i(this,"JWKSTimeout")}};var pr={},Ep=i((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new f("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]=iu(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"),Tp=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)=>{y("policy.inbound.open-id-jwt-auth");let o=n.headers.get("Authorization"),s="bearer ",a=i(g=>x.unauthorized(n,e,{detail:g}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=t.jwkUrl?Ep(r,e):Tp,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 g=o.substring(s.length);if(!g||g.length===0)return a("No bearer token on authorization header");try{return await u(g,t)}catch(h){let v=new URL(n.url);return"code"in h&&h.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${v.pathname} `,h):e.log.warn(`Invalid token on: ${n.method} ${v.pathname}`,h),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return t.allowUnauthenticatedRequests===!0?n:l;let d=t.subPropertyName??"sub",p=l[d];return p?(n.user={sub:p,data:l},n):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var su=i(async(n,e,t,r)=>(y("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),y("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:x.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),x.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 au=i(async(n,e,t)=>{y("policy.inbound.basic-auth");let r=n.headers.get("Authorization"),o="basic ",s=i(l=>x.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!r)return await s("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await s("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let g=d.substring(0,p),h=d.substring(p+1),v=t.accounts.find(b=>b.username===g&&b.password===h);return v||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 uu(n,e){return new Date(n,e+1,0).getDate()}i(uu,"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=uu(t,r),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return o>s?e==="next"?void 0:s:o;let c;a&&(c=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),c!==void 0&&c>s&&(c=void 0));let l;if(u){let d=new Date(t,r,o).getDay(),p=e==="next"?this.weekdays.find(g=>g>=d)??this.weekdays[0]:this.reversed.weekdays.find(g=>g<=d)??this.reversed.weekdays[0];if(p!==void 0){let g=e==="next"?bi(d,p):bi(p,d);l=e==="next"?o+g:o-g,(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 g=this.findAllowedTime("next",t);if(g!==void 0)return new Date(u,c,d,g.hour,g.minute,g.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 g=this.findAllowedTime("prev",t);if(g!==void 0)return new Date(u,c,d,g.hour,g.minute,g.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 xp={min:0,max:59},Op={min:0,max:59},vp={min:0,max:23},Cp={min:1,max:31},Sp={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"}},Ap={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},_p={"@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(g=>t.add(g))}),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=_p[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,xp),minutes:ht(r,Op),hours:ht(o,vp),days:ht(s,Cp),months:new Set(Array.from(ht(a,Sp)).map(c=>c-1)),weekdays:new Set(Array.from(ht(u,Ap)).map(c=>c%7))})}i(wi,"parseCronExpression");var yr=class extends le{static{i(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),y("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 f(`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=x.getProblemFromStatus(this.options.problem?.status??400,{detail:"This API is performing a scheduled brownout in advance of its pending deprecation. Please upgrade to a later version.",...this.options.problem});return x.format(s,e,t)}return e}};var Lp=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function kp(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(kp,"digestMessage");var Np=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 kp(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 cu(n,e,t,r){y("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 Np(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 g=t?.expirationSecondsTtl??60,h=new Response(p.body,p);Lp.forEach(v=>h.headers.delete(v)),h.headers.set("cache-control",`s-maxage=${g}`),e.waitUntil(s.put(u,h))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}i(cu,"CachingInboundPolicy");var lu=i(async(n,e,t,r)=>{if(y("policy.inbound.change-method"),!t.method)throw new f(`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 Dp(n,e){if(Ws(n))throw new Ri(e)}i(Dp,"throwIfUndefinedOrNull");function du(n,e){if(Dp(n,e),!Oe(n))throw new Pi(e,"string")}i(du,"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}){du(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),y("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=Mp(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=Up(l.key,this.policyName);r&&t.log.debug(`QuotaInboundPolicy: key - '${d}'`);let p=ot(this.policyName,o),g=await p.getQuota(d,t.requestId);r&&t.log.debug("QuotaInboundPolicy: quotaResult",g),c&&new Date(g.anchorDate)!==c&&t.log.warn(`QuotaInboundPolicy '${this.policyName}' provided anchorDate ('${c}') did not match the stored, immutable anchorDate ('${g.anchorDate}')`);let h=Object.assign({},s.defaultAllowances);Object.assign(h,l.allowances);let v=[],b="";if(Object.entries(h).forEach(([I,D])=>{r&&(b+=`${I} - allowed: ${D} value: ${g.meters[I]??0}
72
+ `),(g.meters[I]??0)>=D&&v.push(I)}),r&&t.log.debug("QuotaInboundPolicy: debugTable",b),v.length>0)return x.tooManyRequests(e,t,{detail:`Quota exceeded for meters '${v.join(", ")}'`});t.addResponseSendingFinalHook(async(I,D,A)=>{if(r&&A.log.debug(`QuotaInboundPolicy: backend response - ${I.status}: ${I.statusText}`),!s.quotaOnStatusCodes.includes(I.status))return;let $=ue.get(A,Ti),N={config:{period:s.period,anchorDate:c?.toISOString()??""},increments:$};r&&A.log.debug("QuotaInboundPolicy: setQuotaDetails",N);let j=p.setQuota(d,N,A.requestId);A.waitUntil(j)})}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 Mp(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 f(`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 f(`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(Mp,"validateAndParseOptions");function Up(n,e){return encodeURIComponent(`${e}-${n}`)}i(Up,"processKey");var pu=i(async(n,e,t)=>{y("policy.inbound.clear-headers");let r=[...t.exclude??[]],o=new Headers;return r.forEach(a=>{let u=n.headers.get(a);u&&o.set(a,u)}),new oe(n,{headers:o})},"ClearHeadersInboundPolicy");var mu=i(async(n,e,t,r)=>{y("policy.outbound.clear-headers");let o=[...r.exclude??[]],s=new Headers;return o.forEach(u=>{let c=n.headers.get(u);c&&s.set(u,c)}),new Response(n.body,{headers:s,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var gu=i(async(n,e,t,r)=>{y("policy.inbound.clerk-jwt-auth");let o=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),s=new URL(o);return s.pathname="/.well-known/jwks.json",we(n,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var fu=i(async(n,e,t,r)=>{if(y("policy.inbound.cognito-jwt-auth"),!t.userPoolId)throw new f("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new f("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 yu=Be(He());var qp=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:$p(e,"RateLimitInboundPolicy",n),user:Hp,ip:Zp,all:Fp}[e.rateLimitBy??"ip"]}i(Nt,"getRateLimitByFunctions");var Zp=i(async n=>({key:`ip-${qp(n)}`}),"getIP"),Hp=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),Fp=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll");function $p(n,e,t){let r;if(n.rateLimitBy==="function"){if(!n.identifier)throw new f(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new f(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new f(`${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 f(`${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(l)}if(!("key"in c)){let l=`${e} '${u}' - Custom rate limit function must return a valid key property.`;throw a.log.error(l,c),new L(l)}if(typeof c.key!="string"){let l=`${e} '${u}' - Custom rate limit function must return a valid key property of type string. Received type '${typeof c.key}'`;throw a.log.error(l),new L(l)}return c},"outerFunction")}i($p,"wrapUserFunction");var Dt="Retry-After";var hu=(0,yu.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),y("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 f(`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()),x.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),g=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;t.addResponseSendingFinalHook(async()=>{try{let I=n.getIncrements(t);hu(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(I)}`);let D=Object.entries(p).map(([$])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${$}`,ttlSeconds:g,increment:I[$]??0})),A=s.multiIncrement(D,t.requestId);t.waitUntil(A),await A}catch(I){o.error(I),t.log.error(I)}});let h=Object.entries(p).map(([I,D])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${I}`,ttlSeconds:g,limit:D})),v=await s.multiCount(h,t.requestId);return jp(v,h).length>0?u(this.options.headerMode??"retry-after",g):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-r;hu(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function jp(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(jp,"findOverLimits");var bu=i(async(n,e,t,r)=>{if(y("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new f(`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 wu=i(async(n,e,t,r)=>{y("policy.inbound.curity-phantom-token-auth");let o=n.headers.get("Authorization");if(!o)return x.unauthorized(n,e,{detail:"No authorization header"});let s=zp(o);if(!s)return x.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}'`),x.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):x.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function zp(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(zp,"getToken");var Ru=i(async(n,e,t,r)=>(y("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 Pu=i(async(n,e,t)=>{y("policy.inbound.form-data-to-json");let r="application/x-www-form-urlencoded",o="multipart/form-data",s=n.headers.get("content-type")?.toLowerCase();if(!s||![o,r].includes(s))return t&&t.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):n;let a=await n.formData();if(t&&t.optionalHoneypotName&&a.get(t.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(n.headers);return c.set("content-type","application/json"),c.delete("content-length"),new oe(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var Mt="__unknown__",Iu=i(async(n,e,t,r)=>{y("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,g=o.allow.regionCodes,h=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||g.length>0&&!g.includes(a)&&!l||h.length>0&&!h.includes(u)&&!d)return Ut(n,e,r,s,a,u);let v=o.block.countries,b=o.block.regionCodes,I=o.block.asns;return v.length>0&&v.includes(s)&&!c||b.length>0&&b.includes(a)&&!l||I.length>0&&I.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}')`),x.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 f(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}i(qt,"toLowerStringArray");var Eu=i(async(n,e,t)=>{y("policy.inbound.jwt-scope-validation");let r=n.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(r,t.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var xu=i(async(n,e,t,r)=>{y("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(g=>{a.push({responseName:u,contentName:l,exampleName:g,exampleValue:d[g]})})})}),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 Tu(a[u])}else return a.length>0?Tu(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 Tu(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(Tu,"generateResponse");var Oi=i((n,e,t,r)=>{let o=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${r}`;return x.internalServerError(e,t,{detail:o})},"getProblemDetailResponse");var Bp="Incoming",Gp={logRequestBody:!0,logResponseBody:!0};function Ou(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}i(Ou,"headersToObject");function vu(){return new Date().toISOString()}i(vu,"timestamp");var vi=new WeakMap,Vp={};function Au(n,e){let t=vi.get(n);t||(t=Vp);let r=Object.assign({...t},e);vi.set(n,r)}i(Au,"setMoesifContext");async function Cu(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(Cu,"readBody");var Wp={},Ci;function Su(){if(!Ci)throw new L("Invalid State - no _lastLogger");return Ci}i(Su,"getLastLogger");function Kp(n){let e=Wp[n];return e||(e=new ee("moesif-inbound",100,async t=>{let r=JSON.stringify(t);Su().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||Su().error({status:o.status,body:await o.text()})})),e}i(Kp,"getDispatcher");async function _u(n,e,t,r){y("policy.inbound.moesif-analytics"),Ci=e.log;let o=vu(),s=Object.assign(Gp,t);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await Cu(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Kp(s.applicationId),d=n.headers.get("true-client-ip"),p=vi.get(e)??{},g={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Ou(n.headers)},h=s.logResponseBody?await Cu(u,e):void 0,v={time:vu(),status:u.status,headers:Ou(u.headers),body:h},b={request:g,response:v,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Bp};l.enqueue(b),e.waitUntil(l.waitUntilFlushed())}),n}i(_u,"MoesifInboundPolicy");async function Lu(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(Lu,"loadSubscription");async function ku(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(ku,"consumeSubcriptionQuotas");var Jp=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 f(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 f?new f(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}i(Pr,"validateMeters");function Nu(n,e){if(n)try{if(n.length===0)throw new f("Must set valid subscription statuses");let t=pt(n),r=[];for(let o of t)Jp.has(o)||r.push(o);if(r.length>0)throw new f(`Found the following invalid statuses: ${r.join(", ")}`);return n}catch(t){throw t instanceof f?new f(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}i(Nu,"parseAllowedSubscriptionStatuses");function Du(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(Du,"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),y("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=Nu(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(b,I,D)=>{let A=ue.get(D,Vt);if((this.options.allowRequestsWithoutSubscription??!1)&&!A){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 f(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let N=ue.get(D,Wt),j={...this.options.meters,...N};if(Pr(j,this.policyName),o.includes(b.status)&&A&&j){D.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${A.id}' with meters '${JSON.stringify(j)} on response status '${b.status}'`);let{metersInSubscription:T,metersNotInSubscription:Z}=Du(A.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 ku(D,A.id,this.policyName,this.options.bucketId,T)}});let l=e.user;if(!l)return u?e:x.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(Ee.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Ee.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new f(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await Lu(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:x.unauthorized(e,t,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return t.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),x.unauthorized(e,t,{detail:"No valid subscription found"});c.includes(p.status)&&(t.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),ue.set(t,Vt,p));let g=ue.get(t,Vt);if(!g)return u?e:(t.log.warn("Subscription is not available for user"),x.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(g&&Object.keys(g.meters).length===0)return t.log.error(`Quota is not set up for subscription '${g.id}'`),x.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let v=Object.keys(a).filter(b=>!Object.keys(g.meters).includes(b));if(v.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${v.join(", ")}`),x.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${v.join(", ")}`,title:"Quota Exceeded"});for(let b of Object.keys(a))if(g.meters[b].available<=0&&!r)return x.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${b}'`,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 L("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 L("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 Mu="X-OpenFGA-Client-Method",Uu="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,Mu,"BatchCheck"),dn(r,Uu,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,Mu,"ListRelations"),dn(c,Uu,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 qu=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,qu,r)}constructor(e,t){if(super(e,t),Y(e,t).required("apiUrl","string").optional("storeId","string").optional("authorizationModelId","string"),!e.credentials)throw new f(`${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 f(`${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:x.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=ue.get(t,qu);if(!o||o.length===0)throw new L(`${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),x.internalServerError(e,t)}}getAuthorizer(e){if(e.method==="none")return async()=>({});if(e.method==="header")return async t=>{let r=e.headerName??"Authorization",o=t.headers.get(r);if(!o)throw new 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 L("Invalid state for credentials method is not valid. This should not happen.")}};var Zu=["us1","eu1","au1"],xr=class extends Ht{static{i(this,"OktaFGAAuthZInboundPolicy")}constructor(e,t){if(!Zu.includes(e.region))throw new f(`OktaFGAAuthZInboundPolicy '${t}' - The 'region' option is invalid. Must be one of ${Zu.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),y("policy.inbound.oktafga-authz")}};var Hu=i(async(n,e,t,r)=>(y("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),y("policy.inbound.openfga-authz")}};var Fu=require("jose");var Si,$u=i(async(n,e,t,r)=>{if(y("policy.inbound.propel-auth-jwt-auth"),!Si)try{Si=await(0,Fu.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 Vu=Be(He());var zu=Be(He());var ju=(0,zu.debug)("zuplo:policies:RateLimitInboundPolicy"),Bu=i(async(n,e,t,r)=>{let o=te.getLogger(e),s=i((j,T)=>{let Z={};return(!j||j==="retry-after")&&(Z[Dt]=T.toString()),x.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",g=ot(r,o),v=`rate-limit${m.instance.isTestMode?m.instance.build.BUILD_ID:""}/${r}/${c}`,b=await ce(r,void 0,t),I=new se(b,e),D=g.getCountAndUpdateExpiry(v,d,e.requestId),A;i(async()=>{let j=await D;if(j.count>l){let T=Date.now()+j.ttlSeconds*1e3;I.put(v,T,j.ttlSeconds),ju(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${v}' (async mode)`),A=s(p,j.ttlSeconds)}},"asyncCheck")();let N=await I.get(v);if(N!==void 0&&N>Date.now()){ju(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${v}' (async mode)`);let j=Math.round((N-Date.now())/1e3);return s(p,j)}return e.addResponseSendingHook(async j=>A??j),n},"AsyncRateLimitInboundPolicyImpl");var Gu=(0,Vu.debug)("zuplo:policies:RateLimitInboundPolicy"),Qp="strict",Ai=i(async(n,e,t,r)=>{if(y("policy.inbound.rate-limit"),(t.mode??Qp)==="async")return Bu(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()),x.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await Nt(r,t)(n,e,r),p=d.key,g=d.requestsAllowed??t.requestsAllowed,h=d.timeWindowMinutes??t.timeWindowMinutes,v=t.headerMode??"retry-after",b=ot(r,a),D=`rate-limit${m.instance.isTestMode||m.instance.isWorkingCopy?m.instance.build.BUILD_ID:""}/${r}/${p}`,A=await b.getCountAndUpdateExpiry(D,h,e.requestId);return A.count>g?(Gu(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${D}' (strict mode)`),c(v,A.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-s;Gu(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var _i;function Wu(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}i(Wu,"headersToNameValuePairs");function Yp(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}i(Yp,"queryToNameValueParis");function Xp(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}i(Xp,"parseIntOrUndefined");var Ku={};async function Ju(n,e,t,r){y("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:Wu(n.headers),queryString:Yp(n.query)},response:{status:a.status,statusText:a.statusText,headers:Wu(a.headers),content:{size:Xp(n.headers.get("content-length"))}}}]}}},d=Ku[t.apiKey];if(!d){let p=t.apiKey;d=new ee("readme-metering-inbound-policy",10,async g=>{try{let h=t.url??"https://metrics.readme.io/request",v=await F.fetch(h,{method:"POST",body:JSON.stringify(g),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});v.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${v.status}: '${await v.text()}'`)}catch(h){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${h.message}'`),h}}),Ku[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}i(Ju,"ReadmeMetricsInboundPolicy");var Qu=i(async(n,e,t,r)=>{y("policy.inbound.remove-headers");let o=t?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new f(`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)=>{y("policy.outbound.remove-headers");let s=r?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new f(`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)=>{y("policy.inbound.remove-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length===0)throw new f(`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 ec=i(async(n,e,t,r)=>{y("policy.outbound.replace-string");let o=await n.text(),s=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(s,r.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var tc=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),nc=i(async(n,e,t)=>{y("policy.inbound.request-size-limit");let r=t.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(n.method))return n;let o=n.headers.get("content-length"),s=o!==null?parseInt(o):void 0;return s&&!isNaN(s)&&s>t.maxSizeInBytes?tc():s&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?tc():n},"RequestSizeLimitInboundPolicy");function rc(n,e,t){return`_${it(n+"_"+e+"_"+t)}`}i(rc,"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 oc(n,e){return`_${it(n)}__${it(e)}`}i(oc,"getIdForRefSchema");function it(n){let e=[];for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122?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],g=p(e[c.name]),h=Li(p.errors);g||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${h.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),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 ic(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(h){let v=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,b=x.badRequest(e,n,{detail:`${v}, see errors property for more details`,errors:`${h}`});if(Ne(t.validateBody)&&ke(n,t.logLevel??"info",v,[r],h),De(t.validateBody))return b}if(!e.headers.get("Content-Type")){let h=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,v=x.badRequest(e,n,{detail:h});return Ne(t.validateBody)&&ke(n,t.logLevel??"info",h,[r],[h]),De(t.validateBody)?v: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 h=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,v=x.badRequest(e,n,{detail:h});return Ne(t.validateBody)&&ke(n,t.logLevel??"info",h,[r],[h]),De(t.validateBody)?v:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Li(l),g=x.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 g}i(ic,"handleBodyValidation");function sc(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=x.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(sc,"handleHeadersValidation");function ac(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=x.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(ac,"handlePathParameterValidation");function uc(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=x.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(uc,"handleQueryParameterValidation");var ki=i(async(n,e,t)=>{y("policy.inbound.request-validation");let r=uc(e,n,t);if(r!==void 0||(r=ac(e,n,t),r!==void 0)||(r=sc(e,n,t),r!==void 0))return r;let o=await ic(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),cc=ki;var lc=i(async(n,e,t,r)=>{if(y("policy.inbound.require-origin"),t.origins===void 0||t.origins.length===0)throw new f(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof t.origins=="string"?t.origins.split(","):t.origins;o=o.map(a=>a.trim());let s=n.headers.get("origin");if(!s||!o.includes(s)){let a=t.failureDetail??"Forbidden";return x.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var dc=i(async(n,e,t)=>(y("policy.inbound.set-body"),new oe(n,{body:t.body})),"SetBodyInboundPolicy");var pc=i(async(n,e,t,r)=>{y("policy.inbound.set-headers");let o=t.headers;if(!o||!Array.isArray(o)||o.length==0)throw new f(`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 f(`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 mc=i(async(n,e,t,r,o)=>{y("policy.outbound.set-headers");let s=r.headers;if(!s||!Array.isArray(s)||s.length==0)throw new f(`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 f(`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 gc=i(async(n,e,t,r)=>{y("policy.inbound.set-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length==0)throw new f(`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 f(`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 fc=i(async(n,e,t,r,o)=>{if(y("policy.outbound.set-status"),!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(n.body,{headers:n.headers,status:r.status,statusText:r.statusText??n.statusText})},"SetStatusOutboundPolicy");var em=i(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),hc=i(async(n,e,t,r)=>{if(y("policy.inbound.sleep"),!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new f(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await em(t.sleepInMs),n},"SleepInboundPolicy");var yc=i(async(n,e,t,r)=>{y("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 L(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?x.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var bc=i(async(n,e,t,r)=>{y("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 tm(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 tm(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 L("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new L("Response returned from Azure AD is not in the expected format.")}i(tm,"getAccessToken");var wc="https://accounts.google.com/o/oauth2/token",Ni,Rc=i(async(n,e,t,r)=>{y("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:wc,payload:o}),l=await qn(wc,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new L("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var nm="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",rm=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Di,Pc=i(async(n,e,t,r)=>{if(y("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 f(`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(rm.indexOf(p)!==-1)throw new f(`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 L("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new L(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=dt(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new L(`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:nm,payload:c}),g=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,h=await pa(g,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!h.idToken)throw new L("Invalid token response from Firebase");d=h.idToken,u.put(l,d,(h.expiresIn?parseInt(h.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var 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 L("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 Ic="workload-access-token",Ec="service-account-id-token",Sr=class extends le{static{i(this,"UpstreamGcpFederatedAuthInboundPolicy")}cacheName;normalizedWorkloadIdentityProvider;constructor(e,t){super(e,t),y("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(Ic);if(!o){let a=`https://iam.googleapis.com/${this.normalizedWorkloadIdentityProvider}`,u=await jt.getIDToken(t,{audience:a}),c=await la(this.normalizedWorkloadIdentityProvider,u,{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!c.access_token||!c.expires_in)throw new L("Invalid token response from GCP");o=c.access_token,r.put(Ic,o,c.expires_in-(this.options.expirationOffsetSeconds??300))}let s=await r.get(Ec);if(!s){let a=await da({serviceAccountEmailOrIdentifier:this.options.serviceAccountEmail,audience:this.options.audience,accessToken:o},{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!a.token)throw new L("Invalid token response from GCP");s=a.token,r.put(Ec,o,3600-(this.options.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${s}`),e}};var Mi,Tc=i(async(n,e,t,r)=>{y("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 xc="https://www.googleapis.com/oauth2/v4/token",Ui,Oc=i(async(n,e,t,r)=>{y("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 f("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 f?new f(`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:xc,payload:o}),l=await qn(xc,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new L("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new L("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var vc=i(async(n,e,t)=>{y("policy.inbound.validate-json-schema");let r=n.clone(),o;try{o=await r.json()}catch{return x.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator(o))return n;let{errors:a}=t.validator;if(!a)throw new 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 x.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var Cc=i(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=i((b,I)=>e(b,"name",{value:I,configurable:!0}),"__name"),o=i((b,I)=>i(function(){return I||(0,b[t(b)[0]])((I={exports:{}}).exports,I),I.exports},"__require"),"__commonJS"),s=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(b){var I={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:i(function(A,$){return $},"tagValueProcessor"),attributeValueProcessor:i(function(A,$){return $},"attributeValueProcessor"),stopNodes:[],alwaysCreateTextNode:!1,isArray:i(()=>!1,"isArray"),commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:i(function(A,$,N){return A},"updateTag")},D=r(function(A){return Object.assign({},I,A)},"buildOptions");b.buildOptions=D,b.defaultOptions=I}}),a=o({"node_modules/fast-xml-parser/src/util.js"(b){"use strict";var I=":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=I+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",A="["+I+"]["+D+"]*",$=new RegExp("^"+A+"$"),N=r(function(T,Z){let V=[],W=Z.exec(T);for(;W;){let S=[];S.startIndex=Z.lastIndex-W[0].length;let O=W.length;for(let H=0;H<O;H++)S.push(W[H]);V.push(S),W=Z.exec(T)}return V},"getAllMatches"),j=r(function(T){let Z=$.exec(T);return!(Z===null||typeof Z>"u")},"isName");b.isExist=function(T){return typeof T<"u"},b.isEmptyObject=function(T){return Object.keys(T).length===0},b.merge=function(T,Z,V){if(Z){let W=Object.keys(Z),S=W.length;for(let O=0;O<S;O++)V==="strict"?T[W[O]]=[Z[W[O]]]:T[W[O]]=Z[W[O]]}},b.getValue=function(T){return b.isExist(T)?T:""},b.isName=j,b.getAllMatches=N,b.nameRegexp=A}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(b,I){"use strict";var D=class{static{i(this,"XmlNode")}static{r(this,"XmlNode")}constructor(A){this.tagname=A,this.child=[],this[":@"]={}}add(A,$){A==="__proto__"&&(A="#__proto__"),this.child.push({[A]:$})}addChild(A){A.tagname==="__proto__"&&(A.tagname="#__proto__"),A[":@"]&&Object.keys(A[":@"]).length>0?this.child.push({[A.tagname]:A.child,":@":A[":@"]}):this.child.push({[A.tagname]:A.child})}};I.exports=D}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(b,I){var D=a();function A(S,O){let H={};if(S[O+3]==="O"&&S[O+4]==="C"&&S[O+5]==="T"&&S[O+6]==="Y"&&S[O+7]==="P"&&S[O+8]==="E"){O=O+9;let ge=1,X=!1,ne=!1,Se="";for(;O<S.length;O++)if(S[O]==="<"&&!ne){if(X&&j(S,O))O+=7,[entityName,val,O]=$(S,O+1),val.indexOf("&")===-1&&(H[W(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(X&&T(S,O))O+=8;else if(X&&Z(S,O))O+=8;else if(X&&V(S,O))O+=9;else if(N)ne=!0;else throw new Error("Invalid DOCTYPE");ge++,Se=""}else if(S[O]===">"){if(ne?S[O-1]==="-"&&S[O-2]==="-"&&(ne=!1,ge--):ge--,ge===0)break}else S[O]==="["?X=!0:Se+=S[O];if(ge!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:H,i:O}}i(A,"readDocType"),r(A,"readDocType");function $(S,O){let H="";for(;O<S.length&&S[O]!=="'"&&S[O]!=='"';O++)H+=S[O];if(H=H.trim(),H.indexOf(" ")!==-1)throw new Error("External entites are not supported");let ge=S[O++],X="";for(;O<S.length&&S[O]!==ge;O++)X+=S[O];return[H,X,O]}i($,"readEntityExp"),r($,"readEntityExp");function N(S,O){return S[O+1]==="!"&&S[O+2]==="-"&&S[O+3]==="-"}i(N,"isComment"),r(N,"isComment");function j(S,O){return S[O+1]==="!"&&S[O+2]==="E"&&S[O+3]==="N"&&S[O+4]==="T"&&S[O+5]==="I"&&S[O+6]==="T"&&S[O+7]==="Y"}i(j,"isEntity"),r(j,"isEntity");function T(S,O){return S[O+1]==="!"&&S[O+2]==="E"&&S[O+3]==="L"&&S[O+4]==="E"&&S[O+5]==="M"&&S[O+6]==="E"&&S[O+7]==="N"&&S[O+8]==="T"}i(T,"isElement"),r(T,"isElement");function Z(S,O){return S[O+1]==="!"&&S[O+2]==="A"&&S[O+3]==="T"&&S[O+4]==="T"&&S[O+5]==="L"&&S[O+6]==="I"&&S[O+7]==="S"&&S[O+8]==="T"}i(Z,"isAttlist"),r(Z,"isAttlist");function V(S,O){return S[O+1]==="!"&&S[O+2]==="N"&&S[O+3]==="O"&&S[O+4]==="T"&&S[O+5]==="A"&&S[O+6]==="T"&&S[O+7]==="I"&&S[O+8]==="O"&&S[O+9]==="N"}i(V,"isNotation"),r(V,"isNotation");function W(S){if(D.isName(S))return S;throw new Error(`Invalid entity name ${S}`)}i(W,"validateEntityName"),r(W,"validateEntityName"),I.exports=A}}),l=o({"../../node_modules/strnum/strnum.js"(b,I){var D=/^[-+]?0x[a-fA-F0-9]+$/,A=/^([\-\+])?(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 $={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function N(T,Z={}){if(Z=Object.assign({},$,Z),!T||typeof T!="string")return T;let V=T.trim();if(Z.skipLike!==void 0&&Z.skipLike.test(V))return T;if(Z.hex&&D.test(V))return Number.parseInt(V,16);{let W=A.exec(V);if(W){let S=W[1],O=W[2],H=j(W[3]),ge=W[4]||W[6];if(!Z.leadingZeros&&O.length>0&&S&&V[2]!==".")return T;if(!Z.leadingZeros&&O.length>0&&!S&&V[1]!==".")return T;{let X=Number(V),ne=""+X;return ne.search(/[eE]/)!==-1||ge?Z.eNotation?X:T:V.indexOf(".")!==-1?ne==="0"&&H===""||ne===H||S&&ne==="-"+H?X:T:O?H===ne||S+H===ne?X:T:V===ne||V===S+ne?X:T}}else return T}}i(N,"toNumber"),r(N,"toNumber");function j(T){return T&&T.indexOf(".")!==-1&&(T=T.replace(/0+$/,""),T==="."?T="0":T[0]==="."?T="0"+T:T[T.length-1]==="."&&(T=T.substr(0,T.length-1))),T}i(j,"trimZeros"),r(j,"trimZeros"),I.exports=N}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(b,I){"use strict";var D=a(),A=u(),$=c(),N=l(),j=class{static{i(this,"OrderedObjParser")}static{r(this,"OrderedObjParser")}constructor(P){this.options=P,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:i((E,k)=>String.fromCharCode(Number.parseInt(k,10)),"val")},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:i((E,k)=>String.fromCharCode(Number.parseInt(k,16)),"val")}},this.addExternalEntities=T,this.parseXml=O,this.parseTextData=Z,this.resolveNameSpace=V,this.buildAttributesMap=S,this.isItStopNode=ne,this.replaceEntitiesValue=ge,this.readStopNodeData=G,this.saveTextToParentTag=X,this.addChild=H}};function T(P){let E=Object.keys(P);for(let k=0;k<E.length;k++){let B=E[k];this.lastEntities[B]={regex:new RegExp("&"+B+";","g"),val:P[B]}}}i(T,"addExternalEntities"),r(T,"addExternalEntities");function Z(P,E,k,B,M,U,re){if(P!==void 0&&(this.options.trimValues&&!B&&(P=P.trim()),P.length>0)){re||(P=this.replaceEntitiesValue(P));let z=this.options.tagValueProcessor(E,P,k,M,U);return z==null?P:typeof z!=typeof P||z!==P?z:this.options.trimValues?fe(P,this.options.parseTagValue,this.options.numberParseOptions):P.trim()===P?fe(P,this.options.parseTagValue,this.options.numberParseOptions):P}}i(Z,"parseTextData"),r(Z,"parseTextData");function V(P){if(this.options.removeNSPrefix){let E=P.split(":"),k=P.charAt(0)==="/"?"/":"";if(E[0]==="xmlns")return"";E.length===2&&(P=k+E[1])}return P}i(V,"resolveNameSpace"),r(V,"resolveNameSpace");var W=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function S(P,E,k){if(!this.options.ignoreAttributes&&typeof P=="string"){let B=D.getAllMatches(P,W),M=B.length,U={};for(let re=0;re<M;re++){let z=this.resolveNameSpace(B[re][1]),q=B[re][4],de=this.options.attributeNamePrefix+z;if(z.length)if(this.options.transformAttributeName&&(de=this.options.transformAttributeName(de)),de==="__proto__"&&(de="#__proto__"),q!==void 0){this.options.trimValues&&(q=q.trim()),q=this.replaceEntitiesValue(q);let ie=this.options.attributeValueProcessor(z,q,E);ie==null?U[de]=q:typeof ie!=typeof q||ie!==q?U[de]=ie:U[de]=fe(q,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(U[de]=!0)}if(!Object.keys(U).length)return;if(this.options.attributesGroupName){let re={};return re[this.options.attributesGroupName]=U,re}return U}}i(S,"buildAttributesMap"),r(S,"buildAttributesMap");var O=r(function(P){P=P.replace(/\r\n?/g,`
73
+ `);let E=new A("!xml"),k=E,B="",M="";for(let U=0;U<P.length;U++)if(P[U]==="<")if(P[U+1]==="/"){let z=w(P,">",U,"Closing Tag is not closed."),q=P.substring(U+2,z).trim();if(this.options.removeNSPrefix){let _e=q.indexOf(":");_e!==-1&&(q=q.substr(_e+1))}this.options.transformTagName&&(q=this.options.transformTagName(q)),k&&(B=this.saveTextToParentTag(B,k,M));let de=M.substring(M.lastIndexOf(".")+1);if(q&&this.options.unpairedTags.indexOf(q)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${q}>`);let ie=0;de&&this.options.unpairedTags.indexOf(de)!==-1?(ie=M.lastIndexOf(".",M.lastIndexOf(".")-1),this.tagsNodeStack.pop()):ie=M.lastIndexOf("."),M=M.substring(0,ie),k=this.tagsNodeStack.pop(),B="",U=z}else if(P[U+1]==="?"){let z=_(P,U,!1,"?>");if(!z)throw new Error("Pi Tag is not closed.");if(B=this.saveTextToParentTag(B,k,M),!(this.options.ignoreDeclaration&&z.tagName==="?xml"||this.options.ignorePiTags)){let q=new A(z.tagName);q.add(this.options.textNodeName,""),z.tagName!==z.tagExp&&z.attrExpPresent&&(q[":@"]=this.buildAttributesMap(z.tagExp,M,z.tagName)),this.addChild(k,q,M)}U=z.closeIndex+1}else if(P.substr(U+1,3)==="!--"){let z=w(P,"-->",U+4,"Comment is not closed.");if(this.options.commentPropName){let q=P.substring(U+4,z-2);B=this.saveTextToParentTag(B,k,M),k.add(this.options.commentPropName,[{[this.options.textNodeName]:q}])}U=z}else if(P.substr(U+1,2)==="!D"){let z=$(P,U);this.docTypeEntities=z.entities,U=z.i}else if(P.substr(U+1,2)==="!["){let z=w(P,"]]>",U,"CDATA is not closed.")-2,q=P.substring(U+9,z);B=this.saveTextToParentTag(B,k,M);let de=this.parseTextData(q,k.tagname,M,!0,!1,!0,!0);de==null&&(de=""),this.options.cdataPropName?k.add(this.options.cdataPropName,[{[this.options.textNodeName]:q}]):k.add(this.options.textNodeName,de),U=z+2}else{let z=_(P,U,this.options.removeNSPrefix),q=z.tagName,de=z.rawTagName,ie=z.tagExp,_e=z.attrExpPresent,Zi=z.closeIndex;this.options.transformTagName&&(q=this.options.transformTagName(q)),k&&B&&k.tagname!=="!xml"&&(B=this.saveTextToParentTag(B,k,M,!1));let Hi=k;if(Hi&&this.options.unpairedTags.indexOf(Hi.tagname)!==-1&&(k=this.tagsNodeStack.pop(),M=M.substring(0,M.lastIndexOf("."))),q!==E.tagname&&(M+=M?"."+q:q),this.isItStopNode(this.options.stopNodes,M,q)){let Ae="";if(ie.length>0&&ie.lastIndexOf("/")===ie.length-1)U=z.closeIndex;else if(this.options.unpairedTags.indexOf(q)!==-1)U=z.closeIndex;else{let Zr=this.readStopNodeData(P,de,Zi+1);if(!Zr)throw new Error(`Unexpected end of ${de}`);U=Zr.i,Ae=Zr.tagContent}let qr=new A(q);q!==ie&&_e&&(qr[":@"]=this.buildAttributesMap(ie,M,q)),Ae&&(Ae=this.parseTextData(Ae,q,M,!0,_e,!0,!0)),M=M.substr(0,M.lastIndexOf(".")),qr.add(this.options.textNodeName,Ae),this.addChild(k,qr,M)}else{if(ie.length>0&&ie.lastIndexOf("/")===ie.length-1){q[q.length-1]==="/"?(q=q.substr(0,q.length-1),M=M.substr(0,M.length-1),ie=q):ie=ie.substr(0,ie.length-1),this.options.transformTagName&&(q=this.options.transformTagName(q));let Ae=new A(q);q!==ie&&_e&&(Ae[":@"]=this.buildAttributesMap(ie,M,q)),this.addChild(k,Ae,M),M=M.substr(0,M.lastIndexOf("."))}else{let Ae=new A(q);this.tagsNodeStack.push(k),q!==ie&&_e&&(Ae[":@"]=this.buildAttributesMap(ie,M,q)),this.addChild(k,Ae,M),k=Ae}B="",U=Zi}}else B+=P[U];return E.child},"parseXml");function H(P,E,k){let B=this.options.updateTag(E.tagname,k,E[":@"]);B===!1||(typeof B=="string"&&(E.tagname=B),P.addChild(E))}i(H,"addChild"),r(H,"addChild");var ge=r(function(P){if(this.options.processEntities){for(let E in this.docTypeEntities){let k=this.docTypeEntities[E];P=P.replace(k.regx,k.val)}for(let E in this.lastEntities){let k=this.lastEntities[E];P=P.replace(k.regex,k.val)}if(this.options.htmlEntities)for(let E in this.htmlEntities){let k=this.htmlEntities[E];P=P.replace(k.regex,k.val)}P=P.replace(this.ampEntity.regex,this.ampEntity.val)}return P},"replaceEntitiesValue");function X(P,E,k,B){return P&&(B===void 0&&(B=Object.keys(E.child).length===0),P=this.parseTextData(P,E.tagname,k,!1,E[":@"]?Object.keys(E[":@"]).length!==0:!1,B),P!==void 0&&P!==""&&E.add(this.options.textNodeName,P),P=""),P}i(X,"saveTextToParentTag"),r(X,"saveTextToParentTag");function ne(P,E,k){let B="*."+k;for(let M in P){let U=P[M];if(B===U||E===U)return!0}return!1}i(ne,"isItStopNode"),r(ne,"isItStopNode");function Se(P,E,k=">"){let B,M="";for(let U=E;U<P.length;U++){let re=P[U];if(B)re===B&&(B="");else if(re==='"'||re==="'")B=re;else if(re===k[0])if(k[1]){if(P[U+1]===k[1])return{data:M,index:U}}else return{data:M,index:U};else re===" "&&(re=" ");M+=re}}i(Se,"tagExpWithClosingIndex"),r(Se,"tagExpWithClosingIndex");function w(P,E,k,B){let M=P.indexOf(E,k);if(M===-1)throw new Error(B);return M+E.length-1}i(w,"findClosingIndex"),r(w,"findClosingIndex");function _(P,E,k,B=">"){let M=Se(P,E+1,B);if(!M)return;let U=M.data,re=M.index,z=U.search(/\s/),q=U,de=!0;z!==-1&&(q=U.substring(0,z),U=U.substring(z+1).trimStart());let ie=q;if(k){let _e=q.indexOf(":");_e!==-1&&(q=q.substr(_e+1),de=q!==M.data.substr(_e+1))}return{tagName:q,tagExp:U,closeIndex:re,attrExpPresent:de,rawTagName:ie}}i(_,"readTagExp"),r(_,"readTagExp");function G(P,E,k){let B=k,M=1;for(;k<P.length;k++)if(P[k]==="<")if(P[k+1]==="/"){let U=w(P,">",k,`${E} is not closed`);if(P.substring(k+2,U).trim()===E&&(M--,M===0))return{tagContent:P.substring(B,k),i:U};k=U}else if(P[k+1]==="?")k=w(P,"?>",k+1,"StopNode is not closed.");else if(P.substr(k+1,3)==="!--")k=w(P,"-->",k+3,"StopNode is not closed.");else if(P.substr(k+1,2)==="![")k=w(P,"]]>",k,"StopNode is not closed.")-2;else{let U=_(P,k,">");U&&((U&&U.tagName)===E&&U.tagExp[U.tagExp.length-1]!=="/"&&M++,k=U.closeIndex)}}i(G,"readStopNodeData"),r(G,"readStopNodeData");function fe(P,E,k){if(E&&typeof P=="string"){let B=P.trim();return B==="true"?!0:B==="false"?!1:N(P,k)}else return D.isExist(P)?P:""}i(fe,"parseValue"),r(fe,"parseValue"),I.exports=j}}),p=o({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(b){"use strict";function I(j,T){return D(j,T)}i(I,"prettify"),r(I,"prettify");function D(j,T,Z){let V,W={};for(let S=0;S<j.length;S++){let O=j[S],H=A(O),ge="";if(Z===void 0?ge=H:ge=Z+"."+H,H===T.textNodeName)V===void 0?V=O[H]:V+=""+O[H];else{if(H===void 0)continue;if(O[H]){let X=D(O[H],T,ge),ne=N(X,T);O[":@"]?$(X,O[":@"],ge,T):Object.keys(X).length===1&&X[T.textNodeName]!==void 0&&!T.alwaysCreateTextNode?X=X[T.textNodeName]:Object.keys(X).length===0&&(T.alwaysCreateTextNode?X[T.textNodeName]="":X=""),W[H]!==void 0&&W.hasOwnProperty(H)?(Array.isArray(W[H])||(W[H]=[W[H]]),W[H].push(X)):T.isArray(H,ge,ne)?W[H]=[X]:W[H]=X}}}return typeof V=="string"?V.length>0&&(W[T.textNodeName]=V):V!==void 0&&(W[T.textNodeName]=V),W}i(D,"compress"),r(D,"compress");function A(j){let T=Object.keys(j);for(let Z=0;Z<T.length;Z++){let V=T[Z];if(V!==":@")return V}}i(A,"propName"),r(A,"propName");function $(j,T,Z,V){if(T){let W=Object.keys(T),S=W.length;for(let O=0;O<S;O++){let H=W[O];V.isArray(H,Z+"."+H,!0,!0)?j[H]=[T[H]]:j[H]=T[H]}}}i($,"assignAttributes"),r($,"assignAttributes");function N(j,T){let{textNodeName:Z}=T,V=Object.keys(j).length;return!!(V===0||V===1&&(j[Z]||typeof j[Z]=="boolean"||j[Z]===0))}i(N,"isLeafTag"),r(N,"isLeafTag"),b.prettify=I}}),g=o({"node_modules/fast-xml-parser/src/validator.js"(b){"use strict";var I=a(),D={allowBooleanAttributes:!1,unpairedTags:[]};b.validate=function(w,_){_=Object.assign({},D,_);let G=[],fe=!1,P=!1;w[0]==="\uFEFF"&&(w=w.substr(1));for(let E=0;E<w.length;E++)if(w[E]==="<"&&w[E+1]==="?"){if(E+=2,E=$(w,E),E.err)return E}else if(w[E]==="<"){let k=E;if(E++,w[E]==="!"){E=N(w,E);continue}else{let B=!1;w[E]==="/"&&(B=!0,E++);let M="";for(;E<w.length&&w[E]!==">"&&w[E]!==" "&&w[E]!==" "&&w[E]!==`
74
+ `&&w[E]!=="\r";E++)M+=w[E];if(M=M.trim(),M[M.length-1]==="/"&&(M=M.substring(0,M.length-1),E--),!X(M)){let z;return M.trim().length===0?z="Invalid space after '<'.":z="Tag '"+M+"' is an invalid name.",H("InvalidTag",z,ne(w,E))}let U=Z(w,E);if(U===!1)return H("InvalidAttr","Attributes for '"+M+"' have open quote.",ne(w,E));let re=U.value;if(E=U.index,re[re.length-1]==="/"){let z=E-re.length;re=re.substring(0,re.length-1);let q=W(re,_);if(q===!0)fe=!0;else return H(q.err.code,q.err.msg,ne(w,z+q.err.line))}else if(B)if(U.tagClosed){if(re.trim().length>0)return H("InvalidTag","Closing tag '"+M+"' can't have attributes or invalid starting.",ne(w,k));{let z=G.pop();if(M!==z.tagName){let q=ne(w,z.tagStartPos);return H("InvalidTag","Expected closing tag '"+z.tagName+"' (opened in line "+q.line+", col "+q.col+") instead of closing tag '"+M+"'.",ne(w,k))}G.length==0&&(P=!0)}}else return H("InvalidTag","Closing tag '"+M+"' doesn't have proper closing.",ne(w,E));else{let z=W(re,_);if(z!==!0)return H(z.err.code,z.err.msg,ne(w,E-re.length+z.err.line));if(P===!0)return H("InvalidXml","Multiple possible root nodes found.",ne(w,E));_.unpairedTags.indexOf(M)!==-1||G.push({tagName:M,tagStartPos:k}),fe=!0}for(E++;E<w.length;E++)if(w[E]==="<")if(w[E+1]==="!"){E++,E=N(w,E);continue}else if(w[E+1]==="?"){if(E=$(w,++E),E.err)return E}else break;else if(w[E]==="&"){let z=O(w,E);if(z==-1)return H("InvalidChar","char '&' is not expected.",ne(w,E));E=z}else if(P===!0&&!A(w[E]))return H("InvalidXml","Extra text at the end",ne(w,E));w[E]==="<"&&E--}}else{if(A(w[E]))continue;return H("InvalidChar","char '"+w[E]+"' is not expected.",ne(w,E))}if(fe){if(G.length==1)return H("InvalidTag","Unclosed tag '"+G[0].tagName+"'.",ne(w,G[0].tagStartPos));if(G.length>0)return H("InvalidXml","Invalid '"+JSON.stringify(G.map(E=>E.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return H("InvalidXml","Start tag expected.",1);return!0};function A(w){return w===" "||w===" "||w===`
75
75
  `||w==="\r"}i(A,"isWhiteSpace"),r(A,"isWhiteSpace");function $(w,_){let G=_;for(;_<w.length;_++)if(w[_]=="?"||w[_]==" "){let fe=w.substr(G,_-G);if(_>5&&fe==="xml")return H("InvalidXml","XML declaration allowed only at the start of the document.",ne(w,_));if(w[_]=="?"&&w[_+1]==">"){_++;break}else continue}return _}i($,"readPI"),r($,"readPI");function N(w,_){if(w.length>_+5&&w[_+1]==="-"&&w[_+2]==="-"){for(_+=3;_<w.length;_++)if(w[_]==="-"&&w[_+1]==="-"&&w[_+2]===">"){_+=2;break}}else if(w.length>_+8&&w[_+1]==="D"&&w[_+2]==="O"&&w[_+3]==="C"&&w[_+4]==="T"&&w[_+5]==="Y"&&w[_+6]==="P"&&w[_+7]==="E"){let G=1;for(_+=8;_<w.length;_++)if(w[_]==="<")G++;else if(w[_]===">"&&(G--,G===0))break}else if(w.length>_+9&&w[_+1]==="["&&w[_+2]==="C"&&w[_+3]==="D"&&w[_+4]==="A"&&w[_+5]==="T"&&w[_+6]==="A"&&w[_+7]==="["){for(_+=8;_<w.length;_++)if(w[_]==="]"&&w[_+1]==="]"&&w[_+2]===">"){_+=2;break}}return _}i(N,"readCommentAndCDATA"),r(N,"readCommentAndCDATA");var j='"',T="'";function Z(w,_){let G="",fe="",P=!1;for(;_<w.length;_++){if(w[_]===j||w[_]===T)fe===""?fe=w[_]:fe!==w[_]||(fe="");else if(w[_]===">"&&fe===""){P=!0;break}G+=w[_]}return fe!==""?!1:{value:G,index:_,tagClosed:P}}i(Z,"readAttributeStr"),r(Z,"readAttributeStr");var V=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function W(w,_){let G=I.getAllMatches(w,V),fe={};for(let P=0;P<G.length;P++){if(G[P][1].length===0)return H("InvalidAttr","Attribute '"+G[P][2]+"' has no space in starting.",Se(G[P]));if(G[P][3]!==void 0&&G[P][4]===void 0)return H("InvalidAttr","Attribute '"+G[P][2]+"' is without value.",Se(G[P]));if(G[P][3]===void 0&&!_.allowBooleanAttributes)return H("InvalidAttr","boolean attribute '"+G[P][2]+"' is not allowed.",Se(G[P]));let E=G[P][2];if(!ge(E))return H("InvalidAttr","Attribute '"+E+"' is an invalid name.",Se(G[P]));if(!fe.hasOwnProperty(E))fe[E]=1;else return H("InvalidAttr","Attribute '"+E+"' is repeated.",Se(G[P]))}return!0}i(W,"validateAttributeString"),r(W,"validateAttributeString");function S(w,_){let G=/\d/;for(w[_]==="x"&&(_++,G=/[\da-fA-F]/);_<w.length;_++){if(w[_]===";")return _;if(!w[_].match(G))break}return-1}i(S,"validateNumberAmpersand"),r(S,"validateNumberAmpersand");function O(w,_){if(_++,w[_]===";")return-1;if(w[_]==="#")return _++,S(w,_);let G=0;for(;_<w.length;_++,G++)if(!(w[_].match(/\w/)&&G<20)){if(w[_]===";")break;return-1}return _}i(O,"validateAmpersand"),r(O,"validateAmpersand");function H(w,_,G){return{err:{code:w,msg:_,line:G.line||G,col:G.col}}}i(H,"getErrorObject"),r(H,"getErrorObject");function ge(w){return I.isName(w)}i(ge,"validateAttrName"),r(ge,"validateAttrName");function X(w){return I.isName(w)}i(X,"validateTagName"),r(X,"validateTagName");function ne(w,_){let G=w.substring(0,_).split(/\r?\n/);return{line:G.length,col:G[G.length-1].length+1}}i(ne,"getLineNumberForPosition"),r(ne,"getLineNumberForPosition");function Se(w){return w.startIndex+w[1].length}i(Se,"getPositionFromMatch"),r(Se,"getPositionFromMatch")}}),h=o({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(b,I){var{buildOptions:D}=s(),A=d(),{prettify:$}=p(),N=g(),j=class{static{i(this,"XMLParser")}static{r(this,"XMLParser")}constructor(T){this.externalEntities={},this.options=D(T)}parse(T,Z){if(typeof T!="string")if(T.toString)T=T.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(Z){Z===!0&&(Z={});let S=N.validate(T,Z);if(S!==!0)throw Error(`${S.err.msg}:${S.err.line}:${S.err.col}`)}let V=new A(this.options);V.addExternalEntities(this.externalEntities);let W=V.parseXml(T);return this.options.preserveOrder||W===void 0?W:$(W,this.options)}addEntity(T,Z){if(Z.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(T.indexOf("&")!==-1||T.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[T]=Z}};I.exports=j}});let v=h();return new v(n)},"getXmlParser");var Ar=class extends je{static{i(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),y("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=Cc({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,t,r){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let o;try{let u=await e.text();o=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw r.log.error(c,u),new L(c)}let s=new Headers(e.headers);return s.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:s})}};var _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=i(e=>{this.#e.enqueue(e),Wn().waitUntil(this.#e.waitUntilFlushed())},"enqueue")};var Sc=10,Ac=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=Ac,this.#r=Sc}else{let r=t;this.#n=r.ttlSeconds*1e3,this.#o=r.loaderTimeoutSeconds?r.loaderTimeoutSeconds*1e3:Ac,this.#r=Sc}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 om(()=>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 om(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(om,"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 L(`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,y("platform.kv-store")}put(e,t,r){if(typeof e!="string")throw new f("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)}};
76
76
  /*! For license information please see index.js.LEGAL.txt */