@zuplo/runtime 5.1797.0 → 5.1801.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/index.minified.js CHANGED
@@ -22,17 +22,17 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- "use strict";var va=Object.create;var Ke=Object.defineProperty;var Sa=Object.getOwnPropertyDescriptor;var Ta=Object.getOwnPropertyNames;var Oa=Object.getPrototypeOf,Ca=Object.prototype.hasOwnProperty;var s=(t,e)=>Ke(t,"name",{value:e,configurable:!0});var Je=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Aa=(t,e)=>{for(var n in e)Ke(t,n,{get:e[n],enumerable:!0})},yo=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ta(e))!Ca.call(t,o)&&o!==n&&Ke(t,o,{get:()=>e[o],enumerable:!(r=Sa(e,o))||r.enumerable});return t};var Ae=(t,e,n)=>(n=t!=null?va(Oa(t)):{},yo(e||!t||!t.__esModule?Ke(n,"default",{value:t,enumerable:!0}):n,t)),La=t=>yo(Ke({},"__esModule",{value:!0}),t);var No=Je(b=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});b.generateColor=b.colorFunctions=b.stripColor=b.bgRgb24=b.rgb24=b.bgRgb8=b.rgb8=b.bgBrightWhite=b.bgBrightCyan=b.bgBrightMagenta=b.bgBrightBlue=b.bgBrightYellow=b.bgBrightGreen=b.bgBrightRed=b.bgBrightBlack=b.bgWhite=b.bgCyan=b.bgMagenta=b.bgBlue=b.bgYellow=b.bgGreen=b.bgRed=b.bgBlack=b.brightWhite=b.brightCyan=b.brightMagenta=b.brightBlue=b.brightYellow=b.brightGreen=b.brightRed=b.brightBlack=b.gray=b.white=b.cyan=b.magenta=b.blue=b.yellow=b.green=b.red=b.black=b.strikethrough=b.hidden=b.inverse=b.underline=b.italic=b.dim=b.bold=b.reset=b.getColorEnabled=b.setColorEnabled=void 0;var Ao=!0,Vn=!Ao;function _a(t){Ao||(Vn=t)}s(_a,"setColorEnabled");b.setColorEnabled=_a;function ka(){return Vn}s(ka,"getColorEnabled");b.getColorEnabled=ka;function v(t,e){return{open:`\x1B[${t.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}s(v,"code");function S(t,e){return Vn?`${e.open}${t.replace(e.regexp,e.open)}${e.close}`:t}s(S,"run");function Da(t){return S(t,v([0],0))}s(Da,"reset");b.reset=Da;function Ua(t){return S(t,v([1],22))}s(Ua,"bold");b.bold=Ua;function Ha(t){return S(t,v([2],22))}s(Ha,"dim");b.dim=Ha;function Ma(t){return S(t,v([3],23))}s(Ma,"italic");b.italic=Ma;function Na(t){return S(t,v([4],24))}s(Na,"underline");b.underline=Na;function Za(t){return S(t,v([7],27))}s(Za,"inverse");b.inverse=Za;function qa(t){return S(t,v([8],28))}s(qa,"hidden");b.hidden=qa;function $a(t){return S(t,v([9],29))}s($a,"strikethrough");b.strikethrough=$a;function Fa(t){return S(t,v([30],39))}s(Fa,"black");b.black=Fa;function Lo(t){return S(t,v([31],39))}s(Lo,"red");b.red=Lo;function _o(t){return S(t,v([32],39))}s(_o,"green");b.green=_o;function ko(t){return S(t,v([33],39))}s(ko,"yellow");b.yellow=ko;function Do(t){return S(t,v([34],39))}s(Do,"blue");b.blue=Do;function Uo(t){return S(t,v([35],39))}s(Uo,"magenta");b.magenta=Uo;function Ho(t){return S(t,v([36],39))}s(Ho,"cyan");b.cyan=Ho;function Ba(t){return S(t,v([37],39))}s(Ba,"white");b.white=Ba;function ja(t){return Mo(t)}s(ja,"gray");b.gray=ja;function Mo(t){return S(t,v([90],39))}s(Mo,"brightBlack");b.brightBlack=Mo;function za(t){return S(t,v([91],39))}s(za,"brightRed");b.brightRed=za;function Va(t){return S(t,v([92],39))}s(Va,"brightGreen");b.brightGreen=Va;function Ga(t){return S(t,v([93],39))}s(Ga,"brightYellow");b.brightYellow=Ga;function Wa(t){return S(t,v([94],39))}s(Wa,"brightBlue");b.brightBlue=Wa;function Ka(t){return S(t,v([95],39))}s(Ka,"brightMagenta");b.brightMagenta=Ka;function Ja(t){return S(t,v([96],39))}s(Ja,"brightCyan");b.brightCyan=Ja;function Ya(t){return S(t,v([97],39))}s(Ya,"brightWhite");b.brightWhite=Ya;function Qa(t){return S(t,v([40],49))}s(Qa,"bgBlack");b.bgBlack=Qa;function Xa(t){return S(t,v([41],49))}s(Xa,"bgRed");b.bgRed=Xa;function eu(t){return S(t,v([42],49))}s(eu,"bgGreen");b.bgGreen=eu;function tu(t){return S(t,v([43],49))}s(tu,"bgYellow");b.bgYellow=tu;function nu(t){return S(t,v([44],49))}s(nu,"bgBlue");b.bgBlue=nu;function ru(t){return S(t,v([45],49))}s(ru,"bgMagenta");b.bgMagenta=ru;function ou(t){return S(t,v([46],49))}s(ou,"bgCyan");b.bgCyan=ou;function iu(t){return S(t,v([47],49))}s(iu,"bgWhite");b.bgWhite=iu;function su(t){return S(t,v([100],49))}s(su,"bgBrightBlack");b.bgBrightBlack=su;function au(t){return S(t,v([101],49))}s(au,"bgBrightRed");b.bgBrightRed=au;function uu(t){return S(t,v([102],49))}s(uu,"bgBrightGreen");b.bgBrightGreen=uu;function cu(t){return S(t,v([103],49))}s(cu,"bgBrightYellow");b.bgBrightYellow=cu;function lu(t){return S(t,v([104],49))}s(lu,"bgBrightBlue");b.bgBrightBlue=lu;function du(t){return S(t,v([105],49))}s(du,"bgBrightMagenta");b.bgBrightMagenta=du;function pu(t){return S(t,v([106],49))}s(pu,"bgBrightCyan");b.bgBrightCyan=pu;function mu(t){return S(t,v([107],49))}s(mu,"bgBrightWhite");b.bgBrightWhite=mu;function pe(t,e=255,n=0){return Math.trunc(Math.max(Math.min(t,e),n))}s(pe,"clampAndTruncate");function gu(t,e){return S(t,v([38,5,pe(e)],39))}s(gu,"rgb8");b.rgb8=gu;function fu(t,e){return S(t,v([48,5,pe(e)],49))}s(fu,"bgRgb8");b.bgRgb8=fu;function hu(t,e){return typeof e=="number"?S(t,v([38,2,e>>16&255,e>>8&255,e&255],39)):S(t,v([38,2,pe(e.r),pe(e.g),pe(e.b)],39))}s(hu,"rgb24");b.rgb24=hu;function yu(t,e){return typeof e=="number"?S(t,v([48,2,e>>16&255,e>>8&255,e&255],49)):S(t,v([48,2,pe(e.r),pe(e.g),pe(e.b)],49))}s(yu,"bgRgb24");b.bgRgb24=yu;var bu=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 wu(t){return t.replace(bu,"")}s(wu,"stripColor");b.stripColor=wu;b.colorFunctions=[Lo,_o,ko,Do,Uo,Ho];function Ru(t){let e=0,n=t.length,r=0;if(n>0)for(;r<n;)e=(e<<5)-e+t.charCodeAt(r++)|0;return e}s(Ru,"hashCode");function Pu(t){let e=Math.abs(Ru(t));return b.colorFunctions[e%b.colorFunctions.length]}s(Pu,"generateColor");b.generateColor=Pu});var Zo=Je(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.format=void 0;function Iu(t,e,...n){let r=0,o=n.length,i=String(e).replace(/%[sdjoO%]/g,a=>{if(a==="%%")return"%";if(r>=o)return a;switch(a){case"%s":return String(n[r++]);case"%d":return Number(n[r++]).toString();case"%o":return t(n[r++]).split(`
26
- `).map(u=>u.trim()).join(" ");case"%O":return t(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch{return"[Circular]"}default:return a}});for(let a of n.splice(r))a===null||!(typeof a=="object"&&a!==null)?i+=" "+a:i+=" "+t(a);return i}s(Iu,"format");Pt.format=Iu});var zo=Je(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.inspect=void 0;function Re(t,e,n,r){let o={seen:[],stylize:Eu,showHidden:e??!1,depth:n??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=vu),It(o,t,o.depth)}s(Re,"inspect");Et.inspect=Re;Re.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]};Re.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function Eu(t,e){return t}s(Eu,"stylizeNoColor");function xu(t){return typeof t=="boolean"}s(xu,"isBoolean");function $o(t){return t===void 0}s($o,"isUndefined");function vu(t,e){let n=Re.styles[e];return n?"\x1B["+Re.colors[n][0]+"m"+t+"\x1B["+Re.colors[n][1]+"m":t}s(vu,"stylizeWithColor");function Gn(t){return typeof t=="function"}s(Gn,"isFunction");function Fo(t){return typeof t=="string"}s(Fo,"isString");function Su(t){return typeof t=="number"}s(Su,"isNumber");function Bo(t){return t===null}s(Bo,"isNull");function jo(t,e){return Object.prototype.hasOwnProperty.call(t,e)}s(jo,"hasOwn");function Wn(t){return Qn(t)&&Xn(t)==="[object RegExp]"}s(Wn,"isRegExp");function Qn(t){return typeof t=="object"&&t!==null}s(Qn,"isObject");function Kn(t){return Qn(t)&&(Xn(t)==="[object Error]"||t instanceof Error)}s(Kn,"isError");function qo(t){return Qn(t)&&Xn(t)==="[object Date]"}s(qo,"isDate");function Xn(t){return Object.prototype.toString.call(t)}s(Xn,"objectToString");function Tu(t){let e={};return t.forEach(function(n,r){e[n]=!0}),e}s(Tu,"arrayToHash");function Ou(t,e,n,r,o){let i=[];for(let a=0,u=e.length;a<u;++a)jo(e,String(a))?i.push(Yn(t,e,n,r,String(a),!0)):i.push("");return o.forEach(function(a){a.match(/^\d+$/)||i.push(Yn(t,e,n,r,a,!0))}),i}s(Ou,"formatArray");function Jn(t){return"["+Error.prototype.toString.call(t)+"]"}s(Jn,"formatError");function It(t,e,n){if(t.customInspect&&e&&Gn(e.inspect)&&e.inspect!==Re&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(n,t);return Fo(d)||(d=It(t,d,n)),d}let r=Cu(t,e);if(r)return r;let o=Object.keys(e),i=Tu(o);try{t.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(Kn(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return Jn(e);if(o.length===0){if(Gn(e)){let d=e.name?": "+e.name:"";return t.stylize("[Function"+d+"]","special")}if(Wn(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(qo(e))return t.stylize(Date.prototype.toString.call(e),"date");if(Kn(e))return Jn(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),Gn(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),Wn(e)&&(a=" "+RegExp.prototype.toString.call(e)),qo(e)&&(a=" "+Date.prototype.toUTCString.call(e)),Kn(e)&&(a=" "+Jn(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(n<0)return Wn(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special");t.seen.push(e);let l;return u?l=Ou(t,e,n,i,o):l=o.map(function(d){return Yn(t,e,n,i,d,u)}),t.seen.pop(),Au(l,a,c)}s(It,"formatValue");function Yn(t,e,n,r,o,i){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=t.stylize("[Getter/Setter]","special"):u=t.stylize("[Getter]","special"):c.set&&(u=t.stylize("[Setter]","special")),jo(r,o)||(a="["+o+"]"),u||(t.seen.indexOf(c.value)<0?(Bo(n)?u=It(t,c.value,null):u=It(t,c.value,n-1),u.indexOf(`
25
+ "use strict";var Oa=Object.create;var Ke=Object.defineProperty;var Ca=Object.getOwnPropertyDescriptor;var Aa=Object.getOwnPropertyNames;var La=Object.getPrototypeOf,_a=Object.prototype.hasOwnProperty;var s=(t,e)=>Ke(t,"name",{value:e,configurable:!0});var Je=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ka=(t,e)=>{for(var n in e)Ke(t,n,{get:e[n],enumerable:!0})},yo=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Aa(e))!_a.call(t,o)&&o!==n&&Ke(t,o,{get:()=>e[o],enumerable:!(r=Ca(e,o))||r.enumerable});return t};var Ae=(t,e,n)=>(n=t!=null?Oa(La(t)):{},yo(e||!t||!t.__esModule?Ke(n,"default",{value:t,enumerable:!0}):n,t)),Da=t=>yo(Ke({},"__esModule",{value:!0}),t);var No=Je(y=>{"use strict";Object.defineProperty(y,"__esModule",{value:!0});y.generateColor=y.colorFunctions=y.stripColor=y.bgRgb24=y.rgb24=y.bgRgb8=y.rgb8=y.bgBrightWhite=y.bgBrightCyan=y.bgBrightMagenta=y.bgBrightBlue=y.bgBrightYellow=y.bgBrightGreen=y.bgBrightRed=y.bgBrightBlack=y.bgWhite=y.bgCyan=y.bgMagenta=y.bgBlue=y.bgYellow=y.bgGreen=y.bgRed=y.bgBlack=y.brightWhite=y.brightCyan=y.brightMagenta=y.brightBlue=y.brightYellow=y.brightGreen=y.brightRed=y.brightBlack=y.gray=y.white=y.cyan=y.magenta=y.blue=y.yellow=y.green=y.red=y.black=y.strikethrough=y.hidden=y.inverse=y.underline=y.italic=y.dim=y.bold=y.reset=y.getColorEnabled=y.setColorEnabled=void 0;var Ao=!0,Vn=!Ao;function Ua(t){Ao||(Vn=t)}s(Ua,"setColorEnabled");y.setColorEnabled=Ua;function Ha(){return Vn}s(Ha,"getColorEnabled");y.getColorEnabled=Ha;function v(t,e){return{open:`\x1B[${t.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}s(v,"code");function S(t,e){return Vn?`${e.open}${t.replace(e.regexp,e.open)}${e.close}`:t}s(S,"run");function Ma(t){return S(t,v([0],0))}s(Ma,"reset");y.reset=Ma;function Na(t){return S(t,v([1],22))}s(Na,"bold");y.bold=Na;function Za(t){return S(t,v([2],22))}s(Za,"dim");y.dim=Za;function qa(t){return S(t,v([3],23))}s(qa,"italic");y.italic=qa;function $a(t){return S(t,v([4],24))}s($a,"underline");y.underline=$a;function Fa(t){return S(t,v([7],27))}s(Fa,"inverse");y.inverse=Fa;function Ba(t){return S(t,v([8],28))}s(Ba,"hidden");y.hidden=Ba;function ja(t){return S(t,v([9],29))}s(ja,"strikethrough");y.strikethrough=ja;function za(t){return S(t,v([30],39))}s(za,"black");y.black=za;function Lo(t){return S(t,v([31],39))}s(Lo,"red");y.red=Lo;function _o(t){return S(t,v([32],39))}s(_o,"green");y.green=_o;function ko(t){return S(t,v([33],39))}s(ko,"yellow");y.yellow=ko;function Do(t){return S(t,v([34],39))}s(Do,"blue");y.blue=Do;function Uo(t){return S(t,v([35],39))}s(Uo,"magenta");y.magenta=Uo;function Ho(t){return S(t,v([36],39))}s(Ho,"cyan");y.cyan=Ho;function Va(t){return S(t,v([37],39))}s(Va,"white");y.white=Va;function Ga(t){return Mo(t)}s(Ga,"gray");y.gray=Ga;function Mo(t){return S(t,v([90],39))}s(Mo,"brightBlack");y.brightBlack=Mo;function Wa(t){return S(t,v([91],39))}s(Wa,"brightRed");y.brightRed=Wa;function Ka(t){return S(t,v([92],39))}s(Ka,"brightGreen");y.brightGreen=Ka;function Ja(t){return S(t,v([93],39))}s(Ja,"brightYellow");y.brightYellow=Ja;function Ya(t){return S(t,v([94],39))}s(Ya,"brightBlue");y.brightBlue=Ya;function Qa(t){return S(t,v([95],39))}s(Qa,"brightMagenta");y.brightMagenta=Qa;function Xa(t){return S(t,v([96],39))}s(Xa,"brightCyan");y.brightCyan=Xa;function eu(t){return S(t,v([97],39))}s(eu,"brightWhite");y.brightWhite=eu;function tu(t){return S(t,v([40],49))}s(tu,"bgBlack");y.bgBlack=tu;function nu(t){return S(t,v([41],49))}s(nu,"bgRed");y.bgRed=nu;function ru(t){return S(t,v([42],49))}s(ru,"bgGreen");y.bgGreen=ru;function ou(t){return S(t,v([43],49))}s(ou,"bgYellow");y.bgYellow=ou;function iu(t){return S(t,v([44],49))}s(iu,"bgBlue");y.bgBlue=iu;function su(t){return S(t,v([45],49))}s(su,"bgMagenta");y.bgMagenta=su;function au(t){return S(t,v([46],49))}s(au,"bgCyan");y.bgCyan=au;function uu(t){return S(t,v([47],49))}s(uu,"bgWhite");y.bgWhite=uu;function cu(t){return S(t,v([100],49))}s(cu,"bgBrightBlack");y.bgBrightBlack=cu;function lu(t){return S(t,v([101],49))}s(lu,"bgBrightRed");y.bgBrightRed=lu;function du(t){return S(t,v([102],49))}s(du,"bgBrightGreen");y.bgBrightGreen=du;function pu(t){return S(t,v([103],49))}s(pu,"bgBrightYellow");y.bgBrightYellow=pu;function mu(t){return S(t,v([104],49))}s(mu,"bgBrightBlue");y.bgBrightBlue=mu;function gu(t){return S(t,v([105],49))}s(gu,"bgBrightMagenta");y.bgBrightMagenta=gu;function fu(t){return S(t,v([106],49))}s(fu,"bgBrightCyan");y.bgBrightCyan=fu;function hu(t){return S(t,v([107],49))}s(hu,"bgBrightWhite");y.bgBrightWhite=hu;function de(t,e=255,n=0){return Math.trunc(Math.max(Math.min(t,e),n))}s(de,"clampAndTruncate");function yu(t,e){return S(t,v([38,5,de(e)],39))}s(yu,"rgb8");y.rgb8=yu;function bu(t,e){return S(t,v([48,5,de(e)],49))}s(bu,"bgRgb8");y.bgRgb8=bu;function wu(t,e){return typeof e=="number"?S(t,v([38,2,e>>16&255,e>>8&255,e&255],39)):S(t,v([38,2,de(e.r),de(e.g),de(e.b)],39))}s(wu,"rgb24");y.rgb24=wu;function Ru(t,e){return typeof e=="number"?S(t,v([48,2,e>>16&255,e>>8&255,e&255],49)):S(t,v([48,2,de(e.r),de(e.g),de(e.b)],49))}s(Ru,"bgRgb24");y.bgRgb24=Ru;var Pu=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 Iu(t){return t.replace(Pu,"")}s(Iu,"stripColor");y.stripColor=Iu;y.colorFunctions=[Lo,_o,ko,Do,Uo,Ho];function Eu(t){let e=0,n=t.length,r=0;if(n>0)for(;r<n;)e=(e<<5)-e+t.charCodeAt(r++)|0;return e}s(Eu,"hashCode");function xu(t){let e=Math.abs(Eu(t));return y.colorFunctions[e%y.colorFunctions.length]}s(xu,"generateColor");y.generateColor=xu});var Zo=Je(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.format=void 0;function vu(t,e,...n){let r=0,o=n.length,i=String(e).replace(/%[sdjoO%]/g,a=>{if(a==="%%")return"%";if(r>=o)return a;switch(a){case"%s":return String(n[r++]);case"%d":return Number(n[r++]).toString();case"%o":return t(n[r++]).split(`
26
+ `).map(u=>u.trim()).join(" ");case"%O":return t(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch{return"[Circular]"}default:return a}});for(let a of n.splice(r))a===null||!(typeof a=="object"&&a!==null)?i+=" "+a:i+=" "+t(a);return i}s(vu,"format");Pt.format=vu});var zo=Je(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.inspect=void 0;function Re(t,e,n,r){let o={seen:[],stylize:Su,showHidden:e??!1,depth:n??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=Ou),It(o,t,o.depth)}s(Re,"inspect");Et.inspect=Re;Re.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]};Re.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function Su(t,e){return t}s(Su,"stylizeNoColor");function Tu(t){return typeof t=="boolean"}s(Tu,"isBoolean");function $o(t){return t===void 0}s($o,"isUndefined");function Ou(t,e){let n=Re.styles[e];return n?"\x1B["+Re.colors[n][0]+"m"+t+"\x1B["+Re.colors[n][1]+"m":t}s(Ou,"stylizeWithColor");function Gn(t){return typeof t=="function"}s(Gn,"isFunction");function Fo(t){return typeof t=="string"}s(Fo,"isString");function Cu(t){return typeof t=="number"}s(Cu,"isNumber");function Bo(t){return t===null}s(Bo,"isNull");function jo(t,e){return Object.prototype.hasOwnProperty.call(t,e)}s(jo,"hasOwn");function Wn(t){return Qn(t)&&Xn(t)==="[object RegExp]"}s(Wn,"isRegExp");function Qn(t){return typeof t=="object"&&t!==null}s(Qn,"isObject");function Kn(t){return Qn(t)&&(Xn(t)==="[object Error]"||t instanceof Error)}s(Kn,"isError");function qo(t){return Qn(t)&&Xn(t)==="[object Date]"}s(qo,"isDate");function Xn(t){return Object.prototype.toString.call(t)}s(Xn,"objectToString");function Au(t){let e={};return t.forEach(function(n,r){e[n]=!0}),e}s(Au,"arrayToHash");function Lu(t,e,n,r,o){let i=[];for(let a=0,u=e.length;a<u;++a)jo(e,String(a))?i.push(Yn(t,e,n,r,String(a),!0)):i.push("");return o.forEach(function(a){a.match(/^\d+$/)||i.push(Yn(t,e,n,r,a,!0))}),i}s(Lu,"formatArray");function Jn(t){return"["+Error.prototype.toString.call(t)+"]"}s(Jn,"formatError");function It(t,e,n){if(t.customInspect&&e&&Gn(e.inspect)&&e.inspect!==Re&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(n,t);return Fo(d)||(d=It(t,d,n)),d}let r=_u(t,e);if(r)return r;let o=Object.keys(e),i=Au(o);try{t.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(Kn(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return Jn(e);if(o.length===0){if(Gn(e)){let d=e.name?": "+e.name:"";return t.stylize("[Function"+d+"]","special")}if(Wn(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(qo(e))return t.stylize(Date.prototype.toString.call(e),"date");if(Kn(e))return Jn(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),Gn(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),Wn(e)&&(a=" "+RegExp.prototype.toString.call(e)),qo(e)&&(a=" "+Date.prototype.toUTCString.call(e)),Kn(e)&&(a=" "+Jn(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(n<0)return Wn(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special");t.seen.push(e);let l;return u?l=Lu(t,e,n,i,o):l=o.map(function(d){return Yn(t,e,n,i,d,u)}),t.seen.pop(),ku(l,a,c)}s(It,"formatValue");function Yn(t,e,n,r,o,i){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=t.stylize("[Getter/Setter]","special"):u=t.stylize("[Getter]","special"):c.set&&(u=t.stylize("[Setter]","special")),jo(r,o)||(a="["+o+"]"),u||(t.seen.indexOf(c.value)<0?(Bo(n)?u=It(t,c.value,null):u=It(t,c.value,n-1),u.indexOf(`
27
27
  `)>-1&&(i?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=t.stylize("[Circular]","special")),$o(a)){if(i&&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=t.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=t.stylize(a,"string"))}return a+": "+u}s(Yn,"formatProperty");function Cu(t,e){if($o(e))return t.stylize("undefined","undefined");if(Fo(e)){let n="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(n,"string")}if(Su(e))return t.stylize(""+e,"number");if(xu(e))return t.stylize(""+e,"boolean");if(Bo(e))return t.stylize("null","null")}s(Cu,"formatPrimitive");function Au(t,e,n){let r=0;return t.reduce(function(i,a){return r++,a.indexOf(`
32
+ `))):u=t.stylize("[Circular]","special")),$o(a)){if(i&&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=t.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=t.stylize(a,"string"))}return a+": "+u}s(Yn,"formatProperty");function _u(t,e){if($o(e))return t.stylize("undefined","undefined");if(Fo(e)){let n="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(n,"string")}if(Cu(e))return t.stylize(""+e,"number");if(Tu(e))return t.stylize(""+e,"boolean");if(Bo(e))return t.stylize("null","null")}s(_u,"formatPrimitive");function ku(t,e,n){let r=0;return t.reduce(function(i,a){return r++,a.indexOf(`
33
33
  `)>=0&&r++,i+a.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?n[0]+(e===""?"":e+`
34
34
  `)+" "+t.join(`,
35
- `)+" "+n[1]:n[0]+e+" "+t.join(", ")+" "+n[1]}s(Au,"reduceToSingleString")});var Vo=Je(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.format=void 0;var Lu=Zo(),_u=zo(),ku=s((t,...e)=>(0,Lu.format)(_u.inspect,t,e),"format");xt.format=ku});var Pe=Je(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.debug=me.withoutEnv=me.Debugger=void 0;var Du=No(),Uu=Vo(),vt=class{static{s(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,n){this.manager=e,this.ns=n,this.color=(0,Du.generateColor)(n),this.last=0,this.enabled=e.enabled.some(r=>r.test(n))}log(...e){if(!this.enabled)return;let n,r=e[0];typeof r=="function"?n=r():n=String(r);let o=Date.now()-(this.last||Date.now());n=(0,Uu.format)(n,...e);let i=`${this.color(this.ns)} ${n} ${this.color(`+${o}ms`)}`;console.log(i),this.last=Date.now()}};me.Debugger=vt;var St=class{static{s(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function Go(t){return!t||t.length===0?[]:(t=t.replace(/\s/g,"").replace(/\*/g,".+"),t.split(",").map(e=>new RegExp(`^${e}$`)))}s(Go,"extract");var Xe;function Hu(t){t||(t=[]),typeof t=="string"&&(t=Go(t)),Xe=new St(t)}s(Hu,"withoutEnv");me.withoutEnv=Hu;function Mu(t){let e=globalThis.DEBUG;Xe||(Xe=new St(Go(e)));let n=new vt(Xe,t);return Xe.debuggers.set(t,n),Object.assign(n.log.bind(n),{self:n})}s(Mu,"debug");me.debug=Mu});var Hl={};Aa(Hl,{API_KEY:()=>bi,AWSLoggingPlugin:()=>un,AmberfloMeteringInboundPolicy:()=>ps,AmberfloMeteringPolicy:()=>fn,ApiAuthKeyInboundPolicy:()=>fs,ApiKeyInboundPolicy:()=>yn,AuditLogDataStaxProvider:()=>dn,AuditLogPlugin:()=>pn,Auth0JwtInboundPolicy:()=>hs,AwsLambdaHandlerExtensions:()=>Vi,BasicAuthInboundPolicy:()=>ys,BasicRateLimitInboundPolicy:()=>so,CachingInboundPolicy:()=>bs,ChangeMethodInboundPolicy:()=>ws,ClearHeadersInboundPolicy:()=>Rs,ClearHeadersOutboundPolicy:()=>Ps,ClerkJwtInboundPolicy:()=>Is,CognitoJwtInboundPolicy:()=>Es,CompositeInboundPolicy:()=>xs,ConfigurationError:()=>g,ContentTypes:()=>Ct,ContextData:()=>le,CryptoBeta:()=>Tn,CurityPhantomTokenInboundPolicy:()=>vs,DataDogLoggingPlugin:()=>Gt,DataDogMetricsPlugin:()=>cn,DynaTraceLoggingPlugin:()=>rn,DynatraceMetricsPlugin:()=>ln,FirebaseJwtInboundPolicy:()=>Ss,FormDataToJsonInboundPolicy:()=>Ts,GeoFilterInboundPolicy:()=>Os,GoogleCloudLoggingPlugin:()=>jt,Handler:()=>tn,HttpProblems:()=>R,HttpStatusCode:()=>_t,InboundPolicy:()=>ue,JWTScopeValidationInboundPolicy:()=>Cs,KeyValueStore:()=>Cn,LoadSubscriptionInboundPolicy:()=>As,LokiLoggingPlugin:()=>on,LookupResult:()=>Me,MemoryZoneReadThroughCache:()=>N,MeteringInboundPolicy:()=>Ls,MockApiInboundPolicy:()=>ks,MoesifInboundPolicy:()=>Zs,OktaJwtInboundPolicy:()=>qs,OpenIdJwtInboundPolicy:()=>F,OutboundPolicy:()=>Se,ProblemResponseFormatter:()=>ge,PropelAuthJwtInboundPolicy:()=>Fs,RateLimitInboundPolicy:()=>so,ReadmeMetricsInboundPolicy:()=>Gs,RemoveHeadersInboundPolicy:()=>Ws,RemoveHeadersOutboundPolicy:()=>Ks,RemoveQueryParamsInboundPolicy:()=>Js,ReplaceStringOutboundPolicy:()=>Ys,RequestSizeLimitInboundPolicy:()=>Xs,RequestValidationInboundPolicy:()=>co,RequireOriginInboundPolicy:()=>aa,ResponseSendingEvent:()=>ke,ResponseSentEvent:()=>De,Router:()=>Ne,RuntimeError:()=>I,SYSTEM_LOGGER:()=>st,SchemaBasedRequestValidation:()=>sa,ServiceProviderImpl:()=>vn,SetBodyInboundPolicy:()=>ua,SetHeadersInboundPolicy:()=>ca,SetHeadersOutboundPolicy:()=>la,SetQueryParamsInboundPolicy:()=>da,SetStatusOutboundPolicy:()=>pa,SleepInboundPolicy:()=>ma,StripeMeteringPlugin:()=>Qr,StripeWebhookVerificationInboundPolicy:()=>Be,SumoLogicLoggingPlugin:()=>sn,SupabaseJwtInboundPolicy:()=>ga,SystemLogMap:()=>O,SystemRouteName:()=>re,UpstreamAzureAdServiceAuthInboundPolicy:()=>fa,UpstreamFirebaseAdminAuthInboundPolicy:()=>ya,UpstreamFirebaseUserAuthInboundPolicy:()=>ba,UpstreamGcpJwtInboundPolicy:()=>wa,UpstreamGcpServiceAuthInboundPolicy:()=>Pa,VMWareLogInsightLoggingPlugin:()=>an,ValidateJsonSchemaInbound:()=>Ia,ZoneCache:()=>de,ZuploRequest:()=>L,awsLambdaHandler:()=>Gi,environment:()=>q,getIdForParameterSchema:()=>En,getIdForRefSchema:()=>ta,getIdForRequestBodySchema:()=>xn,getRawOperationDataIdentifierName:()=>ea,httpStatuses:()=>kt,isRestrictedEnvVariableName:()=>xr,isZuploReadableEnvVariableName:()=>vr,openApiSpecHandler:()=>Wi,originalFetch:()=>Ze,purgeGatewayCache:()=>Ui,redirectHandler:()=>Ki,sanitizedIdentifierName:()=>we,serialize:()=>At,setMoesifContext:()=>Ns,urlForwardHandler:()=>Ji,urlRewriteHandler:()=>Yi,webSocketHandler:()=>Qi,webSocketPipelineHandler:()=>ts});module.exports=La(Hl);var T=class extends Error{static{s(this,"SystemError")}constructor(e,n){super(e,n),this.name="InternalError"}},I=class extends Error{static{s(this,"RuntimeError")}extensionMembers;constructor(e,n){typeof e=="string"?super(e,n):(super(e.message,n),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},g=class extends I{static{s(this,"ConfigurationError")}constructor(e,n){super(e,n),this.name="ConfigurationError"}},wt=class extends I{static{s(this,"FeatureNotEnabledError")}constructor(e,n){super(e,n),this.name="FeatureNotEnabledError"}};var h=class t{static{s(this,"Environment")}config;static#e;static initialize(e,n){this.#e||(this.#e=new t(e,n))}static get instance(){if(!this.#e)throw new T("Environment has not been initialized");return this.#e}constructor(e,n){let r;try{if(n.__ZUPLO_CONFIG){let o=atob(n.__ZUPLO_CONFIG);r=JSON.parse(o)}}catch{console.warn("Failed to parse runtime configuration")}this.config=r??{},this.build=e,this.runtime=n}build;runtime;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useSha256ServiceRouting(){return this.config.use_sha256_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.dev"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.ENVIRONMENT_TYPE?this.build.ENVIRONMENT_TYPE==="LOCAL_DEVELOPMENT":!1}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}};Function.prototype.toString=function(){return"[native code]"};var Rt=globalThis,bo=Rt.caches;if(bo){let t=bo.open;Rt.caches.open=function(e){let n=h.instance.deploymentName??h.instance.build.BUILD_ID;return t.call(this,`${n}-${e}`)},delete Rt.caches.default,Object.freeze(Rt.caches)}var wo=new Map,Ln=class{static{s(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let n=this.#n.get(e);if(!n)return;let r=Date.now();if(r>n.expiresAt){this.#n.delete(e);return}return n.lastUsed=r,this.#o(),n?.data}put(e,n,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(),i={created:o,lastUsed:o,expiresAt:o+r*1e3,data:n};this.#r.push(e),this.#n.set(e,i)}delete(e){let n=this.#r.indexOf(e);n>=0&&this.#r.slice(n,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((n,r)=>{n.expiresAt>=e&&this.#n.delete(r)})}},Le=class{static{s(this,"MemoryCache")}constructor(e,n={maxSize:1e3}){this.name=e;let r=wo.get(e);r||(r=new Ln(n),wo.set(e,r)),this.#e=r}name;#e;get(e){return this.#e.get(e)}put(e,n,r){return this.#e.put(e,n,r)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var _n="__zuplo-expiry-header",de=class{static{s(this,"ZoneCache")}constructor(e,n){this.#t=e,this.#e=n}#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 n=await this.#r(),r=this.#o(e),o=await n.match(r);if(!o)return;let i=o.headers.get(_n);if(!i){try{await n.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(i);if(Date.now()>=a){try{await n.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(n){this.logDebug(n)}}async put(e,n,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(_n,`${Date.now()+r*1e3}`);let i=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(n),{headers:o});await i.put(a,u)}async delete(e){let n=await this.#r(),r=this.#o(e);try{await n.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 n=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});n.set(_n,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),i=new Response("",{headers:n});await r.put(o,i)}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 N=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,n){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Le(r),this.#n=new de(r,n),this.#r=n}#e;#t;#n;#r;async get(e){let n=this.#t.get(e);if(n)return n;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,n,r){this.#t.put(e,n,r);let o={data:n,expires:Date.now()+r*1e3},i=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(i)}};var Ro="zuplo-request-id",Ye="zp-rid",Po="zp-body-removed",_e="cf-ray",kn="cf-ipcity",Dn="cf-ipcontinent",Un="cf-ipcountry",Hn="cf-iplongitude",Mn="cf-iplatitude",Io="zp-ipcity",Eo="zp-ipcontinent",xo="zp-ipcountry",vo="zp-iplongitude",So="zp-iplatitude",To="true-client-ip",Nn="zp-asn",Zn="zp-asorg",qn="zp-colo",$n="zp-postalcode",Fn="zp-metrocode",Bn="zp-region",jn="zp-regioncode",zn="zp-timezone",Oo=[kn,Dn,Un,Hn,Mn,Nn,Zn,qn,$n,Fn,Bn,jn,zn],Co=["x-b3-sampled","x-b3-spanid","x-b3-traceid","x-envoy-attempt-count","x-envoy-decorator-operation","x-envoy-external-address","x-envoy-peer-metadata","x-envoy-peer-metadata-id","k-proxy-request","fly-client-ip","fly-forwarded-port","fly-forwarded-proto","fly-forwarded-ssl","fly-region","fly-request-id","fly-traceparent","fly-tracestate"],Qe="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49";var Si=Ae(Pe());var et=class t{static{s(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let n=e.problem,r=JSON.stringify(n,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(t.problemResponseFormat=(n,r,o)=>{try{return e(n,r,o)}catch(i){throw new I("Error in custom 'problemResponseFormat'",{cause:i})}})}},ge=class{static{s(this,"ProblemResponseFormatter")}static async format(e,n,r){return await et.problemResponseFormat(e,n,r)}};function Tt(t){for(let e in t){let n=t[e];n&&typeof n=="object"&&Tt(n)}return Object.freeze(t)}s(Tt,"deepFreeze");var L=class t extends Request{static{s(this,"ZuploRequest")}#e=void 0;#t;constructor(e,n){super(e,n);let r=n?.params;r?this.#t=r:e instanceof t?this.#t=e.#t:this.#t={};let o=n?.user;o?this.user=o:e instanceof t&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},n=new URL(this.url).searchParams;for(let[r,o]of n.entries())e[r]=o;this.#e=e}return Tt(this.#e)}get params(){return Tt(this.#t)}user};var Ie=class{static{s(this,"RuntimePlugin")}},ae=class extends Ie{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,n){}},tt={},fe=[],Wo=[],Ko=[],Jo=[];var Ot={addPlugin(t){fe.push(t)},addRequestHook(t){Wo.push(t)},addResponseSendingHook(t){Ko.push(t)},addResponseSendingFinalHook(t){Jo.push(t)}},Yo=s(async(t,e)=>{let n=t;for(let r of Wo){let o=await r(n,e);if(o instanceof L)n=o;else{if(o instanceof Response)return o;throw new g(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof n}.`)}}return n},"invokeOnRequestExtensions"),Qo=s(async(t,e,n)=>{let r=t;for(let o of Ko){let i=await o(t,e,n);if(i instanceof Response)r=i;else throw new g(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof r}.`)}return r},"invokeOnResponseSendingExtensions"),Xo=s(async(t,e,n)=>{for(let r of Jo)await r(t,e,n)},"invokeOnResponseSendingFinalExtensions");async function ei(t=()=>Promise.resolve()){await t(Ot),tt.value=Ot;for(let e of fe)e instanceof ae&&await e.initialize(Ot);et.setProblemResponseFormat(Ot.problemResponseFormat)}s(ei,"initializeRuntime");var Ct={Json:"application/json",Form:"application/x-www-form-urlencoded"};function At(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(Ct.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(Ct.Json)||!e?JSON.stringify(t):t}s(At,"serialize");function nt(t){return Z.instance.runtimeSettings.developerPortal.enabled&&t.pathname.startsWith(Z.instance.runtimeSettings.developerPortal.sitePathname)||t.pathname.startsWith("/__zuplo/")}s(nt,"isSystemRoute");var U=class{static{s(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,n)=>async(r,o)=>{try{return await e(r,o)}catch(i){return o.log.error("Error executing request handler.",i),n.errorHandler(r,o,i)}};#t=({processors:e,gateway:n,handler:r})=>async(o,i)=>{let a=[...e],u=s(async P=>{let E=a.pop();return E?E(o,i,n,u):await this.#e(async A=>{let H=await r(A,i);return Nu(H)},n)(P,i)},"nextPipe"),l=await u(o),d=new URL(o.url);if(nt(d)&&h.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new ke(o,l);i.dispatchEvent(p);let y=B.getContextExtensions(i),m=y.latestRequest,w;try{w=await p.mutableResponse}catch(P){return i.log.error(P),n.errorHandler(o,i,P)}try{w=await y.onResponseSending(w,m,i)}catch(P){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),n.errorHandler(o,i,P)}try{w=await Qo(w,m,i)}catch(P){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),n.errorHandler(o,i,P)}i.dispatchEvent(new De(o,w));try{await y.onResponseSendingFinal(l,m,i)}catch(P){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}try{await Xo(l,m,i)}catch(P){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}return w}};function Nu(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response(At(t),{headers:{"content-type":"application/json"}})}s(Nu,"resultToResponse");var he=class extends Ie{static{s(this,"MetricsPlugin")}};var O=class t{static{s(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let n=t.#e.get(e);if(!n){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new T(r)}return n}static addLogger(e,n){t.#e.set(e,n)}};var C=class{static{s(this,"BatchDispatch")}constructor(e,n,r,o){this.#t=e,this.#i=n,this.#r=r,this.#n=o}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=e=>{this.#o.push(e),this.#e||(this.#e=new Promise(n=>{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&&this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{n()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var Lt=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=h.instance.loggingId,this.#e=e,this.#t=new C("ellie-metrics-transport",10,this.dispatchFunction,O.getLogger(e))}pushMetrics(e,n){this.#n!==void 0&&(this.#t.enqueue(e),n.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let n,{loggingId:r,remoteLogURL:o,deploymentName:i}=h.instance,a=e.map(u=>{let c=Object.assign({},u);return delete c.requestContentLength,delete c.responseContentLength,c});if(r&&i&&(n=`${o}/v1-alpha/metrics?loggingId=${encodeURI(r)}&deploymentName=${encodeURI(i)}`),n){let u=await fetch(n,{method:"POST",body:JSON.stringify(a),headers:{"content-type":"application/json","zp-dn":h.instance.deploymentName??"unknown","user-agent":h.instance.systemUserAgent}});if(!u.ok){let c=await u.text();O.getLogger(this.#e).error(`Metrics POST responded ${u.status}: ${u.statusText}`,c)}}}};var k=class{static{s(this,"SystemRouteConfiguration")}constructor({label:e,path:n,methods:r,systemRouteName:o,corsPolicy:i="none"}){this.label=e,this.path=n,this.methods=r,this.corsPolicy=i,this.version=rt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},rt={name:"__system-no-version",pathPrefix:""};var j=s(async(t,e,n,r)=>{let o=new Date,i=Date.now(),a=await r(t),u=t.headers.get(_e)??void 0,c=t.headers.get(To)??void 0,l=e.incomingRequestProperties,d;e.route instanceof k&&(d=e.route.systemRouteName);let p=B.getContextExtensions(e).latestRequest,y={timestamp:o,statusCode:a.status,durationMs:Date.now()-i,requestContentLength:t.headers.get("content-length")?Number(t.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:t.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:n.instanceId,userSub:p.user?.sub,clientIp:c},m=[];return m.push(new Lt(e)),fe.forEach(w=>{if(w instanceof he){let P=w.getTransport();m.push(P)}}),m.forEach(w=>{w.pushMetrics(y,e)}),a},"metricsProcessor");var re=(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))(re||{});var er=s((t,e)=>{let n=s(async(i,a)=>{let c=new URL(i.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return R.notFound(i,a);let l=h.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=i.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&O.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new U({processors:[j],handler:n,gateway:e}),o=new k({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});t.addRoute(o,r.execute)},"registerBuildRoute");var _t=(f=>(f[f.CONTINUE=100]="CONTINUE",f[f.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",f[f.PROCESSING=102]="PROCESSING",f[f.EARLY_HINTS=103]="EARLY_HINTS",f[f.OK=200]="OK",f[f.CREATED=201]="CREATED",f[f.ACCEPTED=202]="ACCEPTED",f[f.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",f[f.NO_CONTENT=204]="NO_CONTENT",f[f.RESET_CONTENT=205]="RESET_CONTENT",f[f.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",f[f.MULTI_STATUS=207]="MULTI_STATUS",f[f.ALREADY_REPORTED=208]="ALREADY_REPORTED",f[f.IM_USED=226]="IM_USED",f[f.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",f[f.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",f[f.FOUND=302]="FOUND",f[f.SEE_OTHER=303]="SEE_OTHER",f[f.NOT_MODIFIED=304]="NOT_MODIFIED",f[f.USE_PROXY=305]="USE_PROXY",f[f.SWITCH_PROXY=306]="SWITCH_PROXY",f[f.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",f[f.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",f[f.BAD_REQUEST=400]="BAD_REQUEST",f[f.UNAUTHORIZED=401]="UNAUTHORIZED",f[f.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",f[f.FORBIDDEN=403]="FORBIDDEN",f[f.NOT_FOUND=404]="NOT_FOUND",f[f.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",f[f.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",f[f.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",f[f.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",f[f.CONFLICT=409]="CONFLICT",f[f.GONE=410]="GONE",f[f.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",f[f.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",f[f.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",f[f.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",f[f.URI_TOO_LONG=414]="URI_TOO_LONG",f[f.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",f[f.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",f[f.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",f[f.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",f[f.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",f[f.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",f[f.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",f[f.LOCKED=423]="LOCKED",f[f.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",f[f.TOO_EARLY=425]="TOO_EARLY",f[f.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",f[f.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",f[f.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",f[f.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",f[f.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",f[f.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",f[f.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",f[f.BAD_GATEWAY=502]="BAD_GATEWAY",f[f.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",f[f.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",f[f.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",f[f.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",f[f.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",f[f.LOOP_DETECTED=508]="LOOP_DETECTED",f[f.NOT_EXTENDED=510]="NOT_EXTENDED",f[f.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",f))(_t||{}),ti={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 Zu={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"},kt=Zu;function qu(t){return`${new URL(t.url).pathname}`}s(qu,"instance");function $u(t,e){let n={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:h.instance.build.BUILD_ID},r=t.headers.get(_e);return r&&(n.rayId=r),n}s($u,"trace");var Fu=s((t,e,n,r,o)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:qu(e),trace:$u(e,n),...r},additionalHeaders:o,statusText:kt[t.status]}),"merge"),tr=class{static{s(this,"HttpProblemsBase")}static format=(e,n,r)=>"problem"in e?ge.format(e,n,r):ge.format({problem:e},n,r);static getProblemFromStatus(e,n){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:ti[e],...n}}},R=class extends tr{static{s(this,"HttpProblems")}static#e(e,n,r,o,i){let a=Fu(this.getProblemFromStatus(e),n,r,o,i);return ge.format(a,n,r)}static continue=(e,n,r,o)=>this.#e(200,e,n,r,o);static switchingProtocols=(e,n,r,o)=>this.#e(101,e,n,r,o);static processing=(e,n,r,o)=>this.#e(102,e,n,r,o);static earlyHints=(e,n,r,o)=>this.#e(103,e,n,r,o);static ok=(e,n,r,o)=>this.#e(200,e,n,r,o);static created=(e,n,r,o)=>this.#e(201,e,n,r,o);static accepted=(e,n,r,o)=>this.#e(202,e,n,r,o);static nonAuthoritativeInformation=(e,n,r,o)=>this.#e(203,e,n,r,o);static noContent=(e,n,r,o)=>this.#e(204,e,n,r,o);static resetContent=(e,n,r,o)=>this.#e(205,e,n,r,o);static partialContent=(e,n,r,o)=>this.#e(206,e,n,r,o);static multiStatus=(e,n,r,o)=>this.#e(207,e,n,r,o);static alreadyReported=(e,n,r,o)=>this.#e(208,e,n,r,o);static imUsed=(e,n,r,o)=>this.#e(226,e,n,r,o);static multipleChoices=(e,n,r,o)=>this.#e(300,e,n,r,o);static movedPermanently=(e,n,r,o)=>this.#e(301,e,n,r,o);static found=(e,n,r,o)=>this.#e(302,e,n,r,o);static seeOther=(e,n,r,o)=>this.#e(303,e,n,r,o);static notModified=(e,n,r,o)=>this.#e(304,e,n,r,o);static useProxy=(e,n,r,o)=>this.#e(305,e,n,r,o);static switchProxy=(e,n,r,o)=>this.#e(306,e,n,r,o);static temporaryRedirect=(e,n,r,o)=>this.#e(307,e,n,r,o);static permanentRedirect=(e,n,r,o)=>this.#e(308,e,n,r,o);static badRequest=(e,n,r,o)=>this.#e(400,e,n,r,o);static unauthorized=(e,n,r,o)=>this.#e(401,e,n,r,o);static paymentRequired=(e,n,r,o)=>this.#e(402,e,n,r,o);static forbidden=(e,n,r,o)=>this.#e(403,e,n,r,o);static notFound=(e,n,r,o)=>this.#e(404,e,n,r,o);static methodNotAllowed=(e,n,r,o)=>this.#e(405,e,n,r,o);static notAcceptable=(e,n,r,o)=>this.#e(406,e,n,r,o);static proxyAuthenticationRequired=(e,n,r,o)=>this.#e(407,e,n,r,o);static requestTimeout=(e,n,r,o)=>this.#e(408,e,n,r,o);static conflict=(e,n,r,o)=>this.#e(409,e,n,r,o);static gone=(e,n,r,o)=>this.#e(410,e,n,r,o);static lengthRequired=(e,n,r,o)=>this.#e(411,e,n,r,o);static preconditionFailed=(e,n,r,o)=>this.#e(412,e,n,r,o);static contentTooLarge=(e,n,r,o)=>this.#e(413,e,n,r,o);static uriTooLong=(e,n,r,o)=>this.#e(414,e,n,r,o);static unsupportedMediaType=(e,n,r,o)=>this.#e(415,e,n,r,o);static rangeNotSatisfiable=(e,n,r,o)=>this.#e(416,e,n,r,o);static expectationFailed=(e,n,r,o)=>this.#e(417,e,n,r,o);static imATeapot=(e,n,r,o)=>this.#e(418,e,n,r,o);static misdirectedRequest=(e,n,r,o)=>this.#e(421,e,n,r,o);static unprocessableContent=(e,n,r,o)=>this.#e(422,e,n,r,o);static locked=(e,n,r,o)=>this.#e(423,e,n,r,o);static failedDependency=(e,n,r,o)=>this.#e(424,e,n,r,o);static tooEarly=(e,n,r,o)=>this.#e(425,e,n,r,o);static upgradeRequired=(e,n,r,o)=>this.#e(426,e,n,r,o);static preconditionRequired=(e,n,r,o)=>this.#e(428,e,n,r,o);static tooManyRequests=(e,n,r,o)=>this.#e(429,e,n,r,o);static requestHeaderFieldsTooLarge=(e,n,r,o)=>this.#e(431,e,n,r,o);static unavailableForLegalReasons=(e,n,r,o)=>this.#e(451,e,n,r,o);static internalServerError=(e,n,r,o)=>this.#e(500,e,n,r,o);static notImplemented=(e,n,r,o)=>this.#e(501,e,n,r,o);static badGateway=(e,n,r,o)=>this.#e(502,e,n,r,o);static serviceUnavailable=(e,n,r,o)=>this.#e(503,e,n,r,o);static gatewayTimeout=(e,n,r,o)=>this.#e(504,e,n,r,o);static httpVersionNotSupported=(e,n,r,o)=>this.#e(505,e,n,r,o);static variantAlsoNegotiates=(e,n,r,o)=>this.#e(506,e,n,r,o);static insufficientStorage=(e,n,r,o)=>this.#e(507,e,n,r,o);static loopDetected=(e,n,r,o)=>this.#e(508,e,n,r,o);static notExtended=(e,n,r,o)=>this.#e(510,e,n,r,o);static networkAuthenticationRequired=(e,n,r,o)=>this.#e(511,e,n,r,o)};var{toString:Bu}=Object.prototype,{propertyIsEnumerable:ju}=Object.prototype;function nr(t){return Bu.call(t)}s(nr,"toString");function W(t){return typeof t=="string"}s(W,"isString");function Ue(t){return W(t)&&t!==""}s(Ue,"isNonEmptyString");function ni(t){return nr(t)==="[object RegExp]"}s(ni,"isRegexp");function ri(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>ju.call(t,e))]}s(ri,"getOwnEnumerableKeys");function Ee(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof RegExp)&&!(t instanceof Date)}s(Ee,"isObject");function rr(t){return typeof t=="number"&&!isNaN(t)}s(rr,"isNumber");function or(t){return t===!0||t===!1}s(or,"isBoolean");function oi(t){return typeof t>"u"}s(oi,"isUndefined");function ii(t){return oi(t)||t===null}s(ii,"isUndefinedOrNull");function ot(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}s(ot,"isErrorLike");var si=new Map;function Dt(t){if(typeof t!="string")throw new Error("Input must be a string");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(t))throw new Error("Malformed input string");let e=si.get(t);if(e)return e;let n=t.split(","),r=[];for(let o of n){let i=o.split("-");if(i.length===2){let a=parseInt(i[0],10),u=parseInt(i[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return si.set(t,r),r}s(Dt,"statusCodesStringToNumberArray");function xe(t,e,n){if(!e.startsWith("."))throw new g(`Invalid ${n} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=t;return r.forEach(i=>{if(o===void 0)throw new I(`Error applying ${n} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(xe,"getValueFromRequestUser");function ve(t){if(Array.isArray(t)){if(t.includes(n=>typeof n!="string"))throw new g("Received an array that contains non-string values.");return t}if(W(t))return t.includes(",")?t.split(",").map(n=>n.trim()).filter(n=>n!==","&&n!==""):[t];throw new g(`Expected type of string, received type '${typeof t}'`)}s(ve,"parseValueToStringArray");function ai(t){if(t==null)return[];if(!Array.isArray(t))throw new g(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof t}'`);return t.map(n=>{if(!Ee(n))throw new g(`Invalid custom cors policy is set. Expected an object, received '${typeof n}'`);if(!Ue(n.name))throw new g("Value of 'name' on custom cors policies must be a non-empty string.");if(n.maxAge!==void 0&&!rr(n.maxAge))throw new g(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof n.maxAge}'`);if(n.allowCredentials!==void 0&&!or(n.allowCredentials))throw new g("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let r=ir(n,"allowedHeaders"),o=ir(n,"allowedMethods"),i=ir(n,"exposeHeaders"),a;try{a=ve(n.allowedOrigins)}catch(c){throw new g(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:n.name,allowCredentials:typeof n.allowCredentials=="boolean"?String(n.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:r?r.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:i?i.join(", "):void 0,maxAge:typeof n.maxAge=="number"?n.maxAge.toString():void 0}})}s(ai,"parseCorsPolicies");function ir(t,e){let n;if(t[e]!==void 0)try{n=ve(t[e])}catch(r){throw new g(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return n}s(ir,"parseOptionalProperty");var Ut=s((t,e)=>{if(e===null)return;if(t.find(a=>a==="*"))return e;let r=t.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),Ht=s((t,e)=>{let n={"access-control-allow-origin":e};t.allowedHeaders&&(n["access-control-allow-headers"]=t.allowedHeaders),t.allowedMethods&&(n["access-control-allow-methods"]=t.allowedMethods),t.exposeHeaders&&(n["access-control-expose-headers"]=t.exposeHeaders);let r=t.allowCredentials;r&&(n["access-control-allow-credentials"]=r);let o=t.maxAge?.toString()??void 0;return o&&(n["access-control-max-age"]=o),n},"generateCorsHeaders");var sr=s((t,e)=>{let n=e.routeData.corsPolicies,r=s(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 R.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let y=t.lookup(l,c);if(!y)return R.notFound(a,u);let m=y.routeConfiguration,w=zu(l,d,p,m,n);return w.isValid?new Response(void 0,{status:200,statusText:"OK",headers:w.headers}):(w.error&&u.log.warn(w.error),R.notFound(a,u))},"optionsHandler"),o=new U({processors:[j],handler:r,gateway:e}),i=new k({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});t.addRoute(i,o.execute)},"registerCorsRoute"),zu=s((t,e,n,r,o)=>{let i={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":n,"access-control-allow-methods":t,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...i,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new g(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=Ut(a.allowedOrigins,n);return u?{isValid:!0,headers:Ht(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${n}'`}},"validateAndBuildResponseHeaders");var ui=s((t,e)=>{let n=s(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new U({processors:[j],handler:n,gateway:e}),o=new k({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});t.addRoute(o,r.execute)},"registerNoRoutes");var ar=new k({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),ci=s((t,e)=>{let n=s(async(o,i)=>{let a=tt.value?.notFoundHandler;if(a){let u=B.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return R.notFound(o,i)},"notFoundHandler"),r=new U({processors:[j],handler:n,gateway:e});t.addRoute(ar,r.execute)},"registerNotMatchedHandler");var Vu=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],li=s(t=>{Vu.forEach(e=>t.delete(e))},"stripCorsHeaders"),Mt=s(async(t,e,n,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await r(t),p=new Headers(d.headers);return li(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let i=await r(t);if(!(i instanceof Response))throw new T(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=Gu(o,n.routeData.corsPolicies),u=Wu(t,a),c=new Headers(i.headers);return li(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(i.body,{status:i.status,statusText:i.statusText,headers:c,webSocket:i.webSocket})},"corsProcessor"),Gu=s((t,e)=>{if(t.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:t.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let n=e?.find(r=>r.name===t.corsPolicy);if(n===void 0)throw new g(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return n},"getCorsPolicy"),Wu=s((t,e)=>{let n=Ut(e.allowedOrigins,t.headers.get("origin"));return n?Ht(e,n):{}},"getCorsHeaders");var ur=s((t,e)=>{let n=s(async()=>new Response(null,{status:200}),"pingRouteHandler"),r=new U({processors:[Mt],handler:n,gateway:e}),o=new k({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});t.addRoute(o,r.execute)},"registerPingRoute");var Nt=class{static{s(this,"PolicyBase")}options;policyName;constructor(e,n){if(!W(n))throw new I(`The name of a policy must be a string. Received '${n}' of type '${typeof n}'`);this.options=e,this.policyName=n}},ue=class extends Nt{static{s(this,"InboundPolicy")}},Se=class extends Nt{static{s(this,"OutboundPolicy")}};var dr=class extends ue{static{s(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,n,r){super(n,r),this.#e=e}handler(e,n){return this.#e(e,n,this.options,this.policyName)}},pr=class extends Se{static{s(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,n,r){super(n,r),this.#e=e}handler(e,n,r){return this.#e(e,n,r,this.options,this.policyName)}},cr=new Map;function it(t,e){let n,r;return Array.isArray(t)?n=t:(n=t.policies?.inbound??[],r=t.path),n.filter(i=>!cr.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new g(`Invalid state - no Policy with the name '${i}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new g(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new g(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new g(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof ue)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new dr(u,a.handler.options,a.name);else throw new g(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new g(`Invalid state - invalid handler on policy '${i}' on route '${r}' (typeof handler '${typeof c.handler}')`);cr.set(a.name,c)}),n.map(i=>{let a=cr.get(i);if(a===void 0)throw new I("Internal error. Policy not found in cache.");return a})}s(it,"getInboundPolicyInstances");var lr=new Map;function Ku(t,e){let n=t.policies?.outbound??[];return n.filter(o=>!lr.has(o)).forEach(o=>{let i=e?.find(c=>c.name===o);if(!i)throw new g(`Invalid state - no Policy with the name '${o}' on route '${t.path}' was found in the policies configuration (check case).`);if(typeof i.handler?.module!="object")throw new g(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof policy '${typeof i.handler?.module}')`);let a=i.handler?.module[i.handler.export],u;if(typeof a!="function")throw new g(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof Se)u=new a(i.handler.options,i.name);else if(typeof a=="function")u=new pr(a,i.handler.options,i.name);else throw new g(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new g(`Invalid state - invalid handler on policy '${o}' on route '${t.path}'`);lr.set(i.name,u)}),n.map(o=>{let i=lr.get(o);if(i===void 0)throw new I("Internal error. Policy not found in cache.");return i})}s(Ku,"getOutboundPolicyInstances");var mr=s(t=>async(e,n)=>{let r=B.getContextExtensions(n),o=[...t],i=e;for(;o.length>0;){let a=o.shift();if(!a)return i;let u=await a.handler(i,n);if(u instanceof L)i=u;else if(u instanceof Request)i=new L(u);else{if(u instanceof Response)return u;throw new g(`Invalid state - invalid handler on policy '${a.policyName}' on route '${n.route.path}. The result of an inbound policy must be a Response or Request.`)}r.latestRequest=i}return i},"toStackedInboundHandler"),Ju=s(t=>async(e,n,r)=>{let o=[...t],i=e;for(;o.length>0;){let a=o.shift();if(!a)return i;let u=await a.handler(i,n,r);if(!(u instanceof Response))throw new g(`Invalid state - invalid handler on policy '${a.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);i=u}return i},"toStackedOutboundHandler"),Zt=s(async(t,e,n,r)=>{let o=it(e.route,n.routeData.policies),i=Ku(e.route,n.routeData.policies);return pi({request:t,context:e,inboundPolicies:o,outboundPolicies:i,gateway:n,next:r})},"policyProcessor");function di({inboundPolicies:t=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>pi({request:r,context:o,inboundPolicies:t,outboundPolicies:e,gateway:i,next:a}),"policyProcessor")}s(di,"createInternalPolicyProcessor");async function pi({request:t,context:e,inboundPolicies:n,outboundPolicies:r,gateway:o,next:i}){let a=mr(n);try{let u=await a(t,e);if(u instanceof Response)return u;let c=await i(u),l=Ju(r),d;return h.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,t,e):d=c.ok?l(c,t,e):c,d}catch(u){return e.log.error(u),o.errorHandler(t,e,u)}}s(pi,"executePolicyProcessor");function mi(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");let n={},o=(e||{}).decode||Yu,i=0;for(;i<t.length;){let a=t.indexOf("=",i);if(a===-1)break;let u=t.indexOf(";",i);if(u===-1)u=t.length;else if(u<a){i=t.lastIndexOf(";",a-1)+1;continue}let c=t.slice(i,a).trim();if(n[c]===void 0){let l=t.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),n[c]=Qu(l,o)}i=u+1}return n}s(mi,"parse");function Yu(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}s(Yu,"decode");function Qu(t,e){try{return e(t)}catch{return t}}s(Qu,"tryDecode");function gi(t,e){try{let n=/v\d+(-\d+)?/g,o=mi(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&n.test(o)?`https://dev-portal-${o}.zuplo.com`:t}catch{}return t}s(gi,"devPortalBaseURL");var fi="/__zuplo/dev-portal",Xu="dev-portal-id",ec="dev-portal-host",tc="zp-account",nc="zp-project",rc="dev-portal-build",oc=`
35
+ `)+" "+n[1]:n[0]+e+" "+t.join(", ")+" "+n[1]}s(ku,"reduceToSingleString")});var Vo=Je(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.format=void 0;var Du=Zo(),Uu=zo(),Hu=s((t,...e)=>(0,Du.format)(Uu.inspect,t,e),"format");xt.format=Hu});var Pe=Je(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.debug=pe.withoutEnv=pe.Debugger=void 0;var Mu=No(),Nu=Vo(),vt=class{static{s(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,n){this.manager=e,this.ns=n,this.color=(0,Mu.generateColor)(n),this.last=0,this.enabled=e.enabled.some(r=>r.test(n))}log(...e){if(!this.enabled)return;let n,r=e[0];typeof r=="function"?n=r():n=String(r);let o=Date.now()-(this.last||Date.now());n=(0,Nu.format)(n,...e);let i=`${this.color(this.ns)} ${n} ${this.color(`+${o}ms`)}`;console.log(i),this.last=Date.now()}};pe.Debugger=vt;var St=class{static{s(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function Go(t){return!t||t.length===0?[]:(t=t.replace(/\s/g,"").replace(/\*/g,".+"),t.split(",").map(e=>new RegExp(`^${e}$`)))}s(Go,"extract");var Qe;function Zu(t){t||(t=[]),typeof t=="string"&&(t=Go(t)),Qe=new St(t)}s(Zu,"withoutEnv");pe.withoutEnv=Zu;function qu(t){let e=globalThis.DEBUG;Qe||(Qe=new St(Go(e)));let n=new vt(Qe,t);return Qe.debuggers.set(t,n),Object.assign(n.log.bind(n),{self:n})}s(qu,"debug");pe.debug=qu});var Zl={};ka(Zl,{API_KEY:()=>bi,AWSLoggingPlugin:()=>un,AmberfloMeteringInboundPolicy:()=>ps,AmberfloMeteringPolicy:()=>fn,ApiAuthKeyInboundPolicy:()=>fs,ApiKeyInboundPolicy:()=>yn,AuditLogDataStaxProvider:()=>dn,AuditLogPlugin:()=>pn,Auth0JwtInboundPolicy:()=>hs,AwsLambdaHandlerExtensions:()=>Vi,BasicAuthInboundPolicy:()=>ys,BasicRateLimitInboundPolicy:()=>so,CachingInboundPolicy:()=>bs,ChangeMethodInboundPolicy:()=>ws,ClearHeadersInboundPolicy:()=>Rs,ClearHeadersOutboundPolicy:()=>Ps,ClerkJwtInboundPolicy:()=>Is,CognitoJwtInboundPolicy:()=>Es,CompositeInboundPolicy:()=>xs,ConfigurationError:()=>m,ContentTypes:()=>Ct,ContextData:()=>ye,CryptoBeta:()=>Tn,CurityPhantomTokenInboundPolicy:()=>vs,DataDogLoggingPlugin:()=>Gt,DataDogMetricsPlugin:()=>cn,DynaTraceLoggingPlugin:()=>rn,DynatraceMetricsPlugin:()=>ln,FirebaseJwtInboundPolicy:()=>Ss,FormDataToJsonInboundPolicy:()=>Ts,GeoFilterInboundPolicy:()=>Os,GoogleCloudLoggingPlugin:()=>jt,Handler:()=>tn,HttpProblems:()=>R,HttpStatusCode:()=>_t,InboundPolicy:()=>ue,JWTScopeValidationInboundPolicy:()=>Cs,KeyValueStore:()=>Cn,LokiLoggingPlugin:()=>on,LookupResult:()=>Me,MemoryZoneReadThroughCache:()=>M,MockApiInboundPolicy:()=>Hs,MoesifInboundPolicy:()=>Fs,MonetizationInboundPolicy:()=>Ds,OktaJwtInboundPolicy:()=>Bs,OpenIdJwtInboundPolicy:()=>q,OutboundPolicy:()=>Se,ProblemResponseFormatter:()=>me,PropelAuthJwtInboundPolicy:()=>zs,RateLimitInboundPolicy:()=>so,ReadmeMetricsInboundPolicy:()=>Js,RemoveHeadersInboundPolicy:()=>Ys,RemoveHeadersOutboundPolicy:()=>Qs,RemoveQueryParamsInboundPolicy:()=>Xs,ReplaceStringOutboundPolicy:()=>ea,RequestSizeLimitInboundPolicy:()=>na,RequestValidationInboundPolicy:()=>co,RequireOriginInboundPolicy:()=>la,ResponseSendingEvent:()=>ke,ResponseSentEvent:()=>De,Router:()=>Ne,RuntimeError:()=>P,SYSTEM_LOGGER:()=>it,SchemaBasedRequestValidation:()=>ca,ServiceProviderImpl:()=>vn,SetBodyInboundPolicy:()=>da,SetHeadersInboundPolicy:()=>pa,SetHeadersOutboundPolicy:()=>ma,SetQueryParamsInboundPolicy:()=>ga,SetStatusOutboundPolicy:()=>fa,SleepInboundPolicy:()=>ha,StripeMeteringPlugin:()=>Qr,StripeWebhookVerificationInboundPolicy:()=>Be,SumoLogicLoggingPlugin:()=>sn,SupabaseJwtInboundPolicy:()=>ya,SystemLogMap:()=>O,SystemRouteName:()=>re,UpstreamAzureAdServiceAuthInboundPolicy:()=>ba,UpstreamFirebaseAdminAuthInboundPolicy:()=>Ra,UpstreamFirebaseUserAuthInboundPolicy:()=>Pa,UpstreamGcpJwtInboundPolicy:()=>Ia,UpstreamGcpServiceAuthInboundPolicy:()=>xa,VMWareLogInsightLoggingPlugin:()=>an,ValidateJsonSchemaInbound:()=>va,ZoneCache:()=>le,ZuploRequest:()=>A,awsLambdaHandler:()=>Gi,environment:()=>j,getIdForParameterSchema:()=>En,getIdForRefSchema:()=>oa,getIdForRequestBodySchema:()=>xn,getRawOperationDataIdentifierName:()=>ra,httpStatuses:()=>kt,isRestrictedEnvVariableName:()=>xr,isZuploReadableEnvVariableName:()=>vr,openApiSpecHandler:()=>Wi,originalFetch:()=>Ze,purgeGatewayCache:()=>Ui,redirectHandler:()=>Ki,sanitizedIdentifierName:()=>we,serialize:()=>At,setMoesifContext:()=>$s,urlForwardHandler:()=>Ji,urlRewriteHandler:()=>Yi,webSocketHandler:()=>Qi,webSocketPipelineHandler:()=>ts});module.exports=Da(Zl);var T=class extends Error{static{s(this,"SystemError")}constructor(e,n){super(e,n),this.name="InternalError"}},P=class extends Error{static{s(this,"RuntimeError")}extensionMembers;constructor(e,n){typeof e=="string"?super(e,n):(super(e.message,n),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},m=class extends P{static{s(this,"ConfigurationError")}constructor(e,n){super(e,n),this.name="ConfigurationError"}},bt=class extends P{static{s(this,"FeatureNotEnabledError")}constructor(e,n){super(e,n),this.name="FeatureNotEnabledError"}};var h=class t{static{s(this,"Environment")}config;static#e;static initialize(e,n){this.#e||(this.#e=new t(e,n))}static get instance(){if(!this.#e)throw new T("Environment has not been initialized");return this.#e}constructor(e,n){let r;try{if(n.__ZUPLO_CONFIG){let o=atob(n.__ZUPLO_CONFIG);r=JSON.parse(o)}}catch{console.warn("Failed to parse runtime configuration")}this.config=r??{},this.build=e,this.runtime=n}build;runtime;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useSha256ServiceRouting(){return this.config.use_sha256_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.dev"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.ENVIRONMENT_TYPE?this.build.ENVIRONMENT_TYPE==="LOCAL_DEVELOPMENT":!1}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}};Function.prototype.toString=function(){return"[native code]"};var wt=globalThis,bo=wt.caches;if(bo){let t=bo.open;wt.caches.open=function(e){let n=h.instance.deploymentName??h.instance.build.BUILD_ID;return t.call(this,`${n}-${e}`)},delete wt.caches.default,Object.freeze(wt.caches)}var wo=new Map,Ln=class{static{s(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let n=this.#n.get(e);if(!n)return;let r=Date.now();if(r>n.expiresAt){this.#n.delete(e);return}return n.lastUsed=r,this.#o(),n?.data}put(e,n,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(),i={created:o,lastUsed:o,expiresAt:o+r*1e3,data:n};this.#r.push(e),this.#n.set(e,i)}delete(e){let n=this.#r.indexOf(e);n>=0&&this.#r.slice(n,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((n,r)=>{n.expiresAt>=e&&this.#n.delete(r)})}},Le=class{static{s(this,"MemoryCache")}constructor(e,n={maxSize:1e3}){this.name=e;let r=wo.get(e);r||(r=new Ln(n),wo.set(e,r)),this.#e=r}name;#e;get(e){return this.#e.get(e)}put(e,n,r){return this.#e.put(e,n,r)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var _n="__zuplo-expiry-header",le=class{static{s(this,"ZoneCache")}constructor(e,n){this.#t=e,this.#e=n}#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 n=await this.#r(),r=this.#o(e),o=await n.match(r);if(!o)return;let i=o.headers.get(_n);if(!i){try{await n.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(i);if(Date.now()>=a){try{await n.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(n){this.logDebug(n)}}async put(e,n,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(_n,`${Date.now()+r*1e3}`);let i=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(n),{headers:o});await i.put(a,u)}async delete(e){let n=await this.#r(),r=this.#o(e);try{await n.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 n=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});n.set(_n,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),i=new Response("",{headers:n});await r.put(o,i)}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 M=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,n){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Le(r),this.#n=new le(r,n),this.#r=n}#e;#t;#n;#r;async get(e){let n=this.#t.get(e);if(n)return n;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,n,r){this.#t.put(e,n,r);let o={data:n,expires:Date.now()+r*1e3},i=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(i)}};var Ro="zuplo-request-id",Ye="zp-rid",Po="zp-body-removed",_e="cf-ray",kn="cf-ipcity",Dn="cf-ipcontinent",Un="cf-ipcountry",Hn="cf-iplongitude",Mn="cf-iplatitude",Io="zp-ipcity",Eo="zp-ipcontinent",xo="zp-ipcountry",vo="zp-iplongitude",So="zp-iplatitude",To="true-client-ip",Nn="zp-asn",Zn="zp-asorg",qn="zp-colo",$n="zp-postalcode",Fn="zp-metrocode",Bn="zp-region",jn="zp-regioncode",zn="zp-timezone",Oo=[kn,Dn,Un,Hn,Mn,Nn,Zn,qn,$n,Fn,Bn,jn,zn],Co=["x-b3-sampled","x-b3-spanid","x-b3-traceid","x-envoy-attempt-count","x-envoy-decorator-operation","x-envoy-external-address","x-envoy-peer-metadata","x-envoy-peer-metadata-id","k-proxy-request","fly-client-ip","fly-forwarded-port","fly-forwarded-proto","fly-forwarded-ssl","fly-region","fly-request-id","fly-traceparent","fly-tracestate"],Rt="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49";var Si=Ae(Pe());var Xe=class t{static{s(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let n=e.problem,r=JSON.stringify(n,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(t.problemResponseFormat=(n,r,o)=>{try{return e(n,r,o)}catch(i){throw new P("Error in custom 'problemResponseFormat'",{cause:i})}})}},me=class{static{s(this,"ProblemResponseFormatter")}static async format(e,n,r){return await Xe.problemResponseFormat(e,n,r)}};function Tt(t){for(let e in t){let n=t[e];n&&typeof n=="object"&&Tt(n)}return Object.freeze(t)}s(Tt,"deepFreeze");var A=class t extends Request{static{s(this,"ZuploRequest")}#e=void 0;#t;constructor(e,n){super(e,n);let r=n?.params;r?this.#t=r:e instanceof t?this.#t=e.#t:this.#t={};let o=n?.user;o?this.user=o:e instanceof t&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},n=new URL(this.url).searchParams;for(let[r,o]of n.entries())e[r]=o;this.#e=e}return Tt(this.#e)}get params(){return Tt(this.#t)}user};var Ie=class{static{s(this,"RuntimePlugin")}},ae=class extends Ie{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,n){}},et={},ge=[],Wo=[],Ko=[],Jo=[];var Ot={addPlugin(t){ge.push(t)},addRequestHook(t){Wo.push(t)},addResponseSendingHook(t){Ko.push(t)},addResponseSendingFinalHook(t){Jo.push(t)}},Yo=s(async(t,e)=>{let n=t;for(let r of Wo){let o=await r(n,e);if(o instanceof A)n=o;else{if(o instanceof Response)return o;throw new m(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof n}.`)}}return n},"invokeOnRequestExtensions"),Qo=s(async(t,e,n)=>{let r=t;for(let o of Ko){let i=await o(t,e,n);if(i instanceof Response)r=i;else throw new m(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof r}.`)}return r},"invokeOnResponseSendingExtensions"),Xo=s(async(t,e,n)=>{for(let r of Jo)await r(t,e,n)},"invokeOnResponseSendingFinalExtensions");async function ei(t=()=>Promise.resolve()){await t(Ot),et.value=Ot;for(let e of ge)e instanceof ae&&await e.initialize(Ot);Xe.setProblemResponseFormat(Ot.problemResponseFormat)}s(ei,"initializeRuntime");var Ct={Json:"application/json",Form:"application/x-www-form-urlencoded"};function At(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(Ct.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(Ct.Json)||!e?JSON.stringify(t):t}s(At,"serialize");function tt(t){return N.instance.runtimeSettings.developerPortal.enabled&&t.pathname.startsWith(N.instance.runtimeSettings.developerPortal.sitePathname)||t.pathname.startsWith("/__zuplo/")}s(tt,"isSystemRoute");var D=class{static{s(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,n)=>async(r,o)=>{try{return await e(r,o)}catch(i){return o.log.error("Error executing request handler.",i),n.errorHandler(r,o,i)}};#t=({processors:e,gateway:n,handler:r})=>async(o,i)=>{let a=[...e],u=s(async I=>{let E=a.pop();return E?E(o,i,n,u):await this.#e(async L=>{let $=await r(L,i);return $u($)},n)(I,i)},"nextPipe"),l=await u(o),d=new URL(o.url);if(tt(d)&&h.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new ke(o,l);i.dispatchEvent(p);let b=F.getContextExtensions(i),g=b.latestRequest,w;try{w=await p.mutableResponse}catch(I){return i.log.error(I),n.errorHandler(o,i,I)}try{w=await b.onResponseSending(w,g,i)}catch(I){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${I.message}'`,I),n.errorHandler(o,i,I)}try{w=await Qo(w,g,i)}catch(I){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${I.message}'`,I),n.errorHandler(o,i,I)}i.dispatchEvent(new De(o,w));try{await b.onResponseSendingFinal(l,g,i)}catch(I){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${I.message}'`,I),I}try{await Xo(l,g,i)}catch(I){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${I.message}'`,I),I}return w}};function $u(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response(At(t),{headers:{"content-type":"application/json"}})}s($u,"resultToResponse");var fe=class extends Ie{static{s(this,"MetricsPlugin")}};var O=class t{static{s(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let n=t.#e.get(e);if(!n){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new T(r)}return n}static addLogger(e,n){t.#e.set(e,n)}};var C=class{static{s(this,"BatchDispatch")}constructor(e,n,r,o){this.#t=e,this.#i=n,this.#r=r,this.#n=o}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=e=>{this.#o.push(e),this.#e||(this.#e=new Promise(n=>{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&&this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{n()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var Lt=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=h.instance.loggingId,this.#e=e,this.#t=new C("ellie-metrics-transport",10,this.dispatchFunction,O.getLogger(e))}pushMetrics(e,n){this.#n!==void 0&&(this.#t.enqueue(e),n.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let n,{loggingId:r,remoteLogURL:o,deploymentName:i}=h.instance,a=e.map(u=>{let c=Object.assign({},u);return delete c.requestContentLength,delete c.responseContentLength,c});if(r&&i&&(n=`${o}/v1-alpha/metrics?loggingId=${encodeURI(r)}&deploymentName=${encodeURI(i)}`),n){let u=await fetch(n,{method:"POST",body:JSON.stringify(a),headers:{"content-type":"application/json","zp-dn":h.instance.deploymentName??"unknown","user-agent":h.instance.systemUserAgent}});if(!u.ok){let c=await u.text();O.getLogger(this.#e).error(`Metrics POST responded ${u.status}: ${u.statusText}`,c)}}}};var k=class{static{s(this,"SystemRouteConfiguration")}constructor({label:e,path:n,methods:r,systemRouteName:o,corsPolicy:i="none"}){this.label=e,this.path=n,this.methods=r,this.corsPolicy=i,this.version=nt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},nt={name:"__system-no-version",pathPrefix:""};var B=s(async(t,e,n,r)=>{let o=new Date,i=Date.now(),a=await r(t),u=t.headers.get(_e)??void 0,c=t.headers.get(To)??void 0,l=e.incomingRequestProperties,d;e.route instanceof k&&(d=e.route.systemRouteName);let p=F.getContextExtensions(e).latestRequest,b={timestamp:o,statusCode:a.status,durationMs:Date.now()-i,requestContentLength:t.headers.get("content-length")?Number(t.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:t.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:n.instanceId,userSub:p.user?.sub,clientIp:c},g=[];return g.push(new Lt(e)),ge.forEach(w=>{if(w instanceof fe){let I=w.getTransport();g.push(I)}}),g.forEach(w=>{w.pushMetrics(b,e)}),a},"metricsProcessor");var re=(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))(re||{});var er=s((t,e)=>{let n=s(async(i,a)=>{let c=new URL(i.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return R.notFound(i,a);let l=h.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=i.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&O.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new D({processors:[B],handler:n,gateway:e}),o=new k({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});t.addRoute(o,r.execute)},"registerBuildRoute");var _t=(f=>(f[f.CONTINUE=100]="CONTINUE",f[f.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",f[f.PROCESSING=102]="PROCESSING",f[f.EARLY_HINTS=103]="EARLY_HINTS",f[f.OK=200]="OK",f[f.CREATED=201]="CREATED",f[f.ACCEPTED=202]="ACCEPTED",f[f.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",f[f.NO_CONTENT=204]="NO_CONTENT",f[f.RESET_CONTENT=205]="RESET_CONTENT",f[f.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",f[f.MULTI_STATUS=207]="MULTI_STATUS",f[f.ALREADY_REPORTED=208]="ALREADY_REPORTED",f[f.IM_USED=226]="IM_USED",f[f.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",f[f.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",f[f.FOUND=302]="FOUND",f[f.SEE_OTHER=303]="SEE_OTHER",f[f.NOT_MODIFIED=304]="NOT_MODIFIED",f[f.USE_PROXY=305]="USE_PROXY",f[f.SWITCH_PROXY=306]="SWITCH_PROXY",f[f.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",f[f.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",f[f.BAD_REQUEST=400]="BAD_REQUEST",f[f.UNAUTHORIZED=401]="UNAUTHORIZED",f[f.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",f[f.FORBIDDEN=403]="FORBIDDEN",f[f.NOT_FOUND=404]="NOT_FOUND",f[f.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",f[f.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",f[f.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",f[f.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",f[f.CONFLICT=409]="CONFLICT",f[f.GONE=410]="GONE",f[f.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",f[f.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",f[f.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",f[f.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",f[f.URI_TOO_LONG=414]="URI_TOO_LONG",f[f.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",f[f.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",f[f.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",f[f.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",f[f.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",f[f.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",f[f.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",f[f.LOCKED=423]="LOCKED",f[f.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",f[f.TOO_EARLY=425]="TOO_EARLY",f[f.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",f[f.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",f[f.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",f[f.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",f[f.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",f[f.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",f[f.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",f[f.BAD_GATEWAY=502]="BAD_GATEWAY",f[f.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",f[f.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",f[f.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",f[f.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",f[f.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",f[f.LOOP_DETECTED=508]="LOOP_DETECTED",f[f.NOT_EXTENDED=510]="NOT_EXTENDED",f[f.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",f))(_t||{}),ti={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 Fu={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"},kt=Fu;function Bu(t){return`${new URL(t.url).pathname}`}s(Bu,"instance");function ju(t,e){let n={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:h.instance.build.BUILD_ID},r=t.headers.get(_e);return r&&(n.rayId=r),n}s(ju,"trace");var zu=s((t,e,n,r,o)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:Bu(e),trace:ju(e,n),...r},additionalHeaders:o,statusText:kt[t.status]}),"merge"),tr=class{static{s(this,"HttpProblemsBase")}static format=(e,n,r)=>"problem"in e?me.format(e,n,r):me.format({problem:e},n,r);static getProblemFromStatus(e,n){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:ti[e],...n}}},R=class extends tr{static{s(this,"HttpProblems")}static#e(e,n,r,o,i){let a=zu(this.getProblemFromStatus(e),n,r,o,i);return me.format(a,n,r)}static continue=(e,n,r,o)=>this.#e(200,e,n,r,o);static switchingProtocols=(e,n,r,o)=>this.#e(101,e,n,r,o);static processing=(e,n,r,o)=>this.#e(102,e,n,r,o);static earlyHints=(e,n,r,o)=>this.#e(103,e,n,r,o);static ok=(e,n,r,o)=>this.#e(200,e,n,r,o);static created=(e,n,r,o)=>this.#e(201,e,n,r,o);static accepted=(e,n,r,o)=>this.#e(202,e,n,r,o);static nonAuthoritativeInformation=(e,n,r,o)=>this.#e(203,e,n,r,o);static noContent=(e,n,r,o)=>this.#e(204,e,n,r,o);static resetContent=(e,n,r,o)=>this.#e(205,e,n,r,o);static partialContent=(e,n,r,o)=>this.#e(206,e,n,r,o);static multiStatus=(e,n,r,o)=>this.#e(207,e,n,r,o);static alreadyReported=(e,n,r,o)=>this.#e(208,e,n,r,o);static imUsed=(e,n,r,o)=>this.#e(226,e,n,r,o);static multipleChoices=(e,n,r,o)=>this.#e(300,e,n,r,o);static movedPermanently=(e,n,r,o)=>this.#e(301,e,n,r,o);static found=(e,n,r,o)=>this.#e(302,e,n,r,o);static seeOther=(e,n,r,o)=>this.#e(303,e,n,r,o);static notModified=(e,n,r,o)=>this.#e(304,e,n,r,o);static useProxy=(e,n,r,o)=>this.#e(305,e,n,r,o);static switchProxy=(e,n,r,o)=>this.#e(306,e,n,r,o);static temporaryRedirect=(e,n,r,o)=>this.#e(307,e,n,r,o);static permanentRedirect=(e,n,r,o)=>this.#e(308,e,n,r,o);static badRequest=(e,n,r,o)=>this.#e(400,e,n,r,o);static unauthorized=(e,n,r,o)=>this.#e(401,e,n,r,o);static paymentRequired=(e,n,r,o)=>this.#e(402,e,n,r,o);static forbidden=(e,n,r,o)=>this.#e(403,e,n,r,o);static notFound=(e,n,r,o)=>this.#e(404,e,n,r,o);static methodNotAllowed=(e,n,r,o)=>this.#e(405,e,n,r,o);static notAcceptable=(e,n,r,o)=>this.#e(406,e,n,r,o);static proxyAuthenticationRequired=(e,n,r,o)=>this.#e(407,e,n,r,o);static requestTimeout=(e,n,r,o)=>this.#e(408,e,n,r,o);static conflict=(e,n,r,o)=>this.#e(409,e,n,r,o);static gone=(e,n,r,o)=>this.#e(410,e,n,r,o);static lengthRequired=(e,n,r,o)=>this.#e(411,e,n,r,o);static preconditionFailed=(e,n,r,o)=>this.#e(412,e,n,r,o);static contentTooLarge=(e,n,r,o)=>this.#e(413,e,n,r,o);static uriTooLong=(e,n,r,o)=>this.#e(414,e,n,r,o);static unsupportedMediaType=(e,n,r,o)=>this.#e(415,e,n,r,o);static rangeNotSatisfiable=(e,n,r,o)=>this.#e(416,e,n,r,o);static expectationFailed=(e,n,r,o)=>this.#e(417,e,n,r,o);static imATeapot=(e,n,r,o)=>this.#e(418,e,n,r,o);static misdirectedRequest=(e,n,r,o)=>this.#e(421,e,n,r,o);static unprocessableContent=(e,n,r,o)=>this.#e(422,e,n,r,o);static locked=(e,n,r,o)=>this.#e(423,e,n,r,o);static failedDependency=(e,n,r,o)=>this.#e(424,e,n,r,o);static tooEarly=(e,n,r,o)=>this.#e(425,e,n,r,o);static upgradeRequired=(e,n,r,o)=>this.#e(426,e,n,r,o);static preconditionRequired=(e,n,r,o)=>this.#e(428,e,n,r,o);static tooManyRequests=(e,n,r,o)=>this.#e(429,e,n,r,o);static requestHeaderFieldsTooLarge=(e,n,r,o)=>this.#e(431,e,n,r,o);static unavailableForLegalReasons=(e,n,r,o)=>this.#e(451,e,n,r,o);static internalServerError=(e,n,r,o)=>this.#e(500,e,n,r,o);static notImplemented=(e,n,r,o)=>this.#e(501,e,n,r,o);static badGateway=(e,n,r,o)=>this.#e(502,e,n,r,o);static serviceUnavailable=(e,n,r,o)=>this.#e(503,e,n,r,o);static gatewayTimeout=(e,n,r,o)=>this.#e(504,e,n,r,o);static httpVersionNotSupported=(e,n,r,o)=>this.#e(505,e,n,r,o);static variantAlsoNegotiates=(e,n,r,o)=>this.#e(506,e,n,r,o);static insufficientStorage=(e,n,r,o)=>this.#e(507,e,n,r,o);static loopDetected=(e,n,r,o)=>this.#e(508,e,n,r,o);static notExtended=(e,n,r,o)=>this.#e(510,e,n,r,o);static networkAuthenticationRequired=(e,n,r,o)=>this.#e(511,e,n,r,o)};var{toString:Vu}=Object.prototype,{propertyIsEnumerable:Gu}=Object.prototype;function nr(t){return Vu.call(t)}s(nr,"toString");function W(t){return typeof t=="string"}s(W,"isString");function Ue(t){return W(t)&&t!==""}s(Ue,"isNonEmptyString");function ni(t){return nr(t)==="[object RegExp]"}s(ni,"isRegexp");function ri(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>Gu.call(t,e))]}s(ri,"getOwnEnumerableKeys");function Ee(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof RegExp)&&!(t instanceof Date)}s(Ee,"isObject");function rr(t){return typeof t=="number"&&!isNaN(t)}s(rr,"isNumber");function or(t){return t===!0||t===!1}s(or,"isBoolean");function oi(t){return typeof t>"u"}s(oi,"isUndefined");function ii(t){return oi(t)||t===null}s(ii,"isUndefinedOrNull");function rt(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}s(rt,"isErrorLike");var si=new Map;function Dt(t){if(typeof t!="string")throw new Error("Input must be a string");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(t))throw new Error("Malformed input string");let e=si.get(t);if(e)return e;let n=t.split(","),r=[];for(let o of n){let i=o.split("-");if(i.length===2){let a=parseInt(i[0],10),u=parseInt(i[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return si.set(t,r),r}s(Dt,"statusCodesStringToNumberArray");function xe(t,e,n){if(!e.startsWith("."))throw new m(`Invalid ${n} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=t;return r.forEach(i=>{if(o===void 0)throw new P(`Error applying ${n} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(xe,"getValueFromRequestUser");function ve(t){if(Array.isArray(t)){if(t.includes(n=>typeof n!="string"))throw new m("Received an array that contains non-string values.");return t}if(W(t))return t.includes(",")?t.split(",").map(n=>n.trim()).filter(n=>n!==","&&n!==""):[t];throw new m(`Expected type of string, received type '${typeof t}'`)}s(ve,"parseValueToStringArray");function ai(t){if(t==null)return[];if(!Array.isArray(t))throw new m(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof t}'`);return t.map(n=>{if(!Ee(n))throw new m(`Invalid custom cors policy is set. Expected an object, received '${typeof n}'`);if(!Ue(n.name))throw new m("Value of 'name' on custom cors policies must be a non-empty string.");if(n.maxAge!==void 0&&!rr(n.maxAge))throw new m(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof n.maxAge}'`);if(n.allowCredentials!==void 0&&!or(n.allowCredentials))throw new m("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let r=ir(n,"allowedHeaders"),o=ir(n,"allowedMethods"),i=ir(n,"exposeHeaders"),a;try{a=ve(n.allowedOrigins)}catch(c){throw new m(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:n.name,allowCredentials:typeof n.allowCredentials=="boolean"?String(n.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:r?r.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:i?i.join(", "):void 0,maxAge:typeof n.maxAge=="number"?n.maxAge.toString():void 0}})}s(ai,"parseCorsPolicies");function ir(t,e){let n;if(t[e]!==void 0)try{n=ve(t[e])}catch(r){throw new m(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return n}s(ir,"parseOptionalProperty");var Ut=s((t,e)=>{if(e===null)return;if(t.find(a=>a==="*"))return e;let r=t.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),Ht=s((t,e)=>{let n={"access-control-allow-origin":e};t.allowedHeaders&&(n["access-control-allow-headers"]=t.allowedHeaders),t.allowedMethods&&(n["access-control-allow-methods"]=t.allowedMethods),t.exposeHeaders&&(n["access-control-expose-headers"]=t.exposeHeaders);let r=t.allowCredentials;r&&(n["access-control-allow-credentials"]=r);let o=t.maxAge?.toString()??void 0;return o&&(n["access-control-max-age"]=o),n},"generateCorsHeaders");var sr=s((t,e)=>{let n=e.routeData.corsPolicies,r=s(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 R.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let b=t.lookup(l,c);if(!b)return R.notFound(a,u);let g=b.routeConfiguration,w=Wu(l,d,p,g,n);return w.isValid?new Response(void 0,{status:200,statusText:"OK",headers:w.headers}):(w.error&&u.log.warn(w.error),R.notFound(a,u))},"optionsHandler"),o=new D({processors:[B],handler:r,gateway:e}),i=new k({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});t.addRoute(i,o.execute)},"registerCorsRoute"),Wu=s((t,e,n,r,o)=>{let i={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":n,"access-control-allow-methods":t,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...i,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new m(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=Ut(a.allowedOrigins,n);return u?{isValid:!0,headers:Ht(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${n}'`}},"validateAndBuildResponseHeaders");var ui=s((t,e)=>{let n=s(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new D({processors:[B],handler:n,gateway:e}),o=new k({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});t.addRoute(o,r.execute)},"registerNoRoutes");var ar=new k({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),ci=s((t,e)=>{let n=s(async(o,i)=>{let a=et.value?.notFoundHandler;if(a){let u=F.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return R.notFound(o,i)},"notFoundHandler"),r=new D({processors:[B],handler:n,gateway:e});t.addRoute(ar,r.execute)},"registerNotMatchedHandler");var Ku=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],li=s(t=>{Ku.forEach(e=>t.delete(e))},"stripCorsHeaders"),Mt=s(async(t,e,n,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await r(t),p=new Headers(d.headers);return li(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let i=await r(t);if(!(i instanceof Response))throw new T(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=Ju(o,n.routeData.corsPolicies),u=Yu(t,a),c=new Headers(i.headers);return li(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(i.body,{status:i.status,statusText:i.statusText,headers:c,webSocket:i.webSocket})},"corsProcessor"),Ju=s((t,e)=>{if(t.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:t.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let n=e?.find(r=>r.name===t.corsPolicy);if(n===void 0)throw new m(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return n},"getCorsPolicy"),Yu=s((t,e)=>{let n=Ut(e.allowedOrigins,t.headers.get("origin"));return n?Ht(e,n):{}},"getCorsHeaders");var ur=s((t,e)=>{let n=s(async()=>new Response(null,{status:200}),"pingRouteHandler"),r=new D({processors:[Mt],handler:n,gateway:e}),o=new k({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});t.addRoute(o,r.execute)},"registerPingRoute");var Nt=class{static{s(this,"PolicyBase")}options;policyName;constructor(e,n){if(!W(n))throw new P(`The name of a policy must be a string. Received '${n}' of type '${typeof n}'`);this.options=e,this.policyName=n}},ue=class extends Nt{static{s(this,"InboundPolicy")}},Se=class extends Nt{static{s(this,"OutboundPolicy")}};var dr=class extends ue{static{s(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,n,r){super(n,r),this.#e=e}handler(e,n){return this.#e(e,n,this.options,this.policyName)}},pr=class extends Se{static{s(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,n,r){super(n,r),this.#e=e}handler(e,n,r){return this.#e(e,n,r,this.options,this.policyName)}},cr=new Map;function ot(t,e){let n,r;return Array.isArray(t)?n=t:(n=t.policies?.inbound??[],r=t.path),n.filter(i=>!cr.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new m(`Invalid state - no Policy with the name '${i}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof ue)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new dr(u,a.handler.options,a.name);else throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${i}' on route '${r}' (typeof handler '${typeof c.handler}')`);cr.set(a.name,c)}),n.map(i=>{let a=cr.get(i);if(a===void 0)throw new P("Internal error. Policy not found in cache.");return a})}s(ot,"getInboundPolicyInstances");var lr=new Map;function Qu(t,e){let n=t.policies?.outbound??[];return n.filter(o=>!lr.has(o)).forEach(o=>{let i=e?.find(c=>c.name===o);if(!i)throw new m(`Invalid state - no Policy with the name '${o}' on route '${t.path}' was found in the policies configuration (check case).`);if(typeof i.handler?.module!="object")throw new m(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof policy '${typeof i.handler?.module}')`);let a=i.handler?.module[i.handler.export],u;if(typeof a!="function")throw new m(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof Se)u=new a(i.handler.options,i.name);else if(typeof a=="function")u=new pr(a,i.handler.options,i.name);else throw new m(`Invalid state - invalid policy '${o}' on route '${t.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new m(`Invalid state - invalid handler on policy '${o}' on route '${t.path}'`);lr.set(i.name,u)}),n.map(o=>{let i=lr.get(o);if(i===void 0)throw new P("Internal error. Policy not found in cache.");return i})}s(Qu,"getOutboundPolicyInstances");var mr=s(t=>async(e,n)=>{let r=F.getContextExtensions(n),o=[...t],i=e;for(;o.length>0;){let a=o.shift();if(!a)return i;let u=await a.handler(i,n);if(u instanceof A)i=u;else if(u instanceof Request)i=new A(u);else{if(u instanceof Response)return u;throw new m(`Invalid state - invalid handler on policy '${a.policyName}' on route '${n.route.path}. The result of an inbound policy must be a Response or Request.`)}r.latestRequest=i}return i},"toStackedInboundHandler"),Xu=s(t=>async(e,n,r)=>{let o=[...t],i=e;for(;o.length>0;){let a=o.shift();if(!a)return i;let u=await a.handler(i,n,r);if(!(u instanceof Response))throw new m(`Invalid state - invalid handler on policy '${a.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);i=u}return i},"toStackedOutboundHandler"),Zt=s(async(t,e,n,r)=>{let o=ot(e.route,n.routeData.policies),i=Qu(e.route,n.routeData.policies);return pi({request:t,context:e,inboundPolicies:o,outboundPolicies:i,gateway:n,next:r})},"policyProcessor");function di({inboundPolicies:t=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>pi({request:r,context:o,inboundPolicies:t,outboundPolicies:e,gateway:i,next:a}),"policyProcessor")}s(di,"createInternalPolicyProcessor");async function pi({request:t,context:e,inboundPolicies:n,outboundPolicies:r,gateway:o,next:i}){let a=mr(n);try{let u=await a(t,e);if(u instanceof Response)return u;let c=await i(u),l=Xu(r),d;return h.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,t,e):d=c.ok?l(c,t,e):c,d}catch(u){return e.log.error(u),o.errorHandler(t,e,u)}}s(pi,"executePolicyProcessor");function mi(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");let n={},o=(e||{}).decode||ec,i=0;for(;i<t.length;){let a=t.indexOf("=",i);if(a===-1)break;let u=t.indexOf(";",i);if(u===-1)u=t.length;else if(u<a){i=t.lastIndexOf(";",a-1)+1;continue}let c=t.slice(i,a).trim();if(n[c]===void 0){let l=t.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),n[c]=tc(l,o)}i=u+1}return n}s(mi,"parse");function ec(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}s(ec,"decode");function tc(t,e){try{return e(t)}catch{return t}}s(tc,"tryDecode");function gi(t,e){try{let n=/v\d+(-\d+)?/g,o=mi(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&n.test(o)?`https://dev-portal-${o}.zuplo.com`:t}catch{}return t}s(gi,"devPortalBaseURL");var fi="/__zuplo/dev-portal",nc="dev-portal-id",rc="dev-portal-host",oc="zp-account",ic="zp-project",sc="dev-portal-build",ac=`
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
- `,hi=s((t,e)=>{let{sitePathname:n}=e.runtimeSettings.developerPortal,r=h.instance.deploymentName,o=h.instance.devPortalBaseUrl,i=s(async(c,l)=>{if(h.instance.isLocalDevelopment)return new Response(oc,{headers:{"content-type":"text/html"}});if(!r)return R.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=gi(o,c.headers),y=new URL(`${d.pathname}${d.search}`,p),{headers:m,method:w,body:P}=c;return h.instance.build.ACCOUNT_NAME&&m.set(tc,h.instance.build.ACCOUNT_NAME),h.instance.build.PROJECT_NAME&&m.set(nc,h.instance.build.PROJECT_NAME),m.set(Xu,r),m.set(ec,d.host),m.set(rc,h.instance.build.BUILD_ID),await fetch(y.toString(),{headers:m,method:w,body:P,redirect:"manual"})},"devPortalRoute"),a=new U({processors:[j,Zt],handler:i,gateway:e}),u=new k({label:"SYSTEM_API_DOCS_V3_ROUTE",methods:["GET","PUT","POST","DELETE","PATCH","HEAD"],path:`(${n}|/_next)(.*)`,systemRouteName:"developer-portal"});t.addRoute(u,a.execute)},"registerDevPortalV3Route"),yi=s((t,e)=>{let{sitePathname:n}=e.runtimeSettings.developerPortal,r=s(async a=>{let u=new URL(a.url);return u.pathname=`${n}${u.pathname.substring(fi.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new U({processors:[j],handler:r,gateway:e}),i=new k({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${fi}(.*)`,systemRouteName:"developer-portal-legacy"});t.addRoute(i,o.execute)},"registerDevPortalLegacyRedirectRoute");var vi=Ae(Pe());var st="system-logger",bi="api-key";var gr=0,at=class{static{s(this,"CoreLogger")}constructor(e,n,r,o,i){this.#n=n,this.#r=r??"local",this.#o=o,this.#i=i,this.#e(e)}#e=e=>{let n=["error","warn","info","debug"],r=!1,o=s(()=>{},"emptyFunction"),i=s((a,u)=>{this.#i.forEach(c=>{c.log(a,u)})},"pushFunction");n.forEach(a=>{this.#t[a]=r?o:i,a==e&&(r=!0)})};#t={};#n;#r;#o;#i;log(e,n,r,o,i,a){gr>=Number.MAX_SAFE_INTEGER&&(gr=0);let u={requestId:r,rayId:o,level:e,logSource:n,messages:i,timestamp:new Date,logOwner:this.#n,loggingId:this.#r,buildId:this.#o,vectorClock:gr++};this.#t[e](u,a)}};var M=class extends Ie{static{s(this,"LogPlugin")}};var qt=class{static{s(this,"LoggingContext")}constructor(e,n,r){this.#e=e,this.custom=n,this.originalRequest=r}#e;custom;originalRequest;waitUntil=e=>{this.#e.waitUntil(e)}};var ut=class{static{s(this,"RequestLogger")}constructor(e,n,r,o){this.#t=e,this.#n=n,this.#r=r,this.#o=o}#e="request";#t;#n;#r;#o;debug=(...e)=>{this.#r.log("debug",this.#e,this.#t,this.#n,e,this.#o)};info=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};log=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};warn=(...e)=>{this.#r.log("warn",this.#e,this.#t,this.#n,e,this.#o)};error=(...e)=>{this.#r.log("error",this.#e,this.#t,this.#n,e,this.#o)}};var ic=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(t=>[t.name,t]),sc=new Map(ic);var ac=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],fr=Symbol(".toJSON was called"),uc=s(t=>{t[fr]=!0;let e=t.toJSON();return delete t[fr],e},"toJSON"),cc=s(t=>sc.get(t)??Error,"getErrorConstructor"),wi=s(({from:t,seen:e,to:n,forceEnumerable:r,maxDepth:o,depth:i,useToJSON:a,serialize:u})=>{if(!n)if(Array.isArray(t))n=[];else if(!u&&ot(t)){let l=cc(t.name);n=new l}else n={};if(e.push(t),i>=o)return n;if(a&&typeof t.toJSON=="function"&&t[fr]!==!0)return uc(t);let c=s(l=>wi({from:l,seen:[...e],forceEnumerable:r,maxDepth:o,depth:i,useToJSON:a,serialize:u}),"continueDestroyCircular");for(let[l,d]of Object.entries(t)){if(typeof Buffer=="function"&&Buffer.isBuffer(d)){n[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){n[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){n[l]=d;continue}if(!e.includes(t[l])){i++,n[l]=c(t[l]);continue}n[l]="[Circular]"}}for(let{property:l,enumerable:d}of ac)typeof t[l]<"u"&&t[l]!==null&&Object.defineProperty(n,l,{value:ot(t[l])?c(t[l]):t[l],enumerable:r?!0:d,configurable:!0,writable:!0});return n},"destroyCircular");function z(t,e){let n=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof t=="object"&&t!==null?wi({from:t,seen:[],forceEnumerable:!0,maxDepth:n,depth:0,useToJSON:r,serialize:!0}):typeof t=="function"?`[Function: ${t.name??"anonymous"}]`:t}s(z,"serializeError");var lc=/file:\/\/\/(.*?)\/dist\//g,dc=/\(https:\/\/raw\.githubusercontent\.com\/.*?\)/g,pc="at async Event.respondWith";function Ri(t){return typeof t!="string"?t:t.split(`
50
- `).filter(e=>!e.trim().startsWith("at async file")).map((e,n)=>{let r=e.replaceAll(lc,"").replaceAll(dc,"").replaceAll(pc,"").trim();return n===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
49
+ `,hi=s((t,e)=>{let{sitePathname:n}=e.runtimeSettings.developerPortal,r=h.instance.deploymentName,o=h.instance.devPortalBaseUrl,i=s(async(c,l)=>{if(h.instance.isLocalDevelopment)return new Response(ac,{headers:{"content-type":"text/html"}});if(!r)return R.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=gi(o,c.headers),b=new URL(`${d.pathname}${d.search}`,p),{headers:g,method:w,body:I}=c;return h.instance.build.ACCOUNT_NAME&&g.set(oc,h.instance.build.ACCOUNT_NAME),h.instance.build.PROJECT_NAME&&g.set(ic,h.instance.build.PROJECT_NAME),g.set(nc,r),g.set(rc,d.host),g.set(sc,h.instance.build.BUILD_ID),await fetch(b.toString(),{headers:g,method:w,body:I,redirect:"manual"})},"devPortalRoute"),a=new D({processors:[B,Zt],handler:i,gateway:e}),u=new k({label:"SYSTEM_API_DOCS_V3_ROUTE",methods:["GET","PUT","POST","DELETE","PATCH","HEAD"],path:`(${n}|/_next)(.*)`,systemRouteName:"developer-portal"});t.addRoute(u,a.execute)},"registerDevPortalV3Route"),yi=s((t,e)=>{let{sitePathname:n}=e.runtimeSettings.developerPortal,r=s(async a=>{let u=new URL(a.url);return u.pathname=`${n}${u.pathname.substring(fi.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new D({processors:[B],handler:r,gateway:e}),i=new k({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${fi}(.*)`,systemRouteName:"developer-portal-legacy"});t.addRoute(i,o.execute)},"registerDevPortalLegacyRedirectRoute");var vi=Ae(Pe());var it="system-logger",bi="api-key";var gr=0,st=class{static{s(this,"CoreLogger")}constructor(e,n,r,o,i){this.#n=n,this.#r=r??"local",this.#o=o,this.#i=i,this.#e(e)}#e=e=>{let n=["error","warn","info","debug"],r=!1,o=s(()=>{},"emptyFunction"),i=s((a,u)=>{this.#i.forEach(c=>{c.log(a,u)})},"pushFunction");n.forEach(a=>{this.#t[a]=r?o:i,a==e&&(r=!0)})};#t={};#n;#r;#o;#i;log(e,n,r,o,i,a){gr>=Number.MAX_SAFE_INTEGER&&(gr=0);let u={requestId:r,rayId:o,level:e,logSource:n,messages:i,timestamp:new Date,logOwner:this.#n,loggingId:this.#r,buildId:this.#o,vectorClock:gr++};this.#t[e](u,a)}};var U=class extends Ie{static{s(this,"LogPlugin")}};var qt=class{static{s(this,"LoggingContext")}constructor(e,n,r){this.#e=e,this.custom=n,this.originalRequest=r}#e;custom;originalRequest;waitUntil=e=>{this.#e.waitUntil(e)}};var at=class{static{s(this,"RequestLogger")}constructor(e,n,r,o){this.#t=e,this.#n=n,this.#r=r,this.#o=o}#e="request";#t;#n;#r;#o;debug=(...e)=>{this.#r.log("debug",this.#e,this.#t,this.#n,e,this.#o)};info=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};log=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};warn=(...e)=>{this.#r.log("warn",this.#e,this.#t,this.#n,e,this.#o)};error=(...e)=>{this.#r.log("error",this.#e,this.#t,this.#n,e,this.#o)}};var uc=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(t=>[t.name,t]),cc=new Map(uc);var lc=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],fr=Symbol(".toJSON was called"),dc=s(t=>{t[fr]=!0;let e=t.toJSON();return delete t[fr],e},"toJSON"),pc=s(t=>cc.get(t)??Error,"getErrorConstructor"),wi=s(({from:t,seen:e,to:n,forceEnumerable:r,maxDepth:o,depth:i,useToJSON:a,serialize:u})=>{if(!n)if(Array.isArray(t))n=[];else if(!u&&rt(t)){let l=pc(t.name);n=new l}else n={};if(e.push(t),i>=o)return n;if(a&&typeof t.toJSON=="function"&&t[fr]!==!0)return dc(t);let c=s(l=>wi({from:l,seen:[...e],forceEnumerable:r,maxDepth:o,depth:i,useToJSON:a,serialize:u}),"continueDestroyCircular");for(let[l,d]of Object.entries(t)){if(typeof Buffer=="function"&&Buffer.isBuffer(d)){n[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){n[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){n[l]=d;continue}if(!e.includes(t[l])){i++,n[l]=c(t[l]);continue}n[l]="[Circular]"}}for(let{property:l,enumerable:d}of lc)typeof t[l]<"u"&&t[l]!==null&&Object.defineProperty(n,l,{value:rt(t[l])?c(t[l]):t[l],enumerable:r?!0:d,configurable:!0,writable:!0});return n},"destroyCircular");function z(t,e){let n=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof t=="object"&&t!==null?wi({from:t,seen:[],forceEnumerable:!0,maxDepth:n,depth:0,useToJSON:r,serialize:!0}):typeof t=="function"?`[Function: ${t.name??"anonymous"}]`:t}s(z,"serializeError");var mc=/file:\/\/\/(.*?)\/dist\//g,gc=/\(https:\/\/raw\.githubusercontent\.com\/.*?\)/g,fc="at async Event.respondWith";function Ri(t){return typeof t!="string"?t:t.split(`
50
+ `).filter(e=>!e.trim().startsWith("at async file")).map((e,n)=>{let r=e.replaceAll(mc,"").replaceAll(gc,"").replaceAll(fc,"").trim();return n===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
51
51
  `)}s(Ri,"cleanStack");function $t(t,e,n=""){let r=[],o=e?.maxDepth??3;return s(function i(a,u={},c,l){let d=u.indent||" ",p;u.inlineCharacterLimit===void 0?p={newline:`
52
52
  `,newlineOrSpace:`
53
- `,pad:c,indent:c+d}:p={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let y=s(m=>{if(u.inlineCharacterLimit===void 0)return m;let w=m.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return w.length<=u.inlineCharacterLimit?w:m.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"||ni(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 m="["+p.newline+a.map((w,P)=>{let E=a.length-1===P?p.newline:","+p.newlineOrSpace,x=i(w,u,c+d,l+1);return u.transform&&(x=u.transform(a,P,x)),p.indent+x+E}).join("")+p.pad+"]";return r.pop(),y(m)}if(Ee(a)){let m=ri(a);if(u.filter&&(m=m.filter(P=>u.filter?.(a,P))),m.length===0)return"{}";r.push(a);let w="{"+p.newline+m.map((P,E)=>{let x=m.length-1===E?p.newline:","+p.newlineOrSpace,A=typeof P=="symbol",H=!A&&/^[a-z$_][$\w]*$/i.test(P),_=A||H?P:i(P,u,"",l+1),G=i(a[P],u,c+d,l+1);return u.transform&&(G=u.transform(a,P,G)),p.indent+String(_)+": "+G+x}).join("")+p.pad+"}";return r.pop(),y(w)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,m=>m===`
55
- `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(t,e,n,0)}s($t,"stringifyObject");function ye(t){return t.map(e=>z(e))}s(ye,"makeErrorsSerializable");function He(t){if(t.length===0)return"<no data provided to log>";let e=t[0];return typeof e=="string"?e:e instanceof Error?e.message:ce(z(e))}s(He,"extractBestMessage");function Pi(t){let e=[];return t.forEach(n=>{if(typeof n=="string")e.push(n);else if(ot(n))if(n.stack)e.push(n.stack);else{let r=$t(z(n));e.push(r)}else if(typeof n=="object"){let r=$t(n);e.push(r)}else{let r=hr(n);e.push(r)}}),e.join(`
56
- `)}s(Pi,"messagesToMultilineText");function ce(t){return typeof t=="string"?t:JSON.stringify(t)}s(ce,"stringifyNonString");function hr(t){return typeof t=="string"?t:t===null?"null":typeof t>"u"?"undefined":typeof t=="number"||typeof t=="boolean"||typeof t=="bigint"||typeof t=="symbol"?t.toString():typeof t=="function"?`[function ${t.name}]`:typeof t=="object"&&Array.isArray(t)?`[array ${t.length}]`:t instanceof Error?`${t.name??"Error"}: ${t.message??"unknown"}`:typeof t=="object"?nr(t):"unknown"}s(hr,"stringifyNonStringToText");var Ft=require("jose");async function V(t,e,n){for(let r=0;r<=t.retries;r++){let o=fetch(e,n);if(r===t.retries)return o;let i=await o;if(i.status<500&&i.status!==429)return i;t?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:i.status}),await new Promise(a=>setTimeout(a,t.retryDelayMs*Math.pow(2,r)))}throw new g("An unknown error occurred, ensure retries is not negative")}s(V,"fetchRetry");async function oe({serviceAccount:t,audience:e,expirationTime:n="1h",payload:r={}}){let{clientEmail:o,privateKeyId:i,privateKey:a}=t;return await new Ft.SignJWT(r).setProtectedHeader({alg:"RS256",kid:i}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(n).sign(a)}s(oe,"getTokenFromGcpServiceAccount");async function Ii(t,e,n){return Ei(t,{token:e,returnSecureToken:!0},n)}s(Ii,"exchangeFirebaseJwtForIdToken");async function Bt(t,e,n){return Ei(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},n)}s(Bt,"exchangeGgpJwtForIdToken");async function Ei(t,e,n){let r=await V(n,t,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let i;try{let a=await r.text(),u=JSON.parse(a);i={cause:u.error??u}}catch{}throw new I({message:"Could not get token from Google Identity",extensionMembers:i})}return await r.json()}s(Ei,"fetchToken");var K=class t{static{s(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:n}){this.#t=e,this.#e=n}static async init(e){let n=JSON.parse(e),r=await(0,Ft.importPKCS8)(n.private_key.trim(),"RS256");return new t({serviceAccount:n,privateKey:r})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};var jt=class extends M{constructor(n){super();this.options=n}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new ct(this.options)}},mc="https://logging.googleapis.com/v2/entries:write?alt=json",yr={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},ct=class{static{s(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=h.instance.loggingEnvironmentType,this.#i=h.instance.loggingEnvironmentStage,this.#r=h.instance.deploymentName}#e;#t;#n;#r;#o;#i;async init(){this.#t=await K.init(this.#e)}log(e,n){if(!this.#t)throw new T("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:ye(e.messages)},o=this.#t.projectId??"zuplo-production",i={logName:this.#n,resource:{type:"global"},severity:yr[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(i.labels.rayId=e.rayId);let a=He(r.allMessages);i.jsonPayload={...r,message:a},this.batcher.enqueue(i),n.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await K.init(this.#e));let n=await oe({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await fetch(mc,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${n}`,"content-type":"application/json;charset=UTF-8"}});r.ok||console.error(r.status,r.statusText,await r.text())};batcher=new C("google-log-transport",1,this.dispatchFunction)};var zt="gcp";function Vt(t){let e={allMessages:ye(t.messages)},n="zuplo-production",r=He(e.allMessages),o={logName:`projects/${n}/logs/runtime-user`,message:r,severity:yr[t.level],timestamp:t.timestamp,"logging.googleapis.com/labels":{buildId:t.buildId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},"logging.googleapis.com/trace":`projects/${n}/traces/${t.requestId}`,allMessages:e.allMessages};return t.rayId&&(o["logging.googleapis.com/labels"].rayId=t.rayId),o}s(Vt,"gcpLogFormat");var lt=class{static{s(this,"ConsoleTransport")}constructor(e,n){this.#e=e??console,this.#t=n}#e;#t;log(e){if(this.#t===zt){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Vt(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,level:e.level,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId}])}};var Gt=class extends M{constructor(n){super();this.options=n}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new dt(this.options)}},br="__ddtags",wr="__ddattr",Rr=s(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),gc=s(t=>{let e=Object.keys(t),n=[];return e.forEach(r=>{let o=t[r];o==null?n.push(Rr(r)):n.push(`${Rr(r)}:${Rr(o.toString())}`)}),n.join(",")},"formatTags"),dt=class{static{s(this,"DataDogTransport")}constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=h.instance.loggingEnvironmentType,this.#o=h.instance.loggingEnvironmentStage,this.#n=h.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){let r={},o=n.custom[br];o&&typeof o=="object"&&Object.assign(r,o);let i=[...e.messages],a=e.messages.findIndex(m=>m[br]!==void 0);a>-1&&(Object.assign(r,i[a][br]),i.splice(a,1));let u={},c=n.custom[wr];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(m=>m[wr]!==void 0);l>-1&&(Object.assign(u,i[l][wr]),i.splice(l,1));let d=ye(i),y={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(n.originalRequest.url).hostname,msg:He(d),service:e.loggingId,ddtags:gc(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(y,u),this.batcher.enqueue(y),n.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new C("data-dog-transport",10,this.dispatchFunction)};var pt=class{static{s(this,"ProcessTransport")}constructor(e,n){this.#e=e,this.#t=n}#e;#t;log(e){if(this.#t===zt){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Vt(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 fc=s(({url:t,remoteLogToken:e,loggingId:n,sendOnlyErrors:r})=>async o=>{let i;if(r===!0?i=o.filter(a=>a.level==="error"):i=o,i.length!==0)try{await fetch(`${t}/publish/${n}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:i.map(a=>({...a,messages:ye(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":h.instance.systemUserAgent,"zp-dn":h.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Wt,Kt=class{static{s(this,"RemoteLogTransport")}constructor(e){Wt||(Wt=new C("remote-log-transport",1,fc(e)))}log(e,n){Wt.enqueue(e),n.waitUntil(Wt.waitUntilFlushed())}};var hc={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},xi=s((t,e)=>n=>{let r={};return r.deploymentName=t,r.labels={requestId:n.requestId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},r.rayId=n.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=n.vectorClock,{timestamp:n.timestamp,observerdTimestamp:n.timestamp,traceId:n.requestId,severityText:n.level,severityNumber:hc[n.level],body:n.messages,attributes:r}},"unifiedFormatter");var yc=s(({url:t,remoteLogToken:e,deploymentName:n,build:r})=>async o=>{if(o.length===0)return;let i=xi(n,r);try{await fetch(`${t}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(i)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":h.instance.systemUserAgent,"zp-dn":h.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Jt,Yt=class{static{s(this,"UnifiedLogTransport")}constructor(e){Jt||(Jt=new C("unified-log-transport",1,yc(e)))}async log(e,n){Jt.enqueue(e),n.waitUntil(Jt.waitUntilFlushed())}};var Pr=(0,vi.debug)("zuplo:logging"),Qt=class t{static{s(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:n}){this.systemCoreLogger=e,this.userCoreLogger=n}static async init(e){let n=await t.setupSystemCoreLogger(h.instance,e),r=await t.setupUserCoreLogger(h.instance,e);return new t({systemCoreLogger:n,userCoreLogger:r})}static async setupSystemCoreLogger(e,n){let{build:r}=e;Pr("Gateway.setupSystemCoreLogger");let o=[],i=n.getService(st);return i?o.push(new pt(i.logger,e.logFormat)):e.isDeno&&o.push(new lt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Yt({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 at(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,n){Pr("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:i}=e,a=n.getService(st);if(a&&a.captureUserLogs===!0?r.push(new pt(a.logger,e.logFormat)):e.isDeno&&r.push(new lt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new Kt({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:e.isCloudflare})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new ct({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME})),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new dt({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return fe.forEach(u=>{u instanceof M&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new at(e.userLogLevel,"user",e.loggingId,i.BUILD_ID,r)}createRequestLoggers(e,n,r,o,i){Pr("Gateway.createRequestLoggers");let a=new qt(r,o,i),u=new ut(e,n,this.systemCoreLogger,a);return{userRequestLogger:new ut(e,n,this.userCoreLogger,a),systemRequestLogger:u}}};var Te=class{static{s(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 Ir=class{static{s(this,"RouterEntry")}constructor(e,n,r,o){this.fullPath=e,this.urlPattern=n,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},Me=class{static{s(this,"LookupResult")}constructor(e,n,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=n}executableHandler;routeConfiguration;params},Er=class extends Error{static{s(this,"RouterError")}constructor(e,n){super(e,n)}},Ne=class{static{s(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,n){if(!(e instanceof Te||e instanceof k))throw new T("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(i=>i.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let i=new URLPattern({pathname:o}),a=new Ir(o,i,e,n);Object.freeze(a.config),this.routeEntries.push(a)}catch(i){throw new Er(`addRoute-error: Invalid path '${o}'. '${i.message}'`,{cause:i})}}lookup(e,n){if(typeof e>"u")throw new g(`Invalid request - Method was undefined. Path: '${n}'`);let r=this.routeEntries.filter(o=>o.config.methods.includes(e));if(r.length!==0)for(let o=0;o<r.length;o++){let i=r[o],u=i.urlPattern.exec({pathname:n});if(u!==null)return new Me(i.config,i.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let n=[];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 Me(o.config,o.executableHandler,a.pathname.groups);n.push(u)}}return n}};var ie=(0,Si.debug)("zuplo:runtime"),bc=s(t=>{let e=t.findIndex(n=>n.name===rt.name);return e>-1?[...t.splice(e),rt]:[...t,rt]},"setupSystemNoVersion"),Z=class t{constructor(e,n,r,o){this.routeData=e;this.runtimeSettings=n;this.schemaValidator=o;ie("Gateway.constructor"),this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{s(this,"Gateway")}static#e;static async initialize(e,n,r,o,i){if(ie("Gateway.initialize"),!t.#e){await ei(i);let a=await Qt.init(r),u=e(),c={...u,corsPolicies:ai(u.corsPolicies)},l=new t(c,n,a,o);t.#e=l}return t.#e}static purgeGatewayCache(){ie("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new T("Gateway cannot be used before it is initialized");return t.#e}instanceId=crypto.randomUUID();#t;#n;#r=[Zt,Mt,j];#o;setupRoutes=()=>{ie("Gateway.setupRoutes");let e=this.routeData,n=bc(e.versions),r=new Ne(n);if(e.routes.length===0)return er(r,this),ur(r,this),sr(r,this),ui(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(yi(r,this),hi(r,this)),er(r,this),ur(r,this),sr(r,this);for(let i of fe)i instanceof ae&&i.registerRoutes(r,this);return e.routes.forEach(i=>{let a;if(typeof i.handler?.module=="object"&&(a=i.handler?.module[i.handler.export]),typeof a!="function")throw new g(`Invalid state - No handler on route for path '${i.path}'`);let u=new U({processors:this.#r,handler:a,gateway:this}),c=new Te(i);r.addRoute(c,u.execute)}),ci(r,this),r};setupErrorHandler=()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new g("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=s((n,r,o)=>this.#i(n,r,o),"errorHandler");return e};errorHandler(e,n,r){try{return this.#o(e,n,r)}catch(o){return ie("An error occurred in the user's errorHandler",o),this.#i(e,n,o)}}#i(e,n,r){ie("Gateway.internalErrorResponse");let o={};if(h.instance.isDeno){if(r instanceof I&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let i=z(r.cause);"stack"in i&&(i.stack=Ri(i.stack)),o={cause:i}}}return R.internalServerError(e,n,{detail:r.message,...o})}#s(e){let n=new Headers(e.headers);return Oo.forEach(r=>{n.delete(r)}),h.instance.isDeno&&Co.forEach(r=>{n.delete(r)}),new Request(e,{headers:n})}async handleRequest(e,n){let r=e.headers.get(Ye)??e.headers.get(Ro),o=e.headers.get(_e);if(!r){r=crypto.randomUUID();let E=new Headers(e.headers);E.set(Ye,r),e=new Request(e,{headers:E})}if(["GET","HEAD"].includes(e.method)&&e.body){let E=new Headers(e.headers);E.set(Po,"true"),e=new Request(e,{headers:E,body:null})}let i={},{userRequestLogger:a,systemRequestLogger:u}=this.#t.createRequestLoggers(r,o,n,i,e),c=new URL(e.url),l=c.pathname,d=this.#n.lookup(e.method,l);if(!d)throw new T(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let p=new Xt(e.headers),y=this.#s(e),m=new L(y,{params:d.params}),w=new en({logger:a,route:d.routeConfiguration,requestId:r,fetchEvent:n,custom:i,incomingRequestProperties:p}),P=B.initialize(w,m);if(d.routeConfiguration===ar&&tt.value?.notFoundHandler!==void 0){let E=this.#n.lookupByPathOnly(l);P.pathOnlyMatches=E.map(x=>x.routeConfiguration).filter(x=>x instanceof Te)}try{if(O.addLogger(w,u),h.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!nt(c):!c.pathname.startsWith("/__zuplo")){let A=await Yo(m,w);if(A instanceof Response)return A;{let H=B.getContextExtensions(w);m=A,H.latestRequest=m}}nt(c)||a.debug(`Request received '${c.pathname}'`,{method:e.method,url:c.pathname,hostname:c.hostname,route:d.routeConfiguration.path});let E=d.executableHandler;wc(E,d,e),ie("Gateway.handleRequest - call user handler");let x=await E(m,w);if(ie("Gateway.handleRequest - user handler"),!(x instanceof Response))throw new I(`Invalid Response type from the request handler: ${typeof x}`);if(x.bodyUsed)throw new I("The response object has already been used. Return a new response instead.");if(x.headers.get(Ye)===null&&!x.webSocket){let A=new Headers(x.headers);return A.set(Ye,r),new Response(x.body,{status:x.status,statusText:x.statusText,headers:A,cf:x.cf})}else return x}catch(E){return ie("Gateway - error executing handler",E),E instanceof I?(a.error(E),u.warn(E)):u.error(E),await this.#i(m,w,E)}}};function wc(t,e,n){if(ie("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new g(`Invalid state - no routeConfiguration for '${n.method}:${n.url}`):new g(`Invalid state. No handler for request '${n.method}':'${e.routeConfiguration.path}'`)}s(wc,"checkHandler");var Ti=s(async(t,e,n)=>{let r=Z.instance.routeData.policies,o=it([t],r);if(o.length===0)throw new I(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);return o[0].handler(e,n)},"invokeInboundPolicy");var Xt=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Nn);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Zn)??void 0}get city(){return this.#e.get(kn)??this.#e.get(Io)??void 0}get continent(){return this.#e.get(Dn)??this.#e.get(Eo)??void 0}get country(){return this.#e.get(Un)??this.#e.get(xo)??void 0}get latitude(){return this.#e.get(Mn)??this.#e.get(So)??void 0}get longitude(){return this.#e.get(Hn)??this.#e.get(vo)??void 0}get colo(){return this.#e.get(qn)??void 0}get postalCode(){return this.#e.get($n)??void 0}get metroCode(){return this.#e.get(Fn)??void 0}get region(){return this.#e.get(Bn)??void 0}get regionCode(){return this.#e.get(jn)??void 0}get timezone(){return this.#e.get(zn)??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}}},ke=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},De=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,n){super("responseSent"),this.request=e,this.response=n}request;response},B=class t{static{s(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,n){if(!t.#e.has(e)){let r=new t(n);return t.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let n=t.#e.get(e);if(!n)throw new I(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return n}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,n,r)=>{for(let o of this.#t)await o(e,n,r)};onResponseSending=async(e,n,r)=>{let o=e;for(let i of this.#n)o=await i(e,n,r);return o}},en=class extends EventTarget{static{s(this,"SystemZuploContext")}constructor({logger:e,route:n,requestId:r,fetchEvent:o,custom:i,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=n,this.requestId=r,this.custom=i,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>Ti(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{B.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{B.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,n,r){let o=s(i=>{try{typeof n=="function"?n(i):n.handleEvent(i)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var le=class t{static{s(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,n){t.set(e,this.#t,n)}get(e){return t.get(e,this.#t)}static set(e,n,r){t.#e||(t.#e=new WeakMap);let o=t.#e.get(e);o||(o=new Map),o.set(n,r),t.#e.set(e,o)}static get(e,n){return t.#e||(t.#e=new WeakMap),t.#e.get(e)?.get(n)}};var Rc=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function xr(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!Rc.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}s(xr,"isRestrictedEnvVariableName");function vr(t){return!!t.startsWith("ZUPLO_")}s(vr,"isZuploReadableEnvVariableName");var q=new Proxy({},{get(t,e){if(xr(String(e))&&!vr(String(e)))return;let n=globalThis,r;return n.process?r=n.process.env[e]:r=n[e],r}});var Ci=Ae(Pe());var X=(0,Ci.debug)("zuplo:runtime:external-service");function Ai(){let t,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=h.instance.runtime;if(e&&e!=="undefined")try{let n=atob(e);t=JSON.parse(n)}catch{}return t}s(Ai,"getServiceAuth");async function Li(t){let e=Ai();if(!e)throw X("There is no external service auth configured for this zup."),new I("There are no external services configured for this zup.");if(typeof t!="string")throw X("Cannot call external service with Request object"),new I("Currently, we only support fetch(<some_string>, ...).");let r=new URL(t).hostname,o={};o["CF-Access-Client-Id"]=e.clientId,o["CF-Access-Client-Secret"]=e.clientSecret;let i;if(e.customServiceMapping&&e.customServiceMapping[r])i=`https://${e.customServiceMapping[r]}`;else if(h.instance.useSha256ServiceRouting){X("Using sha256 service routing");let a=h.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE)i=`https://${await ki(r,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw X("Cannot use sha256 service routing, missing build variables"),new I("Failed to generate fully qualified tunnel url.")}else i=`https://${r}.zuptunnel.com`;return{serviceBaseUrl:i,tunnelHeaders:o}}s(Li,"externalServiceTunnelConfig");async function _i(t,e){let n=Ai();if(n)if(X(`Using external service auth. ClientId: ${n.clientId})`),typeof t=="string"){let r=new URL(t),o=r.hostname,i=e??{},a=new Headers(i.headers||{});a.set("CF-Access-Client-Id",n.clientId),a.set("CF-Access-Client-Secret",n.clientSecret),i.headers=a;let u;if(n.customServiceMapping&&n.customServiceMapping[o])u=`https://${n.customServiceMapping[o]}`;else if(h.instance.useSha256ServiceRouting){X("Using sha256 service routing");let d=h.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await ki(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw X("Cannot use sha256 service routing, missing build variables"),new I("Failed to generate fully qualified tunnel url.")}else u=`https://${o}.zuptunnel.com`;let c=new URL(`${u}${r.pathname}${r.search}`);X(`Calling external service: ${c.toString()}`);let l=await Ze(c.toString(),i);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:n.clientId,tunnelHost:u}),new I("Could not connect to secure tunnel.");return l}else throw X("Cannot call external service with Request object"),new I("Currently, we only support fetch(<some_string>, ...).");else throw X("There is no external service auth configured for this zup."),new I("There are no external services configured for this zup.")}s(_i,"externalServiceHandler");async function ki(t,e,n,r){let o=t.toLowerCase(),i=e.toLowerCase(),a=n.toLowerCase(),u=Pc(r);X(`Hashing service name: ${i}-${o}.${i}-${a}-${u}`);let c=await Oi(`${i}-${o}`),l=await Oi(`${i}-${a}-${u}`);return`${c}.${l}`}s(ki,"hashServiceName");async function Oi(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("").slice(0,-1)}s(Oi,"hashSegment");function Pc(t){let e=t.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}s(Pc,"sanitizeEnvironmentType");var Di=new Map;Di.set("service:",_i);var Ze=globalThis.fetch;globalThis.fetch=function(t,e){let n=Ic(e);if(typeof t=="string"){let r=new URL(t),o=Di.get(r.protocol);return o?o(t,n):Ze(t,n)}else return Ze(t,n)};var Ic=s(t=>{if(!t||t instanceof Request)return t;let e=t;if(!e.zuplo)return t;let n=t;return n.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete t.zuplo,t},"transformInit");var Ui=s(()=>{Z.purgeGatewayCache()},"purgeGatewayCache"),tn=class{constructor(e,n,r,o,i,a,u){this.routeLoader=e;this.buildEnvironment=n;this.runtimeEnvironment=r;this.runtimeSettings=o;this.serviceProvider=i;this.schemaValidations=a;this.runtimeInit=u}static{s(this,"Handler")}requestHandler=async(e,n)=>{h.initialize(this.buildEnvironment,this.runtimeEnvironment);let r;try{r=await Z.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations,this.runtimeInit)}catch(o){console.error("Error initializing gateway.",o);let i="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.";o instanceof g&&(i=o.message);let a={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:i,instance:e.url,trace:{timestamp:Date.now(),rayId:e.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:h.instance.isDeno?o.message:void 0};return new Response(JSON.stringify(a,null,2),{status:500,headers:{"content-type":"application/json"}})}return r.handleRequest(e,n)}};var ji=Ae(Pe());function Ec(t){for(var e=[],n=0;n<t.length;){var r=t[n];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:n,value:t[n++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:n++,value:t[n++]});continue}if(r==="{"){e.push({type:"OPEN",index:n,value:t[n++]});continue}if(r==="}"){e.push({type:"CLOSE",index:n,value:t[n++]});continue}if(r===":"){for(var o="",i=n+1;i<t.length;){var a=t.charCodeAt(i);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=t[i++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(n));e.push({type:"NAME",index:n,value:o}),n=i;continue}if(r==="("){var u=1,c="",i=n+1;if(t[i]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(i));for(;i<t.length;){if(t[i]==="\\"){c+=t[i++]+t[i++];continue}if(t[i]===")"){if(u--,u===0){i++;break}}else if(t[i]==="("&&(u++,t[i+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(i));c+=t[i++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(n));if(!c)throw new TypeError("Missing pattern at ".concat(n));e.push({type:"PATTERN",index:n,value:c}),n=i;continue}e.push({type:"CHAR",index:n,value:t[n++]})}return e.push({type:"END",index:n,value:""}),e}s(Ec,"lexer");function Sr(t,e){e===void 0&&(e={});for(var n=Ec(t),r=e.prefixes,o=r===void 0?"./":r,i="[^".concat(vc(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=s(function(Y){if(c<n.length&&n[c].type===Y)return n[c++].value},"tryConsume"),p=s(function(Y){var Q=d(Y);if(Q!==void 0)return Q;var Oe=n[c],Ce=Oe.type,An=Oe.index;throw new TypeError("Unexpected ".concat(Ce," at ").concat(An,", expected ").concat(Y))},"mustConsume"),y=s(function(){for(var Y="",Q;Q=d("CHAR")||d("ESCAPED_CHAR");)Y+=Q;return Y},"consumeText");c<n.length;){var m=d("CHAR"),w=d("NAME"),P=d("PATTERN");if(w||P){var E=m||"";o.indexOf(E)===-1&&(l+=E,E=""),l&&(a.push(l),l=""),a.push({name:w||u++,prefix:E,suffix:"",pattern:P||i,modifier:d("MODIFIER")||""});continue}var x=m||d("ESCAPED_CHAR");if(x){l+=x;continue}l&&(a.push(l),l="");var A=d("OPEN");if(A){var E=y(),H=d("NAME")||"",_=d("PATTERN")||"",G=y();p("CLOSE"),a.push({name:H||(_?u++:""),pattern:H&&!_?i:_,prefix:E,suffix:G,modifier:d("MODIFIER")||""});continue}p("END")}return a}s(Sr,"parse");function Hi(t,e){return xc(Sr(t,e),e)}s(Hi,"compile");function xc(t,e){e===void 0&&(e={});var n=Sc(e),r=e.encode,o=r===void 0?function(c){return c}:r,i=e.validate,a=i===void 0?!0:i,u=t.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),n)});return function(c){for(var l="",d=0;d<t.length;d++){var p=t[d];if(typeof p=="string"){l+=p;continue}var y=c?c[p.name]:void 0,m=p.modifier==="?"||p.modifier==="*",w=p.modifier==="*"||p.modifier==="+";if(Array.isArray(y)){if(!w)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(y.length===0){if(m)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var P=0;P<y.length;P++){var E=o(y[P],p);if(a&&!u[d].test(E))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(E,'"'));l+=p.prefix+E+p.suffix}continue}if(typeof y=="string"||typeof y=="number"){var E=o(String(y),p);if(a&&!u[d].test(E))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(E,'"'));l+=p.prefix+E+p.suffix;continue}if(!m){var x=w?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(x))}}return l}}s(xc,"tokensToFunction");function vc(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(vc,"escapeString");function Sc(t){return t&&t.sensitive?"":"i"}s(Sc,"flags");var qi=Ae(Pe());var Tc=(0,qi.debug)("zuplo:runtime"),Or=new TextEncoder,Mi={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"},Oc=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],qe=class{static{s(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:n,sessionToken:r,service:o,region:i,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(n==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=n,this.sessionToken=r,this.service=o,this.region=i,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,n){let r=new Cr(Object.assign({url:e},n,this,n&&n.aws)),o=Object.assign({},n,await r.sign());return delete o.aws,{url:o.url.toString(),request:o}}async fetch(e,n){Tc("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:i}=await this.sign(e,n),a=fetch(o,i);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new g("An unknown error occurred, ensure retries is not negative")}},Cr=class{static{s(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:n,headers:r,body:o,accessKeyId:i,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:y,appendSessionToken:m,allHeaders:w,singleEncode:P}){if(n==null)throw new TypeError("url is a required option");if(i==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(n),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=i,this.secretAccessKey=a,this.sessionToken=u;let E,x;(!c||!l)&&([E,x]=Cc(this.url,this.headers)),this.service=c||E||"",this.region=l||x||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=y,this.appendSessionToken=m||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(_=>w||!Oc.includes(_)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(_=>_+":"+(_==="host"?this.url.host:(this.headers.get(_)||"").replace(/\s+/g," "))).join(`
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,"/");P||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=Zi(this.encodedPath);let H=new Set;this.encodedSearch=[...this.url.searchParams].filter(([_])=>{if(!_)return!1;if(this.service==="s3"){if(H.has(_))return!1;H.add(_)}return!0}).map(_=>_.map(G=>Zi(encodeURIComponent(G)))).sort(([_,G],[Y,Q])=>_<Y?-1:_>Y?1:G<Q?-1:G>Q?1:0).map(_=>_.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),n=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(n);if(!r){let o=await mt("AWS4"+this.secretAccessKey,e),i=await mt(o,this.region),a=await mt(i,this.service);r=await mt(a,"aws4_request"),this.cache.set(n,r)}return Tr(await mt(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Tr(await Ni(await this.canonicalString()))].join(`
53
+ `,pad:c,indent:c+d}:p={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let b=s(g=>{if(u.inlineCharacterLimit===void 0)return g;let w=g.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return w.length<=u.inlineCharacterLimit?w:g.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"||ni(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 g="["+p.newline+a.map((w,I)=>{let E=a.length-1===I?p.newline:","+p.newlineOrSpace,x=i(w,u,c+d,l+1);return u.transform&&(x=u.transform(a,I,x)),p.indent+x+E}).join("")+p.pad+"]";return r.pop(),b(g)}if(Ee(a)){let g=ri(a);if(u.filter&&(g=g.filter(I=>u.filter?.(a,I))),g.length===0)return"{}";r.push(a);let w="{"+p.newline+g.map((I,E)=>{let x=g.length-1===E?p.newline:","+p.newlineOrSpace,L=typeof I=="symbol",$=!L&&/^[a-z$_][$\w]*$/i.test(I),_=L||$?I:i(I,u,"",l+1),G=i(a[I],u,c+d,l+1);return u.transform&&(G=u.transform(a,I,G)),p.indent+String(_)+": "+G+x}).join("")+p.pad+"}";return r.pop(),b(w)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,g=>g===`
55
+ `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(t,e,n,0)}s($t,"stringifyObject");function he(t){return t.map(e=>z(e))}s(he,"makeErrorsSerializable");function He(t){if(t.length===0)return"<no data provided to log>";let e=t[0];return typeof e=="string"?e:e instanceof Error?e.message:ce(z(e))}s(He,"extractBestMessage");function Pi(t){let e=[];return t.forEach(n=>{if(typeof n=="string")e.push(n);else if(rt(n))if(n.stack)e.push(n.stack);else{let r=$t(z(n));e.push(r)}else if(typeof n=="object"){let r=$t(n);e.push(r)}else{let r=hr(n);e.push(r)}}),e.join(`
56
+ `)}s(Pi,"messagesToMultilineText");function ce(t){return typeof t=="string"?t:JSON.stringify(t)}s(ce,"stringifyNonString");function hr(t){return typeof t=="string"?t:t===null?"null":typeof t>"u"?"undefined":typeof t=="number"||typeof t=="boolean"||typeof t=="bigint"||typeof t=="symbol"?t.toString():typeof t=="function"?`[function ${t.name}]`:typeof t=="object"&&Array.isArray(t)?`[array ${t.length}]`:t instanceof Error?`${t.name??"Error"}: ${t.message??"unknown"}`:typeof t=="object"?nr(t):"unknown"}s(hr,"stringifyNonStringToText");var Ft=require("jose");async function V(t,e,n){for(let r=0;r<=t.retries;r++){let o=fetch(e,n);if(r===t.retries)return o;let i=await o;if(i.status<500&&i.status!==429)return i;t?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:i.status}),await new Promise(a=>setTimeout(a,t.retryDelayMs*Math.pow(2,r)))}throw new m("An unknown error occurred, ensure retries is not negative")}s(V,"fetchRetry");async function oe({serviceAccount:t,audience:e,expirationTime:n="1h",payload:r={}}){let{clientEmail:o,privateKeyId:i,privateKey:a}=t;return await new Ft.SignJWT(r).setProtectedHeader({alg:"RS256",kid:i}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(n).sign(a)}s(oe,"getTokenFromGcpServiceAccount");async function Ii(t,e,n){return Ei(t,{token:e,returnSecureToken:!0},n)}s(Ii,"exchangeFirebaseJwtForIdToken");async function Bt(t,e,n){return Ei(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},n)}s(Bt,"exchangeGgpJwtForIdToken");async function Ei(t,e,n){let r=await V(n,t,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let i;try{let a=await r.text(),u=JSON.parse(a);i={cause:u.error??u}}catch{}throw new P({message:"Could not get token from Google Identity",extensionMembers:i})}return await r.json()}s(Ei,"fetchToken");var K=class t{static{s(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:n}){this.#t=e,this.#e=n}static async init(e){let n=JSON.parse(e),r=await(0,Ft.importPKCS8)(n.private_key.trim(),"RS256");return new t({serviceAccount:n,privateKey:r})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};var jt=class extends U{constructor(n){super();this.options=n}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new ut(this.options)}},hc="https://logging.googleapis.com/v2/entries:write?alt=json",yr={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},ut=class{static{s(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=h.instance.loggingEnvironmentType,this.#i=h.instance.loggingEnvironmentStage,this.#r=h.instance.deploymentName}#e;#t;#n;#r;#o;#i;async init(){this.#t=await K.init(this.#e)}log(e,n){if(!this.#t)throw new T("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:he(e.messages)},o=this.#t.projectId??"zuplo-production",i={logName:this.#n,resource:{type:"global"},severity:yr[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(i.labels.rayId=e.rayId);let a=He(r.allMessages);i.jsonPayload={...r,message:a},this.batcher.enqueue(i),n.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await K.init(this.#e));let n=await oe({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await fetch(hc,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${n}`,"content-type":"application/json;charset=UTF-8"}});r.ok||console.error(r.status,r.statusText,await r.text())};batcher=new C("google-log-transport",1,this.dispatchFunction)};var zt="gcp";function Vt(t){let e={allMessages:he(t.messages)},n="zuplo-production",r=He(e.allMessages),o={logName:`projects/${n}/logs/runtime-user`,message:r,severity:yr[t.level],timestamp:t.timestamp,"logging.googleapis.com/labels":{buildId:t.buildId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},"logging.googleapis.com/trace":`projects/${n}/traces/${t.requestId}`,allMessages:e.allMessages};return t.rayId&&(o["logging.googleapis.com/labels"].rayId=t.rayId),o}s(Vt,"gcpLogFormat");var ct=class{static{s(this,"ConsoleTransport")}constructor(e,n){this.#e=e??console,this.#t=n}#e;#t;log(e){if(this.#t===zt){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Vt(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,level:e.level,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId}])}};var Gt=class extends U{constructor(n){super();this.options=n}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new lt(this.options)}},br="__ddtags",wr="__ddattr",Rr=s(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),yc=s(t=>{let e=Object.keys(t),n=[];return e.forEach(r=>{let o=t[r];o==null?n.push(Rr(r)):n.push(`${Rr(r)}:${Rr(o.toString())}`)}),n.join(",")},"formatTags"),lt=class{static{s(this,"DataDogTransport")}constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=h.instance.loggingEnvironmentType,this.#o=h.instance.loggingEnvironmentStage,this.#n=h.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){let r={},o=n.custom[br];o&&typeof o=="object"&&Object.assign(r,o);let i=[...e.messages],a=e.messages.findIndex(g=>g[br]!==void 0);a>-1&&(Object.assign(r,i[a][br]),i.splice(a,1));let u={},c=n.custom[wr];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(g=>g[wr]!==void 0);l>-1&&(Object.assign(u,i[l][wr]),i.splice(l,1));let d=he(i),b={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(n.originalRequest.url).hostname,msg:He(d),service:e.loggingId,ddtags:yc(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(b,u),this.batcher.enqueue(b),n.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new C("data-dog-transport",10,this.dispatchFunction)};var dt=class{static{s(this,"ProcessTransport")}constructor(e,n){this.#e=e,this.#t=n}#e;#t;log(e){if(this.#t===zt){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Vt(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 bc=s(({url:t,remoteLogToken:e,loggingId:n,sendOnlyErrors:r})=>async o=>{let i;if(r===!0?i=o.filter(a=>a.level==="error"):i=o,i.length!==0)try{await fetch(`${t}/publish/${n}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:i.map(a=>({...a,messages:he(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":h.instance.systemUserAgent,"zp-dn":h.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Wt,Kt=class{static{s(this,"RemoteLogTransport")}constructor(e){Wt||(Wt=new C("remote-log-transport",1,bc(e)))}log(e,n){Wt.enqueue(e),n.waitUntil(Wt.waitUntilFlushed())}};var wc={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},xi=s((t,e)=>n=>{let r={};return r.deploymentName=t,r.labels={requestId:n.requestId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},r.rayId=n.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=n.vectorClock,{timestamp:n.timestamp,observerdTimestamp:n.timestamp,traceId:n.requestId,severityText:n.level,severityNumber:wc[n.level],body:n.messages,attributes:r}},"unifiedFormatter");var Rc=s(({url:t,remoteLogToken:e,deploymentName:n,build:r})=>async o=>{if(o.length===0)return;let i=xi(n,r);try{await fetch(`${t}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(i)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":h.instance.systemUserAgent,"zp-dn":h.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Jt,Yt=class{static{s(this,"UnifiedLogTransport")}constructor(e){Jt||(Jt=new C("unified-log-transport",1,Rc(e)))}async log(e,n){Jt.enqueue(e),n.waitUntil(Jt.waitUntilFlushed())}};var Pr=(0,vi.debug)("zuplo:logging"),Qt=class t{static{s(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:n}){this.systemCoreLogger=e,this.userCoreLogger=n}static async init(e){let n=await t.setupSystemCoreLogger(h.instance,e),r=await t.setupUserCoreLogger(h.instance,e);return new t({systemCoreLogger:n,userCoreLogger:r})}static async setupSystemCoreLogger(e,n){let{build:r}=e;Pr("Gateway.setupSystemCoreLogger");let o=[],i=n.getService(it);return i?o.push(new dt(i.logger,e.logFormat)):e.isDeno&&o.push(new ct(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Yt({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 st(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,n){Pr("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:i}=e,a=n.getService(it);if(a&&a.captureUserLogs===!0?r.push(new dt(a.logger,e.logFormat)):e.isDeno&&r.push(new ct(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new Kt({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:e.isCloudflare})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new ut({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME})),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new lt({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return ge.forEach(u=>{u instanceof U&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new st(e.userLogLevel,"user",e.loggingId,i.BUILD_ID,r)}createRequestLoggers(e,n,r,o,i){Pr("Gateway.createRequestLoggers");let a=new qt(r,o,i),u=new at(e,n,this.systemCoreLogger,a);return{userRequestLogger:new at(e,n,this.userCoreLogger,a),systemRequestLogger:u}}};var Te=class{static{s(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 Ir=class{static{s(this,"RouterEntry")}constructor(e,n,r,o){this.fullPath=e,this.urlPattern=n,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},Me=class{static{s(this,"LookupResult")}constructor(e,n,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=n}executableHandler;routeConfiguration;params},Er=class extends Error{static{s(this,"RouterError")}constructor(e,n){super(e,n)}},Ne=class{static{s(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,n){if(!(e instanceof Te||e instanceof k))throw new T("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(i=>i.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let i=new URLPattern({pathname:o}),a=new Ir(o,i,e,n);Object.freeze(a.config),this.routeEntries.push(a)}catch(i){throw new Er(`addRoute-error: Invalid path '${o}'. '${i.message}'`,{cause:i})}}lookup(e,n){if(typeof e>"u")throw new m(`Invalid request - Method was undefined. Path: '${n}'`);let r=this.routeEntries.filter(o=>o.config.methods.includes(e));if(r.length!==0)for(let o=0;o<r.length;o++){let i=r[o],u=i.urlPattern.exec({pathname:n});if(u!==null)return new Me(i.config,i.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let n=[];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 Me(o.config,o.executableHandler,a.pathname.groups);n.push(u)}}return n}};var ie=(0,Si.debug)("zuplo:runtime"),Pc=s(t=>{let e=t.findIndex(n=>n.name===nt.name);return e>-1?[...t.splice(e),nt]:[...t,nt]},"setupSystemNoVersion"),N=class t{constructor(e,n,r,o){this.routeData=e;this.runtimeSettings=n;this.schemaValidator=o;ie("Gateway.constructor"),this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{s(this,"Gateway")}static#e;static async initialize(e,n,r,o,i){if(ie("Gateway.initialize"),!t.#e){await ei(i);let a=await Qt.init(r),u=e(),c={...u,corsPolicies:ai(u.corsPolicies)},l=new t(c,n,a,o);t.#e=l}return t.#e}static purgeGatewayCache(){ie("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new T("Gateway cannot be used before it is initialized");return t.#e}instanceId=crypto.randomUUID();#t;#n;#r=[Zt,Mt,B];#o;setupRoutes=()=>{ie("Gateway.setupRoutes");let e=this.routeData,n=Pc(e.versions),r=new Ne(n);if(e.routes.length===0)return er(r,this),ur(r,this),sr(r,this),ui(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(yi(r,this),hi(r,this)),er(r,this),ur(r,this),sr(r,this);for(let i of ge)i instanceof ae&&i.registerRoutes(r,this);return e.routes.forEach(i=>{let a;if(typeof i.handler?.module=="object"&&(a=i.handler?.module[i.handler.export]),typeof a!="function")throw new m(`Invalid state - No handler on route for path '${i.path}'`);let u=new D({processors:this.#r,handler:a,gateway:this}),c=new Te(i);r.addRoute(c,u.execute)}),ci(r,this),r};setupErrorHandler=()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new m("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=s((n,r,o)=>this.#i(n,r,o),"errorHandler");return e};errorHandler(e,n,r){try{return this.#o(e,n,r)}catch(o){return ie("An error occurred in the user's errorHandler",o),this.#i(e,n,o)}}#i(e,n,r){ie("Gateway.internalErrorResponse");let o={};if(h.instance.isDeno){if(r instanceof P&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let i=z(r.cause);"stack"in i&&(i.stack=Ri(i.stack)),o={cause:i}}}return R.internalServerError(e,n,{detail:r.message,...o})}#s(e){let n=new Headers(e.headers);return Oo.forEach(r=>{n.delete(r)}),h.instance.isDeno&&Co.forEach(r=>{n.delete(r)}),new Request(e,{headers:n})}async handleRequest(e,n){let r=e.headers.get(Ye)??e.headers.get(Ro),o=e.headers.get(_e);if(!r){r=crypto.randomUUID();let E=new Headers(e.headers);E.set(Ye,r),e=new Request(e,{headers:E})}if(["GET","HEAD"].includes(e.method)&&e.body){let E=new Headers(e.headers);E.set(Po,"true"),e=new Request(e,{headers:E,body:null})}let i={},{userRequestLogger:a,systemRequestLogger:u}=this.#t.createRequestLoggers(r,o,n,i,e),c=new URL(e.url),l=c.pathname,d=this.#n.lookup(e.method,l);if(!d)throw new T(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let p=new Xt(e.headers),b=this.#s(e),g=new A(b,{params:d.params}),w=new en({logger:a,route:d.routeConfiguration,requestId:r,event:n,custom:i,incomingRequestProperties:p}),I=F.initialize(w,g);if(d.routeConfiguration===ar&&et.value?.notFoundHandler!==void 0){let E=this.#n.lookupByPathOnly(l);I.pathOnlyMatches=E.map(x=>x.routeConfiguration).filter(x=>x instanceof Te)}try{if(O.addLogger(w,u),h.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!tt(c):!c.pathname.startsWith("/__zuplo")){let L=await Yo(g,w);if(L instanceof Response)return L;{let $=F.getContextExtensions(w);g=L,$.latestRequest=g}}tt(c)||a.debug(`Request received '${c.pathname}'`,{method:e.method,url:c.pathname,hostname:c.hostname,route:d.routeConfiguration.path});let E=d.executableHandler;Ic(E,d,e),ie("Gateway.handleRequest - call user handler");let x=await E(g,w);if(ie("Gateway.handleRequest - user handler"),!(x instanceof Response))throw new P(`Invalid Response type from the request handler: ${typeof x}`);if(x.bodyUsed)throw new P("The response object has already been used. Return a new response instead.");if(x.headers.get(Ye)===null&&!x.webSocket){let L=new Headers(x.headers);return L.set(Ye,r),new Response(x.body,{status:x.status,statusText:x.statusText,headers:L,cf:x.cf})}else return x}catch(E){return ie("Gateway - error executing handler",E),E instanceof P?(a.error(E),u.warn(E)):u.error(E),await this.#i(g,w,E)}}};function Ic(t,e,n){if(ie("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new m(`Invalid state - no routeConfiguration for '${n.method}:${n.url}`):new m(`Invalid state. No handler for request '${n.method}':'${e.routeConfiguration.path}'`)}s(Ic,"checkHandler");var Ti=s(async(t,e,n)=>{let r=N.instance.routeData.policies,o=ot([t],r);if(o.length===0)throw new P(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);return o[0].handler(e,n)},"invokeInboundPolicy");var Xt=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Nn);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Zn)??void 0}get city(){return this.#e.get(kn)??this.#e.get(Io)??void 0}get continent(){return this.#e.get(Dn)??this.#e.get(Eo)??void 0}get country(){return this.#e.get(Un)??this.#e.get(xo)??void 0}get latitude(){return this.#e.get(Mn)??this.#e.get(So)??void 0}get longitude(){return this.#e.get(Hn)??this.#e.get(vo)??void 0}get colo(){return this.#e.get(qn)??void 0}get postalCode(){return this.#e.get($n)??void 0}get metroCode(){return this.#e.get(Fn)??void 0}get region(){return this.#e.get(Bn)??void 0}get regionCode(){return this.#e.get(jn)??void 0}get timezone(){return this.#e.get(zn)??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}}},ke=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},De=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,n){super("responseSent"),this.request=e,this.response=n}request;response},F=class t{static{s(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,n){if(!t.#e.has(e)){let r=new t(n);return t.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let n=t.#e.get(e);if(!n)throw new P(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return n}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,n,r)=>{for(let o of this.#t)await o(e,n,r)};onResponseSending=async(e,n,r)=>{let o=e;for(let i of this.#n)o=await i(e,n,r);return o}},en=class extends EventTarget{static{s(this,"SystemZuploContext")}constructor({logger:e,route:n,requestId:r,event:o,custom:i,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=n,this.requestId=r,this.custom=i,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>Ti(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{F.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{F.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,n,r){let o=s(i=>{try{typeof n=="function"?n(i):n.handleEvent(i)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var ye=class t{static{s(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,n){t.set(e,this.#t,n)}get(e){return t.get(e,this.#t)}static set(e,n,r){t.#e||(t.#e=new WeakMap);let o=t.#e.get(e);o||(o=new Map),o.set(n,r),t.#e.set(e,o)}static get(e,n){return t.#e||(t.#e=new WeakMap),t.#e.get(e)?.get(n)}};var Ec=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function xr(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!Ec.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}s(xr,"isRestrictedEnvVariableName");function vr(t){return!!t.startsWith("ZUPLO_")}s(vr,"isZuploReadableEnvVariableName");var j=new Proxy({},{get(t,e){if(xr(String(e))&&!vr(String(e)))return;let n=globalThis,r;return n.process?r=n.process.env[e]:r=n[e],r}});var Ci=Ae(Pe());var X=(0,Ci.debug)("zuplo:runtime:external-service");function Ai(){let t,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=h.instance.runtime;if(e&&e!=="undefined")try{let n=atob(e);t=JSON.parse(n)}catch{}return t}s(Ai,"getServiceAuth");async function Li(t){let e=Ai();if(!e)throw X("There is no external service auth configured for this zup."),new P("There are no external services configured for this zup.");if(typeof t!="string")throw X("Cannot call external service with Request object"),new P("Currently, we only support fetch(<some_string>, ...).");let r=new URL(t).hostname,o={};o["CF-Access-Client-Id"]=e.clientId,o["CF-Access-Client-Secret"]=e.clientSecret;let i;if(e.customServiceMapping&&e.customServiceMapping[r])i=`https://${e.customServiceMapping[r]}`;else if(h.instance.useSha256ServiceRouting){X("Using sha256 service routing");let a=h.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE)i=`https://${await ki(r,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw X("Cannot use sha256 service routing, missing build variables"),new P("Failed to generate fully qualified tunnel url.")}else i=`https://${r}.zuptunnel.com`;return{serviceBaseUrl:i,tunnelHeaders:o}}s(Li,"externalServiceTunnelConfig");async function _i(t,e){let n=Ai();if(n)if(X(`Using external service auth. ClientId: ${n.clientId})`),typeof t=="string"){let r=new URL(t),o=r.hostname,i=e??{},a=new Headers(i.headers||{});a.set("CF-Access-Client-Id",n.clientId),a.set("CF-Access-Client-Secret",n.clientSecret),i.headers=a;let u;if(n.customServiceMapping&&n.customServiceMapping[o])u=`https://${n.customServiceMapping[o]}`;else if(h.instance.useSha256ServiceRouting){X("Using sha256 service routing");let d=h.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await ki(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw X("Cannot use sha256 service routing, missing build variables"),new P("Failed to generate fully qualified tunnel url.")}else u=`https://${o}.zuptunnel.com`;let c=new URL(`${u}${r.pathname}${r.search}`);X(`Calling external service: ${c.toString()}`);let l=await Ze(c.toString(),i);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:n.clientId,tunnelHost:u}),new P("Could not connect to secure tunnel.");return l}else throw X("Cannot call external service with Request object"),new P("Currently, we only support fetch(<some_string>, ...).");else throw X("There is no external service auth configured for this zup."),new P("There are no external services configured for this zup.")}s(_i,"externalServiceHandler");async function ki(t,e,n,r){let o=t.toLowerCase(),i=e.toLowerCase(),a=n.toLowerCase(),u=xc(r);X(`Hashing service name: ${i}-${o}.${i}-${a}-${u}`);let c=await Oi(`${i}-${o}`),l=await Oi(`${i}-${a}-${u}`);return`${c}.${l}`}s(ki,"hashServiceName");async function Oi(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("").slice(0,-1)}s(Oi,"hashSegment");function xc(t){let e=t.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}s(xc,"sanitizeEnvironmentType");var Di=new Map;Di.set("service:",_i);var Ze=globalThis.fetch;globalThis.fetch=function(t,e){let n=vc(e);if(typeof t=="string"){let r=new URL(t),o=Di.get(r.protocol);return o?o(t,n):Ze(t,n)}else return Ze(t,n)};var vc=s(t=>{if(!t||t instanceof Request)return t;let e=t;if(!e.zuplo)return t;let n=t;return n.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete t.zuplo,t},"transformInit");var Ui=s(()=>{N.purgeGatewayCache()},"purgeGatewayCache"),tn=class{constructor(e,n,r,o,i,a,u){this.routeLoader=e;this.buildEnvironment=n;this.runtimeEnvironment=r;this.runtimeSettings=o;this.serviceProvider=i;this.schemaValidations=a;this.runtimeInit=u}static{s(this,"Handler")}requestHandler=async(e,n)=>{h.initialize(this.buildEnvironment,this.runtimeEnvironment);let r;try{r=await N.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations,this.runtimeInit)}catch(o){console.error("Error initializing gateway.",o);let i="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.";o instanceof m&&(i=o.message);let a={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:i,instance:e.url,trace:{timestamp:Date.now(),rayId:e.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:h.instance.isDeno?o.message:void 0};return new Response(JSON.stringify(a,null,2),{status:500,headers:{"content-type":"application/json"}})}return r.handleRequest(e,n)}};var ji=Ae(Pe());function Sc(t){for(var e=[],n=0;n<t.length;){var r=t[n];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:n,value:t[n++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:n++,value:t[n++]});continue}if(r==="{"){e.push({type:"OPEN",index:n,value:t[n++]});continue}if(r==="}"){e.push({type:"CLOSE",index:n,value:t[n++]});continue}if(r===":"){for(var o="",i=n+1;i<t.length;){var a=t.charCodeAt(i);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=t[i++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(n));e.push({type:"NAME",index:n,value:o}),n=i;continue}if(r==="("){var u=1,c="",i=n+1;if(t[i]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(i));for(;i<t.length;){if(t[i]==="\\"){c+=t[i++]+t[i++];continue}if(t[i]===")"){if(u--,u===0){i++;break}}else if(t[i]==="("&&(u++,t[i+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(i));c+=t[i++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(n));if(!c)throw new TypeError("Missing pattern at ".concat(n));e.push({type:"PATTERN",index:n,value:c}),n=i;continue}e.push({type:"CHAR",index:n,value:t[n++]})}return e.push({type:"END",index:n,value:""}),e}s(Sc,"lexer");function Sr(t,e){e===void 0&&(e={});for(var n=Sc(t),r=e.prefixes,o=r===void 0?"./":r,i="[^".concat(Oc(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=s(function(Y){if(c<n.length&&n[c].type===Y)return n[c++].value},"tryConsume"),p=s(function(Y){var Q=d(Y);if(Q!==void 0)return Q;var Oe=n[c],Ce=Oe.type,An=Oe.index;throw new TypeError("Unexpected ".concat(Ce," at ").concat(An,", expected ").concat(Y))},"mustConsume"),b=s(function(){for(var Y="",Q;Q=d("CHAR")||d("ESCAPED_CHAR");)Y+=Q;return Y},"consumeText");c<n.length;){var g=d("CHAR"),w=d("NAME"),I=d("PATTERN");if(w||I){var E=g||"";o.indexOf(E)===-1&&(l+=E,E=""),l&&(a.push(l),l=""),a.push({name:w||u++,prefix:E,suffix:"",pattern:I||i,modifier:d("MODIFIER")||""});continue}var x=g||d("ESCAPED_CHAR");if(x){l+=x;continue}l&&(a.push(l),l="");var L=d("OPEN");if(L){var E=b(),$=d("NAME")||"",_=d("PATTERN")||"",G=b();p("CLOSE"),a.push({name:$||(_?u++:""),pattern:$&&!_?i:_,prefix:E,suffix:G,modifier:d("MODIFIER")||""});continue}p("END")}return a}s(Sr,"parse");function Hi(t,e){return Tc(Sr(t,e),e)}s(Hi,"compile");function Tc(t,e){e===void 0&&(e={});var n=Cc(e),r=e.encode,o=r===void 0?function(c){return c}:r,i=e.validate,a=i===void 0?!0:i,u=t.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),n)});return function(c){for(var l="",d=0;d<t.length;d++){var p=t[d];if(typeof p=="string"){l+=p;continue}var b=c?c[p.name]:void 0,g=p.modifier==="?"||p.modifier==="*",w=p.modifier==="*"||p.modifier==="+";if(Array.isArray(b)){if(!w)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(b.length===0){if(g)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var I=0;I<b.length;I++){var E=o(b[I],p);if(a&&!u[d].test(E))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(E,'"'));l+=p.prefix+E+p.suffix}continue}if(typeof b=="string"||typeof b=="number"){var E=o(String(b),p);if(a&&!u[d].test(E))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(E,'"'));l+=p.prefix+E+p.suffix;continue}if(!g){var x=w?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(x))}}return l}}s(Tc,"tokensToFunction");function Oc(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(Oc,"escapeString");function Cc(t){return t&&t.sensitive?"":"i"}s(Cc,"flags");var qi=Ae(Pe());var Ac=(0,qi.debug)("zuplo:runtime"),Or=new TextEncoder,Mi={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"},Lc=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],qe=class{static{s(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:n,sessionToken:r,service:o,region:i,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(n==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=n,this.sessionToken=r,this.service=o,this.region=i,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,n){let r=new Cr(Object.assign({url:e},n,this,n&&n.aws)),o=Object.assign({},n,await r.sign());return delete o.aws,{url:o.url.toString(),request:o}}async fetch(e,n){Ac("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:i}=await this.sign(e,n),a=fetch(o,i);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new m("An unknown error occurred, ensure retries is not negative")}},Cr=class{static{s(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:n,headers:r,body:o,accessKeyId:i,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:b,appendSessionToken:g,allHeaders:w,singleEncode:I}){if(n==null)throw new TypeError("url is a required option");if(i==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(n),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=i,this.secretAccessKey=a,this.sessionToken=u;let E,x;(!c||!l)&&([E,x]=_c(this.url,this.headers)),this.service=c||E||"",this.region=l||x||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=b,this.appendSessionToken=g||this.service==="iotdevicegateway",this.headers.delete("Host");let L=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"),L.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&L.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(_=>w||!Lc.includes(_)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(_=>_+":"+(_==="host"?this.url.host:(this.headers.get(_)||"").replace(/\s+/g," "))).join(`
57
+ `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!L.has("X-Amz-Expires")&&L.set("X-Amz-Expires","86400"),L.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),L.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),L.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,"/");I||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=Zi(this.encodedPath);let $=new Set;this.encodedSearch=[...this.url.searchParams].filter(([_])=>{if(!_)return!1;if(this.service==="s3"){if($.has(_))return!1;$.add(_)}return!0}).map(_=>_.map(G=>Zi(encodeURIComponent(G)))).sort(([_,G],[Y,Q])=>_<Y?-1:_>Y?1:G<Q?-1:G>Q?1:0).map(_=>_.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),n=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(n);if(!r){let o=await pt("AWS4"+this.secretAccessKey,e),i=await pt(o,this.region),a=await pt(i,this.service);r=await pt(a,"aws4_request"),this.cache.set(n,r)}return Tr(await pt(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Tr(await Ni(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 I("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Tr(await Ni(this.body||""))}return e}};async function mt(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?Or.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",n,Or.encode(e))}s(mt,"hmac");async function Ni(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?Or.encode(t):t)}s(Ni,"hash");function Tr(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}s(Tr,"buf2hex");function Zi(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}s(Zi,"encodeRfc3986");function Cc(t,e){let{hostname:n,pathname:r}=t,o=n.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[i,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",i="s3";else if(i==="iot")n.startsWith("iot.")?i="execute-api":n.startsWith("data.jobs.iot.")?i="iot-jobs-data":i=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(i==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?i="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(i="autoscaling-plans")}else a==null&&i.startsWith("s3-")?(a=i.slice(3).replace(/^fips-|^external-1/,""),i="s3"):i.endsWith("-fips")?i=i.slice(0,-5):a&&/-\d$/.test(i)&&!/-\d$/.test(a)&&([i,a]=[a,i]);return i in Mi?[Mi[i],a]:[i,a]}s(Cc,"guessServiceRegion");function Ac(t){return t>64&&t<91?t-65:t>96&&t<123?t-71:t>47&&t<58?t+4:t===43?62:t===47?63:0}s(Ac,"b64ToUint6");function $i(t,e){let n=t.replace(/[^A-Za-z0-9+/]/g,""),r=n.length,o=e?Math.ceil((r*3+1>>2)/e)*e:r*3+1>>2,i=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=Ac(n.charCodeAt(d))<<6*(3-u),u===3||r-d===1){for(a=0;a<3&&l<o;)i[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return i}s($i,"base64Decode");function nn(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}s(nn,"uint6ToB64");function Fi(t){let e=2,n="",r=t.length,o=0;for(let i=0;i<r;i++)e=i%3,o|=t[i]<<(16>>>e&24),(e===2||t.length-i===1)&&(n+=String.fromCodePoint(nn(o>>>18&63),nn(o>>>12&63),nn(o>>>6&63),nn(o&63)),o=0);return n.substring(0,n.length-2+e)+(e===2?"":e===1?"=":"==")}s(Fi,"base64Encode");function $e(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}s($e,"numberToString");function Lc(t){let e=t.getTimezoneOffset(),n=Math.abs(e),r=e>0?"-":"+",o=$e(Math.floor(n/60)),i=$e(n%60);return`${r}${o}${i}`}s(Lc,"getCLFOffset");function Ar(t=new Date){if(!(t instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=$e(t.getDate()),r=e[t.getMonth()],o=t.getFullYear(),i=$e(t.getHours()),a=$e(t.getMinutes()),u=$e(t.getSeconds()),c=Lc(t);return`${n}/${r}/${o}:${i}:${a}:${u} ${c}`}s(Ar,"toCLFDate");var Bi=(0,ji.debug)("zuplo:runtime"),_c="X-Amzn-Trace-Id",kc="x-amzn-errortype",zi=[],Dc=s(async(t,e,n)=>{let r=n;for await(let o of zi)r=await o(t,e,n);return r},"onSendingAwsLambdaEvent"),J=class extends I{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,n){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=n.get(_c)??void 0,this.errorType=n.get(kc)??void 0}},Vi={addSendingAwsLambdaEventHook:t=>{zi.push(t)}};async function Gi(t,e){let{accessKeyId:n,secretAccessKey:r,region:o,functionName:i,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!n)throw new g("awsAccessKeyId is not set in the handler options");if(!r)throw new g("secretAccessKey is not set in the handler options");if(!o)throw new g("region is not set in the handler options");if(!i)throw new g("functionName is not set in the handler options");let l=new qe({accessKeyId:n,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(Bi(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,y]=await Nc(t,{binaryMediaTypes:c}),{options:m}=e.route.handler,w;m&&typeof m=="object"&&"payloadFormatVersion"in m&&m.payloadFormatVersion==="2.0"?w=Mc(t,e):w=await Hc(t,e,{useAwsResourcePathStyle:u}),Bi("Calling onSendingAwsLambdaEvent hook");let P=await Dc(t,e,w);P.body=p,P.isBase64Encoded=y;let E=await l.fetch(d,{body:JSON.stringify(P)});try{return Uc(E)}catch(x){if(x instanceof J){let A=m&&typeof m=="object"&&"returnAmazonTraceIdHeader"in m&&m.returnAmazonTraceIdHeader&&x.traceId?{AMZN_TRACE_ID_HEADER:x.traceId}:void 0;return R.internalServerError(t,e,void 0,A)}throw x}}s(Gi,"awsLambdaHandler");async function Uc(t){let e;try{e=await t.json()}catch{throw new J("Lambda response did not contain valid JSON",t.headers)}if(t.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new J(e.message,t.headers):new J(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new J(e.errorMessage,t.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:t.status,headers:{"content-type":"application/json"}});let n=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new J(`Response headers must be an object. Received ${typeof e.headers}`,t.headers);for(let[o,i]of Object.entries(e.headers))n.set(o,i)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new J(`Response cookies must be an array. Received ${typeof e.cookies}`,t.headers);n.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new J(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,t.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new J("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new J("Response was set to base64 encoded but body was not a string",t.headers);r=$i(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 J(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,t.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:n,status:e.statusCode})}s(Uc,"getResponse");async function Hc(t,e,{useAwsResourcePathStyle:n}){let r={},o={};t.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let i=t.query,a={};for(let[l,d]of Object.entries(i))a[l]=[d];let u=new URL(t.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:t.method,headers:r,multiValueHeaders:o,queryStringParameters:i,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:t.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:t.headers.get("CF-Connecting-IP"),user:null,userAgent:t.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:Ar(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:qc(e.route.path,n),stage:null},pathParameters:t.params,stageVariables:null}}s(Hc,"buildEventVersion1");function Mc(t,e){let n={};t.headers.forEach((i,a)=>{n[a]=i});let r=new URL(t.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:n,queryStringParameters:t.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:t.method,path:r.pathname,protocol:"HTTP/1.1",sourceIp:t.headers.get("CF-Connecting-IP"),userAgent:t.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:Ar(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}s(Mc,"buildEventVersion2");async function Nc(t,{binaryMediaTypes:e}){let n,r=!1,o=t.headers.get("content-type");if(t.method==="GET"||t.method==="HEAD")n=null;else if(e&&o&&Zc(e,o)){let i=await t.arrayBuffer();n=Fi(new Uint8Array(i)),r=!0}else n=await t.clone().text();return[n,r]}s(Nc,"getBodyResult");function Zc(t,e){let n=e.split(";")[0].trim().toLowerCase();return t.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===n)>-1}s(Zc,"matchesContentType");function qc(t,e=!1){if(!e)return t;let n=Sr(t),r=Hi(t),o={};return n.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),r(o)}s(qc,"getResourcePath");var $c=[502,503,504];async function Fe(t,e){if($c.includes(t.status)){let n=O.getLogger(e),o=await t.clone().text(),i={};for(let[a,u]of t.headers)i[a]=u;n.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:o,headers:i})}}s(Fe,"logBadGatewayResponses");var Lr;function be(t){if(Lr===void 0){let n=h.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(n??"")||(n="debug"),Lr=n}return t.log[Lr]}s(be,"getHandlerUserLogFunction");async function Wi(t,e){let n=h.instance.build.BUILD_ID,{buildAssetsUrl:r}=h.instance,o=e.route.handler.options,{openApiFilePath:i}=o;if(!i)throw new g("Open API Spec Handler must have 'openApiFilePath' specified");let a=Fc(i);if(!a.isValid)throw new g(a.error);let u;h.instance.isLocalDevelopment?u=`${r}/${i.substring(1)}`:u=`${r}/${n}${i.substring(1)}`;let c=await fetch(u,{method:t.method,body:t.body,headers:t.headers});if(c.status!==200)return R.notFound(t,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 Fe(l,e),l}s(Wi,"openApiSpecHandler");var Fc=s(t=>t.startsWith("./")?t.startsWith("./config")?t.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 Ki(t,e){let n=e.route.handler.options;if(!n.location)throw new g("Redirect Handler must have 'location' specified");let r=n.status??302;return new Response(null,{status:r,headers:{location:n.location}})}s(Ki,"redirectHandler");function Bc(t,e){let n=t.endsWith("/"),r=e.startsWith("/");return n&&r?`${t.substring(0,t.length-1)}${e}`:!n&&!r?`${t}/${e}`:`${t}${e}`}s(Bc,"join");async function Ji(t,e){let n=be(e),r=e.route.handler.options,o=r.forwardSearch!==!1;if(!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new g("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(t.url),u=r.__rewriteFunction(t,i),c=Bc(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();n(`URL Forwarding to '${l}'`);let p=await fetch(l,{method:t.method,body:t.body,headers:t.headers}),y=Date.now()-d;return n(`URL Forward received response ${p.status} - ${p.statusText} in ${y}ms`),Fe(p,e),p}s(Ji,"urlForwardHandler");var jc=s((t,e)=>{let n=new URL(t),r=new URL(e);for(let[o,i]of r.searchParams.entries())n.searchParams.append(o,i);return n.toString()},"addQuery");async function Yi(t,e){let n=be(e),r=e.route.handler.options,o=r.forwardSearch!==!1,i=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new g("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=o?jc(u,t.url):u,l=Date.now();n(`URL Rewriting to '${c}'`);let d=await fetch(c.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:i?"follow":"manual"}),p=Date.now()-l;return n(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),Fe(d,e),d}s(Yi,"urlRewriteHandler");async function Qi(t,e){let n=h.instance,r=e.route.handler.options,o=be(e);if(!r||!r.rewritePattern)throw new g("WebSocket Handler must have option 'rewritePattern' specified");let i=t.headers.get("Upgrade");if(!i||i!=="websocket")return R.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new g("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno){let p=new Headers(t.headers);if(u.startsWith("service:")){let m=await Li(u),w=new URL(u);u=new URL(`${m.serviceBaseUrl}${w.pathname}${w.search}`).toString();for(let E in m.tunnelHeaders)p.set(E,m.tunnelHeaders[E])}u=u.replace(/^(http)/,"ws");try{if(p.get("Authorization")){let m=p.get("Authorization")?.replace("Bearer ","");u+=`?apiKey=${m}`}}catch{}let y=JSON.stringify({url:u});return new Response(y,{headers:p})}u=u.replace(/^(ws)/,"http");let l=await fetch(u,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let p=await l.text(),y=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${p}'`;throw new Error(y)}let d=Date.now()-c;return o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${d}ms`),new Response(null,{status:101,webSocket:l.webSocket})}s(Qi,"webSocketHandler");var _r=s((t,e)=>t.map((r,o)=>{let i;if(typeof r.module=="object"&&(i=r.module[r.export]),!i||typeof i!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${o+1}, export name: ${r.export}`;throw new g(`${a} - Websocket policy must be a valid function (${u})`)}return i}),"getWebSocketPolicyFunctions"),Xi=s(async(t,e,n,r,o,i)=>{let a=t.data;if(i&&i.length>0){let u=[...i];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,n,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function es(t,e,n,r,o){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",i=>{r.log.error("WebSocket error: ",i),e.send(JSON.stringify(i))}),t.addEventListener("message",i=>{try{let u=s(async c=>{let l=await Xi(c,t,e,n,r,o);l!==void 0&&e.send(l)},"innerPipeline")(i).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}s(es,"wireUpListeners");async function ts(t,e){let n=h.instance,r=e.route.handler.options,o=be(e);if(!r||!r.rewritePattern)throw new g("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let i=t.headers.get("Upgrade");if(!i||i!=="websocket")return R.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new g("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno)throw new g("Websocket pipeline handler is currently not supported on working-copy environments");u=u.replace(/^(ws)/,"http");let l=await fetch(u,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let x=await l.text(),A=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${x}'`;throw new Error(A)}let d=new WebSocketPair,[p,y]=Object.values(d),m=Date.now()-c;o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${m}ms`);let w=l.webSocket;w.accept(),y.accept();let P=r.policies&&r.policies.inbound?_r(r.policies.inbound,"inbound"):[],E=r.policies&&r.policies.outbound?_r(r.policies.outbound,"outbound"):[];return es(y,w,t,e,P),es(w,y,t,e,E),new Response(null,{status:101,webSocket:p})}s(ts,"webSocketPipelineHandler");var rn=class extends M{constructor(n){super();this.options=n}static{s(this,"DynaTraceLoggingPlugin")}getTransport(){return new kr(this.options)}},kr=class{static{s(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#r=h.instance.loggingEnvironmentType,this.#o=h.instance.loggingEnvironmentStage,this.#n=h.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:ce(z(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)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{e.length!==0&&await fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new C("dyna-trace-log-transport",10,this.#i)};var on=class extends M{constructor(n){super();this.options=n}static{s(this,"LokiLoggingPlugin")}getTransport(){return new Ur(this.options)}},Dr=class{static{s(this,"LokiStream")}constructor(e,n,r,o,i){this.level=e,this.environment=n,this.environmentType=r,this.environmentStage=o,this.requestId=i}job="zuplo";level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function zc(t,e){return btoa(`${t}:${e}`)}s(zc,"createBasicDigest");var Ur=class{static{s(this,"LokiTransport")}constructor(e){this.#e=e.url,this.#t=zc(e.username,e.password),this.#r=h.instance.loggingEnvironmentType,this.#o=h.instance.loggingEnvironmentStage,this.#n=h.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){let r=new Dr(e.level,this.#n,this.#r,this.#o,e.requestId);e.messages.forEach(o=>{let i={stream:r,message:ce(z(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(i)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=e=>{let n={streams:[]};return e.forEach(r=>{let o=n.streams.find(i=>i.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},n.streams.push(o)),o.values.push([r.nanoSecondEpoch,r.message])}),n};#s=async e=>{if(e.length===0)return;let n=this.#i(e);await fetch(this.#e,{method:"POST",body:JSON.stringify(n),headers:{"content-type":"application/json",authorization:`Basic ${this.#t}`}})};batcher=new C("loki-log-transport",10,this.#s)};var sn=class extends M{constructor(n){super();this.options=n}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new Hr(this.options)}},Hr=class{static{s(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=h.instance.loggingEnvironmentType,this.#r=h.instance.loggingEnvironmentStage,this.#t=h.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:ce(z(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)}),n.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let n=e.map(o=>JSON.stringify(o)).join(`
61
- `),r=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&r.set("X-Sumo-Name",this.#i),this.#o&&r.set("X-Sumo-Category",this.#o),await fetch(this.#e,{method:"POST",body:n,headers:r})};batcher=new C("sumo-logic-log-transport",10,this.#s)};var Vc="d3a5b78f-8236-48f5-b1df-4fe269d41172",an=class extends M{constructor(n){super();this.options=n}static{s(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new Mr(this.options)}},Mr=class{static{s(this,"VMWareLogInsightTransport")}constructor(e){let n;try{n=new URL(e.url)}catch{throw new g(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=n.origin,this.#n=h.instance.loggingEnvironmentType,this.#r=h.instance.loggingEnvironmentStage,this.#t=h.instance.deploymentName,this.#o=e.onMessageSending,e.fields&&(this.#i=Object.entries(e.fields).map(([r,o])=>({name:r,content:o})))}#e;#t;#n;#r;#o;#i;log(e,n){let r=this.buildEntry(e,n);this.batcher.enqueue(r),n.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,n){let r=Pi(e.messages),o={timestamp:Date.now(),text:r,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#n},{name:"environment_stage",content:this.#r},{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.#t&&o.fields.push({name:"environment",content:this.#t}),this.#i&&o.fields.push(...this.#i),n.custom&&Object.entries(n.custom).forEach(([i,a])=>{let u=hr(a);u&&o.fields.push({name:i,content:u})}),this.#o&&(o=this.#o(o)),o}#s=async e=>{if(e.length===0)return;let n=await fetch(`${this.#e}/api/v1/events/ingest/${Vc}`,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8"}});if(n.status!==200)try{let r=await n.text();console.error("Error logging to Log Insight",r)}catch(r){console.error(r)}};batcher=new C("vmware-log-insights-log-transport",10,this.#s)};var un=class extends M{constructor(n){super();this.options=n}static{s(this,"AWSLoggingPlugin")}getTransport(){return new Nr(this.options)}},Nr=class{static{s(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new C("aws-log-transport",10,async e=>{if(e.length===0)return;let n=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:n,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}})});constructor({accessKeyId:e,logStreamName:n,logGroupName:r,secretAccessKey:o,region:i}){this.awsClient=new qe({accessKeyId:e,secretAccessKey:o,service:"logs",region:i}),this.logGroupName=r,this.logStreamName=n,this.region=i,this.environmentType=h.instance.loggingEnvironmentType,this.environment=h.instance.deploymentName}log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:ce(z(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)}),n.waitUntil(this.batcher.waitUntilFlushed())}};var Zr=new WeakMap,Gc={tags:[]},cn=class extends he{constructor(n){super();this.options=n}static{s(this,"DataDogMetricsPlugin")}getTransport(){return new qr(this.options)}static setContext(n,r){let o=Zr.get(n);o||(o=Gc);let i=Object.assign({...o},r);Zr.set(n,i)}},qr=class{static{s(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,n){this.#i===void 0&&(this.#i=new C("data-dog-metrics-transport",10,this.dispatchFunction,O.getLogger(n)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(Zr.get(n)?.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 i=e.systemRouteName||e.routePath;o.push(`path:${i}`)}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}),n.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let n=JSON.stringify({series:e}),r=await fetch(this.#t,{method:"POST",body:n,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new $r(await r.text())}},$r=class t extends Error{static{s(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var Fr=new WeakMap,Wc={dimensions:[]},ln=class extends he{constructor(n){super();this.options=n}static{s(this,"DynatraceMetricsPlugin")}getTransport(){return new Br(this.options)}static setContext(n,r){let o=Fr.get(n);o||(o=Wc);let i=Object.assign({...o},r);Fr.set(n,i)}},Br=class{static{s(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,n){this.#r===void 0&&(this.#r=new C("dynatrace-metrics-transport",10,this.dispatchFunction,O.getLogger(n)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(Fr.get(n)?.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 i=o.join(",");this.#t.latency&&this.#r.enqueue(`zuplo.request.latency,${i} ${e.durationMs} ${r}`),this.#t.requestContentLength&&e.requestContentLength&&this.#r.enqueue(`zuplo.request.content_length,${i} ${e.requestContentLength} ${r}`),this.#t.responseContentLength&&e.responseContentLength&&this.#r.enqueue(`zuplo.response.content_length,${i} ${e.responseContentLength} ${r}`),n.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let n=e.join(`
62
- `),r=await fetch(this.#e,{method:"POST",body:n,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new jr(await r.text())}},jr=class t extends Error{static{s(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var dn=class{static{s(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async n=>{await fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(n)})}))}};var pn=class extends ae{static{s(this,"AuditLogPlugin")}constructor(e,n){super(),this.#e=e,this.#t=n}#e;#t;async initialize(e){new zr(e,this.#e,this.#t)}},ns=s(t=>{let e={};return t.forEach((n,r)=>{e[r]=n}),e},"serializableHeaders"),Kc={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},zr=class{static{s(this,"AuditPluginImpl")}constructor(e,n,r){this.#t=n;let o={...Kc};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 C("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,n,r,o,i,a)=>{try{let u={timestamp:o,durationMs:i,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:n.url,method:n.method,headers:this.#e.include?.request?.headers?ns(n.headers):void 0,body:this.#e.include?.request?.body?await n.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?ns(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(u),r.waitUntil(this.#n.waitUntilFlushed())}catch(u){r.log.error(u)}};#i=async(e,n)=>{try{if(!await this.#e.requestFilter(e,n))return e;let o=new Date,i=Date.now(),a=e.clone();return n.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#o(d,a,n,o,l-i,c.user?.sub).catch(y=>{n.log.error(y)});n.waitUntil(p)}),e}catch(r){return n.log.error(r),e}}};var Vr=class extends Error{static{s(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}},se=class extends Vr{static{s(this,"StripeSignatureVerificationError")}header;payload;constructor(e,n,r={}){super(r),this.header=e,this.payload=n}};var Jc="v1",Yc=300;async function rs(t,e,n,r=Yc,o){return await Xc(t,e,n,r,o),t instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(t)):JSON.parse(t)}s(rs,"constructEventAsync");function Qc(t,e){return`${e.timestamp}.${t}`}s(Qc,"makeHMACContent");async function Xc(t,e,n,r,o){let{decodedHeader:i,decodedPayload:a,details:u,suspectPayloadType:c}=el(t,e,Jc),l=/\s/.test(n),d=await ol(Qc(a,u),n);return tl(a,i,u,d,r,c,l,o)}s(Xc,"verifyHeaderAsync");function el(t,e,n){if(!t)throw new se(e,t,{message:"No webhook payload was provided."});let r=typeof t!="string"&&!(t instanceof Uint8Array),o=new TextDecoder("utf8"),i=t instanceof Uint8Array?o.decode(t):t;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 se(e,t,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=nl(a,n);if(!u||u.timestamp===-1)throw new se(a,i,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new se(a,i,{message:"No signatures found with expected scheme"});return{decodedPayload:i,decodedHeader:a,details:u,suspectPayloadType:r}}s(el,"parseEventDetails");function tl(t,e,n,r,o,i,a,u){let c=!!n.signatures.filter(y=>rl(y,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 P("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Tr(await Ni(this.body||""))}return e}};async function pt(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?Or.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",n,Or.encode(e))}s(pt,"hmac");async function Ni(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?Or.encode(t):t)}s(Ni,"hash");function Tr(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}s(Tr,"buf2hex");function Zi(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}s(Zi,"encodeRfc3986");function _c(t,e){let{hostname:n,pathname:r}=t,o=n.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[i,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",i="s3";else if(i==="iot")n.startsWith("iot.")?i="execute-api":n.startsWith("data.jobs.iot.")?i="iot-jobs-data":i=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(i==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?i="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(i="autoscaling-plans")}else a==null&&i.startsWith("s3-")?(a=i.slice(3).replace(/^fips-|^external-1/,""),i="s3"):i.endsWith("-fips")?i=i.slice(0,-5):a&&/-\d$/.test(i)&&!/-\d$/.test(a)&&([i,a]=[a,i]);return i in Mi?[Mi[i],a]:[i,a]}s(_c,"guessServiceRegion");function kc(t){return t>64&&t<91?t-65:t>96&&t<123?t-71:t>47&&t<58?t+4:t===43?62:t===47?63:0}s(kc,"b64ToUint6");function $i(t,e){let n=t.replace(/[^A-Za-z0-9+/]/g,""),r=n.length,o=e?Math.ceil((r*3+1>>2)/e)*e:r*3+1>>2,i=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=kc(n.charCodeAt(d))<<6*(3-u),u===3||r-d===1){for(a=0;a<3&&l<o;)i[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return i}s($i,"base64Decode");function nn(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}s(nn,"uint6ToB64");function Fi(t){let e=2,n="",r=t.length,o=0;for(let i=0;i<r;i++)e=i%3,o|=t[i]<<(16>>>e&24),(e===2||t.length-i===1)&&(n+=String.fromCodePoint(nn(o>>>18&63),nn(o>>>12&63),nn(o>>>6&63),nn(o&63)),o=0);return n.substring(0,n.length-2+e)+(e===2?"":e===1?"=":"==")}s(Fi,"base64Encode");function $e(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}s($e,"numberToString");function Dc(t){let e=t.getTimezoneOffset(),n=Math.abs(e),r=e>0?"-":"+",o=$e(Math.floor(n/60)),i=$e(n%60);return`${r}${o}${i}`}s(Dc,"getCLFOffset");function Ar(t=new Date){if(!(t instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=$e(t.getDate()),r=e[t.getMonth()],o=t.getFullYear(),i=$e(t.getHours()),a=$e(t.getMinutes()),u=$e(t.getSeconds()),c=Dc(t);return`${n}/${r}/${o}:${i}:${a}:${u} ${c}`}s(Ar,"toCLFDate");var Bi=(0,ji.debug)("zuplo:runtime"),Uc="X-Amzn-Trace-Id",Hc="x-amzn-errortype",zi=[],Mc=s(async(t,e,n)=>{let r=n;for await(let o of zi)r=await o(t,e,n);return r},"onSendingAwsLambdaEvent"),J=class extends P{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,n){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=n.get(Uc)??void 0,this.errorType=n.get(Hc)??void 0}},Vi={addSendingAwsLambdaEventHook:t=>{zi.push(t)}};async function Gi(t,e){let{accessKeyId:n,secretAccessKey:r,region:o,functionName:i,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!n)throw new m("awsAccessKeyId is not set in the handler options");if(!r)throw new m("secretAccessKey is not set in the handler options");if(!o)throw new m("region is not set in the handler options");if(!i)throw new m("functionName is not set in the handler options");let l=new qe({accessKeyId:n,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(Bi(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,b]=await $c(t,{binaryMediaTypes:c}),{options:g}=e.route.handler,w;g&&typeof g=="object"&&"payloadFormatVersion"in g&&g.payloadFormatVersion==="2.0"?w=qc(t,e):w=await Zc(t,e,{useAwsResourcePathStyle:u}),Bi("Calling onSendingAwsLambdaEvent hook");let I=await Mc(t,e,w);I.body=p,I.isBase64Encoded=b;let E=await l.fetch(d,{body:JSON.stringify(I)});try{return Nc(E)}catch(x){if(x instanceof J){let L=g&&typeof g=="object"&&"returnAmazonTraceIdHeader"in g&&g.returnAmazonTraceIdHeader&&x.traceId?{AMZN_TRACE_ID_HEADER:x.traceId}:void 0;return R.internalServerError(t,e,void 0,L)}throw x}}s(Gi,"awsLambdaHandler");async function Nc(t){let e;try{e=await t.json()}catch{throw new J("Lambda response did not contain valid JSON",t.headers)}if(t.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new J(e.message,t.headers):new J(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new J(e.errorMessage,t.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:t.status,headers:{"content-type":"application/json"}});let n=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new J(`Response headers must be an object. Received ${typeof e.headers}`,t.headers);for(let[o,i]of Object.entries(e.headers))n.set(o,i)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new J(`Response cookies must be an array. Received ${typeof e.cookies}`,t.headers);n.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new J(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,t.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new J("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new J("Response was set to base64 encoded but body was not a string",t.headers);r=$i(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 J(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,t.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:n,status:e.statusCode})}s(Nc,"getResponse");async function Zc(t,e,{useAwsResourcePathStyle:n}){let r={},o={};t.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let i=t.query,a={};for(let[l,d]of Object.entries(i))a[l]=[d];let u=new URL(t.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:t.method,headers:r,multiValueHeaders:o,queryStringParameters:i,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:t.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:t.headers.get("CF-Connecting-IP"),user:null,userAgent:t.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:Ar(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Bc(e.route.path,n),stage:null},pathParameters:t.params,stageVariables:null}}s(Zc,"buildEventVersion1");function qc(t,e){let n={};t.headers.forEach((i,a)=>{n[a]=i});let r=new URL(t.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:n,queryStringParameters:t.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:t.method,path:r.pathname,protocol:"HTTP/1.1",sourceIp:t.headers.get("CF-Connecting-IP"),userAgent:t.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:Ar(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}s(qc,"buildEventVersion2");async function $c(t,{binaryMediaTypes:e}){let n,r=!1,o=t.headers.get("content-type");if(t.method==="GET"||t.method==="HEAD")n=null;else if(e&&o&&Fc(e,o)){let i=await t.arrayBuffer();n=Fi(new Uint8Array(i)),r=!0}else n=await t.clone().text();return[n,r]}s($c,"getBodyResult");function Fc(t,e){let n=e.split(";")[0].trim().toLowerCase();return t.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===n)>-1}s(Fc,"matchesContentType");function Bc(t,e=!1){if(!e)return t;let n=Sr(t),r=Hi(t),o={};return n.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),r(o)}s(Bc,"getResourcePath");var jc=[502,503,504];async function Fe(t,e){if(jc.includes(t.status)){let n=O.getLogger(e),o=await t.clone().text(),i={};for(let[a,u]of t.headers)i[a]=u;n.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:o,headers:i})}}s(Fe,"logBadGatewayResponses");var Lr;function be(t){if(Lr===void 0){let n=h.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(n??"")||(n="debug"),Lr=n}return t.log[Lr]}s(be,"getHandlerUserLogFunction");async function Wi(t,e){let n=h.instance.build.BUILD_ID,{buildAssetsUrl:r}=h.instance,o=e.route.handler.options,{openApiFilePath:i}=o;if(!i)throw new m("Open API Spec Handler must have 'openApiFilePath' specified");let a=zc(i);if(!a.isValid)throw new m(a.error);let u;h.instance.isLocalDevelopment?u=`${r}/${i.substring(1)}`:u=`${r}/${n}${i.substring(1)}`;let c=await fetch(u,{method:t.method,body:t.body,headers:t.headers});if(c.status!==200)return R.notFound(t,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 Fe(l,e),l}s(Wi,"openApiSpecHandler");var zc=s(t=>t.startsWith("./")?t.startsWith("./config")?t.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 Ki(t,e){let n=e.route.handler.options;if(!n.location)throw new m("Redirect Handler must have 'location' specified");let r=n.status??302;return new Response(null,{status:r,headers:{location:n.location}})}s(Ki,"redirectHandler");function Vc(t,e){let n=t.endsWith("/"),r=e.startsWith("/");return n&&r?`${t.substring(0,t.length-1)}${e}`:!n&&!r?`${t}/${e}`:`${t}${e}`}s(Vc,"join");async function Ji(t,e){let n=be(e),r=e.route.handler.options,o=r.forwardSearch!==!1;if(!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new m("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(t.url),u=r.__rewriteFunction(t,i),c=Vc(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();n(`URL Forwarding to '${l}'`);let p=await fetch(l,{method:t.method,body:t.body,headers:t.headers}),b=Date.now()-d;return n(`URL Forward received response ${p.status} - ${p.statusText} in ${b}ms`),Fe(p,e),p}s(Ji,"urlForwardHandler");var Gc=s((t,e)=>{let n=new URL(t),r=new URL(e);for(let[o,i]of r.searchParams.entries())n.searchParams.append(o,i);return n.toString()},"addQuery");async function Yi(t,e){let n=be(e),r=e.route.handler.options,o=r.forwardSearch!==!1,i=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new m("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=o?Gc(u,t.url):u,l=Date.now();n(`URL Rewriting to '${c}'`);let d=await fetch(c.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:i?"follow":"manual"}),p=Date.now()-l;return n(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),Fe(d,e),d}s(Yi,"urlRewriteHandler");async function Qi(t,e){let n=h.instance,r=e.route.handler.options,o=be(e);if(!r||!r.rewritePattern)throw new m("WebSocket Handler must have option 'rewritePattern' specified");let i=t.headers.get("Upgrade");if(!i||i!=="websocket")return R.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new m("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno){let p=new Headers(t.headers);if(u.startsWith("service:")){let g=await Li(u),w=new URL(u);u=new URL(`${g.serviceBaseUrl}${w.pathname}${w.search}`).toString();for(let E in g.tunnelHeaders)p.set(E,g.tunnelHeaders[E])}u=u.replace(/^(http)/,"ws");try{if(p.get("Authorization")){let g=p.get("Authorization")?.replace("Bearer ","");u+=`?apiKey=${g}`}}catch{}let b=JSON.stringify({url:u});return new Response(b,{headers:p})}u=u.replace(/^(ws)/,"http");let l=await fetch(u,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let p=await l.text(),b=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${p}'`;throw new Error(b)}let d=Date.now()-c;return o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${d}ms`),new Response(null,{status:101,webSocket:l.webSocket})}s(Qi,"webSocketHandler");var _r=s((t,e)=>t.map((r,o)=>{let i;if(typeof r.module=="object"&&(i=r.module[r.export]),!i||typeof i!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${o+1}, export name: ${r.export}`;throw new m(`${a} - Websocket policy must be a valid function (${u})`)}return i}),"getWebSocketPolicyFunctions"),Xi=s(async(t,e,n,r,o,i)=>{let a=t.data;if(i&&i.length>0){let u=[...i];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,n,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function es(t,e,n,r,o){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",i=>{r.log.error("WebSocket error: ",i),e.send(JSON.stringify(i))}),t.addEventListener("message",i=>{try{let u=s(async c=>{let l=await Xi(c,t,e,n,r,o);l!==void 0&&e.send(l)},"innerPipeline")(i).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}s(es,"wireUpListeners");async function ts(t,e){let n=h.instance,r=e.route.handler.options,o=be(e);if(!r||!r.rewritePattern)throw new m("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let i=t.headers.get("Upgrade");if(!i||i!=="websocket")return R.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new m("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno)throw new m("Websocket pipeline handler is currently not supported on working-copy environments");u=u.replace(/^(ws)/,"http");let l=await fetch(u,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let x=await l.text(),L=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${x}'`;throw new Error(L)}let d=new WebSocketPair,[p,b]=Object.values(d),g=Date.now()-c;o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${g}ms`);let w=l.webSocket;w.accept(),b.accept();let I=r.policies&&r.policies.inbound?_r(r.policies.inbound,"inbound"):[],E=r.policies&&r.policies.outbound?_r(r.policies.outbound,"outbound"):[];return es(b,w,t,e,I),es(w,b,t,e,E),new Response(null,{status:101,webSocket:p})}s(ts,"webSocketPipelineHandler");var rn=class extends U{constructor(n){super();this.options=n}static{s(this,"DynaTraceLoggingPlugin")}getTransport(){return new kr(this.options)}},kr=class{static{s(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#r=h.instance.loggingEnvironmentType,this.#o=h.instance.loggingEnvironmentStage,this.#n=h.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:ce(z(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)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{e.length!==0&&await fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new C("dyna-trace-log-transport",10,this.#i)};var on=class extends U{constructor(n){super();this.options=n}static{s(this,"LokiLoggingPlugin")}getTransport(){return new Ur(this.options)}},Dr=class{static{s(this,"LokiStream")}constructor(e,n,r,o,i){this.level=e,this.environment=n,this.environmentType=r,this.environmentStage=o,this.requestId=i}job="zuplo";level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function Wc(t,e){return btoa(`${t}:${e}`)}s(Wc,"createBasicDigest");var Ur=class{static{s(this,"LokiTransport")}constructor(e){this.#e=e.url,this.#t=Wc(e.username,e.password),this.#r=h.instance.loggingEnvironmentType,this.#o=h.instance.loggingEnvironmentStage,this.#n=h.instance.deploymentName}#e;#t;#n;#r;#o;log(e,n){let r=new Dr(e.level,this.#n,this.#r,this.#o,e.requestId);e.messages.forEach(o=>{let i={stream:r,message:ce(z(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(i)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=e=>{let n={streams:[]};return e.forEach(r=>{let o=n.streams.find(i=>i.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},n.streams.push(o)),o.values.push([r.nanoSecondEpoch,r.message])}),n};#s=async e=>{if(e.length===0)return;let n=this.#i(e);await fetch(this.#e,{method:"POST",body:JSON.stringify(n),headers:{"content-type":"application/json",authorization:`Basic ${this.#t}`}})};batcher=new C("loki-log-transport",10,this.#s)};var sn=class extends U{constructor(n){super();this.options=n}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new Hr(this.options)}},Hr=class{static{s(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=h.instance.loggingEnvironmentType,this.#r=h.instance.loggingEnvironmentStage,this.#t=h.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:ce(z(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)}),n.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let n=e.map(o=>JSON.stringify(o)).join(`
61
+ `),r=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&r.set("X-Sumo-Name",this.#i),this.#o&&r.set("X-Sumo-Category",this.#o),await fetch(this.#e,{method:"POST",body:n,headers:r})};batcher=new C("sumo-logic-log-transport",10,this.#s)};var Kc="d3a5b78f-8236-48f5-b1df-4fe269d41172",an=class extends U{constructor(n){super();this.options=n}static{s(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new Mr(this.options)}},Mr=class{static{s(this,"VMWareLogInsightTransport")}constructor(e){let n;try{n=new URL(e.url)}catch{throw new m(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=n.origin,this.#n=h.instance.loggingEnvironmentType,this.#r=h.instance.loggingEnvironmentStage,this.#t=h.instance.deploymentName,this.#o=e.onMessageSending,e.fields&&(this.#i=Object.entries(e.fields).map(([r,o])=>({name:r,content:o})))}#e;#t;#n;#r;#o;#i;log(e,n){let r=this.buildEntry(e,n);this.batcher.enqueue(r),n.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,n){let r=Pi(e.messages),o={timestamp:Date.now(),text:r,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#n},{name:"environment_stage",content:this.#r},{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.#t&&o.fields.push({name:"environment",content:this.#t}),this.#i&&o.fields.push(...this.#i),n.custom&&Object.entries(n.custom).forEach(([i,a])=>{let u=hr(a);u&&o.fields.push({name:i,content:u})}),this.#o&&(o=this.#o(o)),o}#s=async e=>{if(e.length===0)return;let n=await fetch(`${this.#e}/api/v1/events/ingest/${Kc}`,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8"}});if(n.status!==200)try{let r=await n.text();console.error("Error logging to Log Insight",r)}catch(r){console.error(r)}};batcher=new C("vmware-log-insights-log-transport",10,this.#s)};var un=class extends U{constructor(n){super();this.options=n}static{s(this,"AWSLoggingPlugin")}getTransport(){return new Nr(this.options)}},Nr=class{static{s(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new C("aws-log-transport",10,async e=>{if(e.length===0)return;let n=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:n,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}})});constructor({accessKeyId:e,logStreamName:n,logGroupName:r,secretAccessKey:o,region:i}){this.awsClient=new qe({accessKeyId:e,secretAccessKey:o,service:"logs",region:i}),this.logGroupName=r,this.logStreamName=n,this.region=i,this.environmentType=h.instance.loggingEnvironmentType,this.environment=h.instance.deploymentName}log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:ce(z(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)}),n.waitUntil(this.batcher.waitUntilFlushed())}};var Zr=new WeakMap,Jc={tags:[]},cn=class extends fe{constructor(n){super();this.options=n}static{s(this,"DataDogMetricsPlugin")}getTransport(){return new qr(this.options)}static setContext(n,r){let o=Zr.get(n);o||(o=Jc);let i=Object.assign({...o},r);Zr.set(n,i)}},qr=class{static{s(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,n){this.#i===void 0&&(this.#i=new C("data-dog-metrics-transport",10,this.dispatchFunction,O.getLogger(n)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(Zr.get(n)?.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 i=e.systemRouteName||e.routePath;o.push(`path:${i}`)}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}),n.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let n=JSON.stringify({series:e}),r=await fetch(this.#t,{method:"POST",body:n,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new $r(await r.text())}},$r=class t extends Error{static{s(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var Fr=new WeakMap,Yc={dimensions:[]},ln=class extends fe{constructor(n){super();this.options=n}static{s(this,"DynatraceMetricsPlugin")}getTransport(){return new Br(this.options)}static setContext(n,r){let o=Fr.get(n);o||(o=Yc);let i=Object.assign({...o},r);Fr.set(n,i)}},Br=class{static{s(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,n){this.#r===void 0&&(this.#r=new C("dynatrace-metrics-transport",10,this.dispatchFunction,O.getLogger(n)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(Fr.get(n)?.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 i=o.join(",");this.#t.latency&&this.#r.enqueue(`zuplo.request.latency,${i} ${e.durationMs} ${r}`),this.#t.requestContentLength&&e.requestContentLength&&this.#r.enqueue(`zuplo.request.content_length,${i} ${e.requestContentLength} ${r}`),this.#t.responseContentLength&&e.responseContentLength&&this.#r.enqueue(`zuplo.response.content_length,${i} ${e.responseContentLength} ${r}`),n.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let n=e.join(`
62
+ `),r=await fetch(this.#e,{method:"POST",body:n,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new jr(await r.text())}},jr=class t extends Error{static{s(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var dn=class{static{s(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async n=>{await fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(n)})}))}};var pn=class extends ae{static{s(this,"AuditLogPlugin")}constructor(e,n){super(),this.#e=e,this.#t=n}#e;#t;async initialize(e){new zr(e,this.#e,this.#t)}},ns=s(t=>{let e={};return t.forEach((n,r)=>{e[r]=n}),e},"serializableHeaders"),Qc={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},zr=class{static{s(this,"AuditPluginImpl")}constructor(e,n,r){this.#t=n;let o={...Qc};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 C("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,n,r,o,i,a)=>{try{let u={timestamp:o,durationMs:i,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:n.url,method:n.method,headers:this.#e.include?.request?.headers?ns(n.headers):void 0,body:this.#e.include?.request?.body?await n.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?ns(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(u),r.waitUntil(this.#n.waitUntilFlushed())}catch(u){r.log.error(u)}};#i=async(e,n)=>{try{if(!await this.#e.requestFilter(e,n))return e;let o=new Date,i=Date.now(),a=e.clone();return n.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#o(d,a,n,o,l-i,c.user?.sub).catch(b=>{n.log.error(b)});n.waitUntil(p)}),e}catch(r){return n.log.error(r),e}}};var Vr=class extends Error{static{s(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}},se=class extends Vr{static{s(this,"StripeSignatureVerificationError")}header;payload;constructor(e,n,r={}){super(r),this.header=e,this.payload=n}};var Xc="v1",el=300;async function rs(t,e,n,r=el,o){return await nl(t,e,n,r,o),t instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(t)):JSON.parse(t)}s(rs,"constructEventAsync");function tl(t,e){return`${e.timestamp}.${t}`}s(tl,"makeHMACContent");async function nl(t,e,n,r,o){let{decodedHeader:i,decodedPayload:a,details:u,suspectPayloadType:c}=rl(t,e,Xc),l=/\s/.test(n),d=await al(tl(a,u),n);return ol(a,i,u,d,r,c,l,o)}s(nl,"verifyHeaderAsync");function rl(t,e,n){if(!t)throw new se(e,t,{message:"No webhook payload was provided."});let r=typeof t!="string"&&!(t instanceof Uint8Array),o=new TextDecoder("utf8"),i=t instanceof Uint8Array?o.decode(t):t;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 se(e,t,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=il(a,n);if(!u||u.timestamp===-1)throw new se(a,i,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new se(a,i,{message:"No signatures found with expected scheme"});return{decodedPayload:i,decodedHeader:a,details:u,suspectPayloadType:r}}s(rl,"parseEventDetails");function ol(t,e,n,r,o,i,a,u){let c=!!n.signatures.filter(b=>sl(b,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 i?new se(e,t,{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,5 +68,5 @@ Signature verification is impossible without access to the original signed mater
68
68
  `+d}):new se(e,t,{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)-n.timestamp;if(o>0&&p>o)throw new se(e,t,{message:"Timestamp outside the tolerance zone"});return!0}s(tl,"validateComputedSignature");function nl(t,e){return typeof t!="string"?null:t.split(",").reduce((n,r)=>{let o=r.split("=");return o[0]==="t"&&(n.timestamp=parseInt(o[1],10)),o[0]===e&&n.signatures.push(o[1]),n},{timestamp:-1,signatures:[]})}s(nl,"parseHeader");function rl(t,e){if(t.length!==e.length)return!1;let n=t.length,r=0;for(let o=0;o<n;++o)r|=t.charCodeAt(o)^e.charCodeAt(o);return r===0}s(rl,"secureCompare");async function ol(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,n.encode(t)),i=new Uint8Array(o),a=new Array(i.length);for(let u=0;u<i.length;u++)a[u]=Gr[i[u]];return a.join("")}s(ol,"computeHMACSignatureAsync");var Gr=new Array(256);for(let t=0;t<Gr.length;t++)Gr[t]=t.toString(16).padStart(2,"0");function D(t,e){if(!Ee(t))throw new g(`Options on policy '${e}' is expected to be an object. Received the type '${typeof t}'.`);let n=s((i,a,u)=>{let c=t[i];if(!(u&&c===void 0)){if(c===void 0)throw new g(`Value of '${String(i)}' on policy '${e}' is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(a==="array"&&Array.isArray(c))throw new g(`Value of '${String(i)}' on policy '${e}' must be an array. Received type ${typeof c}.`);if(typeof c!==a)throw new g(`Value of '${String(i)}' on policy '${e}' must be of type ${a}. Received type ${typeof c}.`);if(typeof c=="string"&&c.length===0)throw new g(`Value of '${String(i)}' on policy '${e}' must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof c=="number"&&isNaN(c))throw new g(`Value of '${String(i)}' on policy '${e}' must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),r=s((i,a)=>(n(i,a,!0),{optional:r,required:o}),"optional"),o=s((i,a)=>(n(i,a,!1),{optional:r,required:o}),"required");return{optional:r,required:o}}s(D,"optionValidator");var Be=class extends ue{static{s(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,n){D(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 rs(o,r,this.options.signingSecret)}catch(o){return n.log.error("Error validating stripe webhook",o),R.badRequest(e,n,{title:"Webhook Error",detail:o.message})}return e}};function os(t){return t!==null&&typeof t=="object"&&"id"in t&&W(t.id)&&"type"in t&&W(t.type)}s(os,"isStripeWebhookEvent");var mn=class extends ae{static{s(this,"MeteringPlugin")}};var il={getSubscription:async({subscriptionId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/subscriptions/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving subscription from Stripe API.";throw n.error(i,o),new I(i)}return o},getCustomer:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/customers/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer from Stripe API.";throw n.error(i,o),new I(i)}return o}},is=il;var Wr="https://api-key-management-service-eq7z4lly2a-ue.a.run.app";async function ss({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,managerSub:i,context:a}){let{authApiJWT:u}=h.instance,c=new URL(`/v1/buckets/${t}/consumers`,Wr);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:"API Subscription",tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[{sub:i,email:o}]},p=await V({retryDelayMs:5,retries:2,logger:O.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),y=await p.json();if(p.status!==200){let m="Error creating API Key Consumer";throw a.log.error(m,y),new I(m)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:n}),l}s(ss,"createConsumer");async function as({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,context:i}){let{authApiJWT:a}=h.instance,u=new URL(`/v1/buckets/${t}/consumers`,Wr);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:"API Subscription",tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[o]},d=await V({retryDelayMs:5,retries:2,logger:O.getLogger(i)},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 y="Error creating API Key Consumer";throw i.log.error(y,p),new I(y)}return i.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:n}),c}s(as,"createConsumerInvite");async function us({apiKeyBucketName:t,consumerId:e,context:n}){let{authApiJWT:r}=h.instance,o=new URL(`/v1/buckets/${t}/consumers/${e}`,Wr);o.searchParams.set("with-api-key","true");let i=await V({retryDelayMs:5,retries:2,logger:O.getLogger(n)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(i.status!==204){let a=await i.json(),u="Error deleting API Key Consumer";throw n.log.error(u,a),new I(u)}return n.log.info(`Successfully deleted API Key Consumer '${e}`),e}s(us,"deleteConsumer");async function cs({context:t,stripeSubscriptionId:e,stripeProductId:n,customerKey:r,meteringBucketId:o,meteringBucketRegion:i,customerExternalId:a,subscriptionStatus:u}){let c={status:u,type:"periodic",renewalStrategy:"monthly",region:i,subscriptionExternalId:e,planExternalIds:[n],customerKey:r,customerExternalId:a},{authApiJWT:l,meteringServiceUrl:d}=h.instance;if(!Ue(l))throw new T("No Zuplo JWT token set.");let p=await V({retryDelayMs:5,retries:2,logger:O.getLogger(t)},`${d}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(c)});if(!p.ok){let y="Error creating metering subscription.",m;try{m=await p.json()}catch{m={status:p.status,statusText:p.statusText}}throw t.log.error(y,m),new I(y)}t.log.info("Successfully created/updated metering subscription.",c)}s(cs,"createSubscription");async function gt({context:t,meteringSubscriptionId:e,meteringBucketId:n,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:i}=h.instance;if(!Ue(o))throw new T("No Zuplo JWT token set.");let a=await V({retryDelayMs:5,retries:2,logger:O.getLogger(t)},`${i}/internal/v1/metering/${n}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Error updating metering subscription to '${JSON.stringify(r)}'.`,c;try{c=await a.json()}catch{c={status:a.status,statusText:a.statusText}}throw t.log.error(u,c),new I(u)}t.log.info(`Successfully update metering subscription to '${JSON.stringify(r)}'.`)}s(gt,"updateSubscription");async function ft({context:t,stripeSubscriptionId:e,stripeCustomerId:n,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:i}=h.instance;if(!Ue(o))throw new T("No Zuplo JWT token set.");let a=await V({retryDelayMs:5,retries:2,logger:O.getLogger(t)},`${i}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":t.requestId},method:"GET"});if(!a.ok){let c="Error querying for metering subscription.",l;try{l=await a.json()}catch{l={status:a.status,statusText:a.statusText}}throw t.log.error(c,l),new I(c,l)}let u=await a.json();if(u.data.length===0){let c="Subscription was not found and the event was ignored by Stripe metering plugin webhook.";throw t.log.error(c),new I(c)}if(u.data[0].customerExternalId!==n){let c="A subscription was not found for the customer provided and the event was ignored by Stripe metering plugin webhook.";throw t.log.error(c),new I(c)}return u.data[0]}s(ft,"getSubscription");function gn(t){return t.replaceAll("_","-")}s(gn,"stripeStatusToMeteringStatus");async function Kr(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),R.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=n.data.object.plan;if(!i||!i.product)return e.log.warn(`Invalid Stripe API result. Expected event '${n.id}' to have a plan data.`),R.badRequest(t,e,{detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=n.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),R.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let u=i.product,c;if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_email&&n.data.object.metadata.zuplo_created_by_sub)c=await ss({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:n.data.object.metadata.zuplo_created_by_email,managerSub:n.data.object.metadata.zuplo_created_by_sub,context:e});else{let l=await is.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!l.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),R.badRequest(t,e,{detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await as({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l.email,context:e})}if(!c)return R.internalServerError(t,e,{detail:"No consumer was created, skipping creation of subscription"});try{let l=gn(n.data.object.status);await cs({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:l})}catch(l){return await us({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),R.internalServerError(t,e,{detail:l.message})}return R.ok(t,e)}s(Kr,"onCustomerSubscriptionCreated");async function Jr(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),R.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=n.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),R.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let a=await ft({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId});return await gt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}}),R.ok(t,e)}s(Jr,"onCustomerSubscriptionDeleted");async function Yr(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to include '.data.object.id' as the subscription ID.`),R.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=n.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),R.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(n.data.previous_attributes){let a=n.data.previous_attributes;if(a.status&&a.status!==n.data.object.status){let u=await ft({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=gn(n.data.object.status);return await gt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds}}),R.ok(t,e)}if(a.plan&&a.plan.product!==n.data.object.plan.product){let u=await ft({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId});return await gt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[n.data.object.plan.product]}}),R.ok(t,e)}}return e.log.warn(`This update event '${n.id}' is not supported by Stripe metering plugin webhook.`),R.badRequest(t,e,{detail:"This update event is not supported by Stripe metering plugin webhook."})}s(Yr,"onCustomerSubscriptionUpdated");var Qr=class extends mn{constructor(n){super();this.options=n}static{s(this,"StripeMeteringPlugin")}registerRoutes(n,r){let o=s(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(q.ZUPLO_METERING_SERVICE_BUCKET_ID)d=q.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g("StripeMeteringPlugin - No 'meteringBucketId' property provided");if(!p)if(q.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=q.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new g("StripeMeteringPlugin - No 'apiKeyBucketName' property provided");if(!h.instance.build.ACCOUNT_NAME)throw new T("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let y=this.options.meteringBucketRegion??"us-central1";if(!sl(y))throw new g(`StripeMeteringPlugin - The value '${y}' on the property 'meteringBucketRegion' is invalid.`);let m=await c.json();if(!os(m))return R.badRequest(c,l,{detail:"The received body was not in the expected format."});switch(l.log.info(`Received Stripe webhook event of type '${m.type}' with ID '${m.id}'.`),m.type){case"customer.subscription.created":return await Kr(c,l,m,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:y,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await Yr(c,l,m,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:y,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await Jr(c,l,m,{meteringBucketId:d});default:return R.badRequest(c,l,{detail:"Event is not supported by Stripe metering plugin webhook."})}},"stripeWebhookHandler"),i=di({inboundPolicies:[new Be({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]}),a=new U({processors:[j,i],handler:o,gateway:r}),u=new k({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});n.addRoute(u,a.execute)}};function sl(t){return t!==null&&typeof t=="string"&&["us-central1","europe-west4"].includes(t)}s(sl,"isMetricsRegion");var ds=new WeakMap,ls={},fn=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){ds.set(e,n)}};async function ps(t,e,n,r){if(!n.statusCodes)throw new g(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Array.isArray(n.statusCodes)?n.statusCodes:Dt(n.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=ds.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new I(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=xe(t.user,n.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??n.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??n.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(n.dimensions??{},a?.dimensions)},y=ls[n.apiKey];if(!y){let m=n.apiKey,w=t.headers.get("zm-test-id")??"";y=new C("amberflo-ingest-meter",10,async P=>{try{let E=n.url??"https://app.amberflo.io/ingest",x=await fetch(E,{method:"POST",body:JSON.stringify(P),headers:{"content-type":"application/json","x-api-key":m,"zm-test-id":w}});x.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${x.status}: ${await x.text()}`)}catch(E){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${E.message}`),E}}),ls[m]=y}y.enqueue(p),e.waitUntil(y.waitUntilFlushed())}}),t}s(ps,"AmberfloMeteringInboundPolicy");async function hn(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")}s(hn,"sha256");var ms=new Map;async function $(t,e){let n,r=ms.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await hn(JSON.stringify({policyName:t,options:e}))}`,ms.set(t,n)),n}s($,"getPolicyCacheName");var gs="key-metadata-cache-type";function al(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}s(al,"getKeyValue");async function yn(t,e,n,r){if(!n.bucketName)if(q.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=q.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new g(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:n.authHeader??"authorization",authScheme:n.authScheme??"Bearer",bucketName:n.bucketName,cacheTtlSeconds:n.cacheTtlSeconds??60,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:n.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new g(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(E=>o.allowUnauthenticatedRequests?t:R.unauthorized(t,e,{detail:E}),"unauthorizedResponse"),a=t.headers.get(o.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let u=al(a,o);if(!u||u==="")return i("No key present");let c=await ul(u),l=await $(r,o),d=new N(l,e),p=await d.get(c);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==gs&&O.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let y={key:u},m=await V({retryDelayMs:5,retries:2,logger:O.getLogger(e)},`${h.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":h.instance.deploymentName??"unknown","User-Agent":h.instance.systemUserAgent},body:JSON.stringify(y)});if(m.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(m.status!==200){try{let E=await m.text(),x=JSON.parse(E);e.log.error("Unexpected response from key service",x)}catch{e.log.error("Invalid response from key service")}throw new I(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${m.status}`)}let w=await m.json(),P={isValid:!0,typeId:gs,user:{sub:w.name,data:w.metadata}};return t.user=P.user,d.put(c,P,o.cacheTtlSeconds),t}s(yn,"ApiKeyInboundPolicy");async function ul(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(ul,"hashValue");var fs=yn;var ht=require("jose");var Xr={},cl=s(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new g("Invalid State - jwkUrl not set");Xr[e.jwkUrl]||(Xr[e.jwkUrl]=(0,ht.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,ht.jwtVerify)(t,Xr[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),ll=s(async(t,e)=>{let n;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let i=new TextEncoder().encode(e.secret);n=new Uint8Array(i)}else n=e.secret;let{payload:r}=await(0,ht.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),F=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),i="bearer ",a=s(y=>R.unauthorized(t,e,{detail:y}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new g(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new g(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?cl:ll,l=await s(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(i)!==0)return a("Invalid bearer token format for authorization header");let y=o.substring(i.length);if(!y||y.length===0)return a("No bearer token on authorization header");try{return await u(y,n)}catch(m){let w=new URL(t.url);return"code"in m&&m.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${w.pathname} `,m):e.log.warn(`Invalid token on: ${t.method} ${w.pathname}`,m),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return n.allowUnauthenticatedRequests===!0?t:l;let d=n.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var hs=s(async(t,e,n,r)=>F(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var ys=s(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",i=s(l=>R.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),u=await s(async()=>{if(!r)return await i("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await i("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await i("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let y=d.substring(0,p),m=d.substring(p+1),w=n.accounts.find(P=>P.username===y&&P.password===m);return w||await i("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return n.allowUnauthenticatedRequests?t:u;let c=u.username;return t.user={sub:c,data:u.data},t},"BasicAuthInboundPolicy");var dl=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function pl(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(pl,"digestMessage");var ml=s(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of t.headers.entries())n.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await pl(JSON.stringify(r)),i=new URL(t.url),a=new URLSearchParams(i.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",t.method);let c=`${i.origin}${i.pathname}?${a}`;return new Request(c,{method:u?"GET":t.method})},"createCacheKeyRequest");async function bs(t,e,n,r){let o=await $(r,n),i=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await ml(t,n),c=await i.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=n.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let y=n?.expirationSecondsTtl??60,m=new Response(p.body,p);dl.forEach(w=>m.headers.delete(w)),m.headers.set("cache-control",`s-maxage=${y}`),e.waitUntil(i.put(u,m))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}s(bs,"CachingInboundPolicy");var ws=s(async(t,e,n,r)=>{if(!n.method)throw new g(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new L(t,{method:n.method})},"ChangeMethodInboundPolicy");var Rs=s(async(t,e,n)=>{let r=[...n.exclude??[]],o=new Headers;return r.forEach(a=>{let u=t.headers.get(a);u&&o.set(a,u)}),new L(t,{headers:o})},"ClearHeadersInboundPolicy");var Ps=s(async(t,e,n,r)=>{let o=[...r.exclude??[]],i=new Headers;return o.forEach(u=>{let c=t.headers.get(u);c&&i.set(u,c)}),new Response(t.body,{headers:i,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");var Is=s(async(t,e,n,r)=>{let o=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",F(t,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var Es=s(async(t,e,n,r)=>{if(!n.userPoolId)throw new g("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new g("region must be set in the options for CognitoJwtInboundPolicy");return F(t,e,{issuer:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}`,jwkUrl:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var xs=s(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new g(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=Z.instance,i=it(n.policies,o?.routeData.policies);return mr(i)(t,e)},"CompositeInboundPolicy");var vs=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization");if(!o)return R.unauthorized(t,e,{detail:"No authorization header"});let i=gl(o);if(!i)return R.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await $(r,n),u=new N(a,e),c=await u.get(i);if(!c){let l=await fetch(n.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${n.clientId}:${n.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+i+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(i,c,n.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),R.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):R.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${c}`),t},"CurityPhantomTokenInboundPolicy");function gl(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}s(gl,"getToken");var Ss=s(async(t,e,n,r)=>(D(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),F(t,e,{issuer:`https://securetoken.google.com/${n.projectId}`,audience:n.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var Ts=s(async(t,e,n)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",i=t.headers.get("content-type")?.toLowerCase();if(!i||![o,r].includes(i))return n&&n.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(n&&n.optionalHoneypotName&&a.get(n.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(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new L(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var je="__unknown__",Os=s(async(t,e,n,r)=>{let o={allow:{countries:Ve(n.allow?.countries,"allow.countries",r),regionCodes:Ve(n.allow?.regionCodes,"allow.regionCode",r),asns:Ve(n.allow?.asns,"allow.asOrganization",r)},block:{countries:Ve(n.block?.countries,"block.countries",r),regionCodes:Ve(n.block?.regionCodes,"block.regionCode",r),asns:Ve(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??je,a=e.incomingRequestProperties.regionCode?.toLowerCase()??je,u=e.incomingRequestProperties.asn?.toString()??je,c=o.ignoreUnknown&&i===je,l=o.ignoreUnknown&&a===je,d=o.ignoreUnknown&&u===je,p=o.allow.countries,y=o.allow.regionCodes,m=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||y.length>0&&!y.includes(a)&&!l||m.length>0&&!m.includes(u)&&!d)return ze(t,e,r,i,a,u);let w=o.block.countries,P=o.block.regionCodes,E=o.block.asns;return w.length>0&&w.includes(i)&&!c||P.length>0&&P.includes(a)&&!l||E.length>0&&E.includes(u)&&!d?ze(t,e,r,i,a,u):t},"GeoFilterInboundPolicy");function ze(t,e,n,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),R.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(ze,"blockedResponse");function Ve(t,e,n){if(typeof t=="string")return t.split(",").map(r=>r.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(r=>r.trim().toLowerCase());throw new g(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}s(Ve,"toLowerStringArray");var Cs=s(async(t,e,n)=>{let r=t.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(u=>i.includes(u)),"scopeChecker")(r,n.scopes)){let i={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${n.scopes}`};return new Response(JSON.stringify(i),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");var fl=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]),As=s(async(t,e,n,r)=>{D(n,r).optional("allowRequestsWithoutSubscription","boolean").optional("bucketId","string");let o=O.getLogger(e),i=n.allowRequestsWithoutSubscription??!1;if(n.allowedSubscriptionStatuses)try{if(n.allowedSubscriptionStatuses.length===0)throw new g("Must set valid subscription statuses");let m=ve(n.allowedSubscriptionStatuses),w=[];for(let P of m)fl.has(P)||w.push(P);if(w.length>0)throw new g(`Found the following invalid statuses: ${w.join(", ")}`)}catch(m){throw m instanceof g?new g(`LoadSubscriptionInboundPolicy '${r}' - The property 'allowedSubscriptionStatuses' is invalid. ${m.message}`):m}else n.allowedSubscriptionStatuses=["active","incomplete","trialing"];let a=n.allowedSubscriptionStatuses,u=t.user;if(!u)return i?t:R.unauthorized(t,e,{detail:"Unable to check subscription for anonymous user"});if(!n.bucketId)if(q.ZUPLO_METERING_SERVICE_BUCKET_ID)n.bucketId=q.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`LoadSubscriptionInboundPolicy '${r}' - No bucketId property provided`);let{authApiJWT:c,meteringServiceUrl:l}=h.instance,{sub:d}=u,p;try{let m=await fetch(`${l}/internal/v1/metering/${n.bucketId}/subscriptions?customerKey=${d}`,{headers:{Authorization:`Bearer ${c}`,"zp-rid":e.requestId},method:"GET"});if(!m.ok)return e.log.error(await m.text()),R.forbidden(t,e);p=await m.json()}catch(m){o.error(`LoadSubscriptionInboundPolicy '${r}' - Error loading subscription`,m)}let y=p&&p.data&&p.data.length>0?p.data[0]:void 0;return y?!a.includes(y.status)&&!i?(e.log.warn(`Subscription '${y.id}' has status '${y.status}' which is not part of the allowed statuses.`),R.unauthorized(t,e,{detail:"No valid subscription found"})):(a.includes(y.status)&&(e.log.debug(`Loading subscription '${y.id}' for user sub '${d}' to ContextData`),le.set(e,Qe,y)),t):(e.log.warn("No valid subscription found"),i?t:R.unauthorized(t,e,{detail:"No valid subscription found"}))},"LoadSubscriptionInboundPolicy");var Ls=s(async(t,e,n,r)=>{D(n,r).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string");let o=O.getLogger(e);if(!n.meterOnStatusCodes)throw new g(`Invalid MeteringInboundPolicy '${r}' - The property 'meterOnStatusCodes' must be an array of HTTP status code numbers`);let i=Array.isArray(n.meterOnStatusCodes)?n.meterOnStatusCodes:Dt(n.meterOnStatusCodes);try{let p=[];for(let y in n.meters)typeof n.meters[y]!="number"&&!(Number.isInteger(n.meters[y])&&/^-?\d+$/.test(n.meters[y].toString()))&&p.push(y);if(p.length>0)throw new g(p.length>1?`The values found in these properties are not integers : ${p.join(", ")}`:`The value in property '${p[0]}' is not an integer`)}catch(p){throw p instanceof g?new g(`MeteringInboundPolicy '${r}' - The property 'meters' is invalid. ${p.message}`):p}e.addResponseSendingFinalHook(async(p,y,m)=>{let w=le.get(m,Qe);if((n.allowRequestsWithoutSubscription??!1)&&!w){m.log.debug(`MeteringInboundPolicy '${r}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!n.bucketId)if(q.ZUPLO_METERING_SERVICE_BUCKET_ID)n.bucketId=q.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`MeteringInboundPolicy '${r}' - No bucketId property provided`);let{authApiJWT:E,meteringServiceUrl:x}=h.instance;if(i.includes(p.status)&&w&&n.meters){m.log.debug(`MeteringInboundPolicy '${r}' - Updating subscription '${w.id}' with meters '${JSON.stringify(n.meters)} on response status '${p.status}'`);try{let A=await fetch(`${x}/internal/v1/metering/${n.bucketId}/subscriptions/${w.id}/quotas/consume`,{headers:{Authorization:`Bearer ${E}`,"zp-rid":m.requestId},method:"POST",body:JSON.stringify({meters:n.meters})});if(!A.ok){let H=await A.json(),_=H.detail??H.title??"Unknown error on quota consumption.";m.log.error(`MeteringInboundPolicy '${r}' - Error updating subscription quota. ${A.status} - ${_}`),o.error(`MeteringInboundPolicy '${r}' - Error updating subscription quota. ${A.status} - ${_}`)}}catch(A){m.log.error(`MeteringInboundPolicy '${r}' - Error updating subscription quota.`),o.error(`MeteringInboundPolicy '${r}' - Error updating subscription quota.`,A)}}});let a=le.get(e,Qe),u=n.allowRequestsWithoutSubscription??!1,c=n.allowRequestsOverQuota??!1;if(!a)return u?t:(e.log.warn("Subscription is not available for user"),R.paymentRequired(t,e,{detail:"Subscription is not available for user",title:"No Subscription"}));if(a&&Object.keys(a.quotas).length===0)return e.log.error(`Quota is not set up for subscription '${a.id}'`),R.tooManyRequests(t,e,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let d=Object.keys(n.meters).filter(p=>!Object.keys(a.quotas).includes(p));if(d.length>0)return e.log.warn(`The following policy meters are not present in the subscription: ${d.join(", ")}`),R.tooManyRequests(t,e,{detail:`The following policy meters are not present in the subscription: ${d.join(", ")}`,title:"Quota Exceeded"});for(let p of Object.keys(n.meters))if(a.quotas[p]<=0&&!c)return R.tooManyRequests(t,e,{detail:`Quota exceeded for meter '${p}'`,title:"Quota Exceeded"});return t},"MeteringInboundPolicy");var ks=s(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return eo(r,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return eo(r,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(i.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(y=>{a.push({responseName:u,contentName:l,exampleName:y,exampleValue:d[y]})})})}),a=a.filter(u=>!(n.responsePrefixFilter&&!u.responseName.startsWith(n.responsePrefixFilter)||n.contentType&&u.contentName!==n.contentType||n.exampleName&&u.exampleName!==n.exampleName)),n.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return _s(a[u])}else return a.length>0?_s(a[0]):eo(r,t,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 _s(t){let e=JSON.stringify(t.exampleValue,null,2),n=new Headers;switch(n.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:n});case"2XX":return new Response(e,{status:200,headers:n});case"3XX":return new Response(e,{status:300,headers:n});case"4XX":return new Response(e,{status:400,headers:n});case"5XX":case"default":return new Response(e,{status:500,headers:n});default:return new Response(e,{status:Number(t.responseName),headers:n})}}s(_s,"generateResponse");var eo=s((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return R.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var hl="Incoming",yl={logRequestBody:!0,logResponseBody:!0};function Ds(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}s(Ds,"headersToObject");function Us(){return new Date().toISOString()}s(Us,"timestamp");var to=new WeakMap,bl={};function Ns(t,e){let n=to.get(t);n||(n=bl);let r=Object.assign({...n},e);to.set(t,r)}s(Ns,"setMoesifContext");async function Hs(t,e){let n=t.headers.get("content-type");if(n&&n.indexOf("json")!==0)try{return await t.clone().json()}catch(o){e.log.error(o)}let r=await t.clone().text();return e.log.debug({textBody:r}),r}s(Hs,"readBody");var wl={},no;function Ms(){if(!no)throw new I("Invalid State - no _lastLogger");return no}s(Ms,"getLastLogger");function Rl(t){let e=wl[t];return e||(e=new C("moesif-inbound",100,async n=>{let r=JSON.stringify(n);Ms().debug("posting",r);let o=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:r});o.ok||Ms().error({status:o.status,body:await o.text()})})),e}s(Rl,"getDispatcher");async function Zs(t,e,n,r){no=e.log;let o=Us(),i=Object.assign(yl,n);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await Hs(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Rl(i.applicationId),d=t.headers.get("true-client-ip"),p=to.get(e)??{},y={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Ds(t.headers)},m=i.logResponseBody?await Hs(u,e):void 0,w={time:Us(),status:u.status,headers:Ds(u.headers),body:m},P={request:y,response:w,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:hl};l.enqueue(P),e.waitUntil(l.waitUntilFlushed())}),t}s(Zs,"MoesifInboundPolicy");var qs=s(async(t,e,n,r)=>F(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var $s=require("jose");var ro,Fs=s(async(t,e,n,r)=>{if(!ro)try{ro=await(0,$s.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return F(t,e,{issuer:n.authUrl,secret:ro,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var js=Ae(Pe());var bn=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},oo=class extends bn{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},io=class extends bn{static{s(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function Pl(t,e){if(ii(t))throw new oo(e)}s(Pl,"throwIfUndefinedOrNull");function yt(t,e){if(Pl(t,e),!W(t))throw new io(e,"string")}s(yt,"throwIfNotString");var wn=class t{static{s(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,n,r,o){this.redisClientUrl=e,this.clientAuthToken=n,this.deploymentName=r,this.userAgent=o}static initialize(e,n,r,o){return yt(e,"redisClientUrl"),yt(n,"clientAuthToken"),t.instance||(t.instance=new t(e,n,r,o)),t.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:n,method:r,requestId:o}){yt(e,"url");let i=await fetch(`${this.redisClientUrl}${e}`,{method:r,body:n,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=i.headers.get("Content-Type")?.includes("application/json")?await i.json():await i.text();if(i.ok)return a;throw i.status===401?new T("Redis client failed with 401: Unauthorized"):new T(`Redis client failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},Rn=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(yt(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:i,key:a}=JSON.parse(n),u=Date.now()+i*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new T("The in-memory redis client only supports /rate-limit calls")}};var Pn=(0,js.debug)("zuplo:policies:RateLimitInboundPolicy"),Il="strict",El=s(t=>{let e=t.headers.get("cf-connecting-ip")??t.headers.get("true-client-ip");if(e)return e;let n=t.headers.get("x-forwarded-for");return n?n.split(",")[0]:"127.0.0.1"},"getRealIP"),xl=s(async t=>({key:`ip-${El(t)}`}),"getIP"),vl=s(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),Sl=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),In;function Tl(t,e){let n;if(In)return In;if(h.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new Rn,In=n,n;let{authApiJWT:r,redisURL:o}=h.instance;if(!W(o))throw new T(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!W(r))throw new T(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=wn.initialize(o,r,h.instance.deploymentName??"unknown",h.instance.systemUserAgent)),!n||!n.isEnabled())throw new T(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return In=n,n}s(Tl,"getRedisClient");async function Bs(t,e,n,r,o){let i=Math.floor(e*60);return await n.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:i,key:t}),requestId:o})}s(Bs,"getCountAndUpdateExpiry");function Ol(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new g(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new g(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new g(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(n=t.identifier.module[t.identifier.export],!n||typeof n!="function")throw new g(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return s(async(o,i,a)=>{let u=await n(o,i,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw i.log.error(c),new I(c)}return u},"outerFunction")}s(Ol,"wrapUserFunction");var Cl="Retry-After",so=s(async(t,e,n,r)=>{let o=Date.now(),i=O.getLogger(e),a=s((c,l)=>{if(n.throwOnFailure)throw new T(c,{cause:l});i.error(c,l)},"throwOrLog"),u=s((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[Cl]=l.toString()),R.tooManyRequests(t,e,void 0,d)},"rateLimited");try{let l={function:Ol(n,r),user:vl,ip:xl,all:Sl}[n.rateLimitBy],d=await l(t,e,r),p=d.key,y=d.requestsAllowed??n.requestsAllowed,m=d.timeWindowMinutes??n.timeWindowMinutes,w=n.headerMode??"retry-after",P=Tl(r,i),x=`bucket/${h.instance.build.BUILD_ID}/${r}/${p}`;if((n.mode??Il)==="async"){let _=await $(r,n),G=new de(_,{logger:O.getLogger(e)}),Y=Bs(x,m,P,i,e.requestId),Q=await G.get(x);if(Q!==void 0&&Q<=Date.now()){Pn(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${x}' (async mode)`);let Oe=Math.round((Q-Date.now())/1e3);return u(w,Oe)}return e.addEventListener("responseSending",Oe=>{try{let Ce=Oe,An=Ce.mutableResponse;Ce.mutableResponse=(async()=>{let bt=await Y;if(bt.count>y){let Ea=Date.now()+bt.ttlSeconds*1e3,xa=G.put(x,Ea,bt.ttlSeconds).catch(ho=>{throw i.error(new T("Error caching rate limit result.",{cause:ho})),ho});return e.waitUntil(xa),Pn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${x}' (async mode)`),u(w,bt.ttlSeconds)}return An})()}catch(Ce){i.error(`RateLimitInboundPolicy '${r}' -error in responseSending`,Ce)}}),t}let H=await Bs(x,m,P,i,e.requestId);return H.count>y?(Pn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${x}' (strict mode)`),u(w,H.ttlSeconds)):t}catch(c){return a(c.message,c),t}finally{let c=Date.now()-o;Pn(`RateLimitInboundPolicy '${r}' - latency ${c}ms`)}},"RateLimitInboundPolicy");var ao;function zs(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}s(zs,"headersToNameValuePairs");function Al(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}s(Al,"queryToNameValueParis");function Ll(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}s(Ll,"parseIntOrUndefined");var Vs={};async function Gs(t,e,n,r){let o=new Date,i=Date.now();return ao||(ao={name:"zuplo",version:h.instance.build.ZUPLO_VERSION,comment:`zuplo/${h.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?xe(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?xe(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:h.instance.isDeno,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:ao,entries:[{startedDateTime:o.toISOString(),time:Date.now()-i,request:{method:t.method,url:n.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:zs(t.headers),queryString:Al(t.query)},response:{status:a.status,statusText:a.statusText,headers:zs(a.headers),content:{size:Ll(t.headers.get("content-length"))}}}]}}},d=Vs[n.apiKey];if(!d){let p=n.apiKey;d=new C("readme-metering-inbound-policy",10,async y=>{try{let m=n.url??"https://metrics.readme.io/request",w=await fetch(m,{method:"POST",body:JSON.stringify(y),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});w.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${w.status}: '${await w.text()}'`)}catch(m){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${m.message}'`),m}}),Vs[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}s(Gs,"ReadmeMetricsInboundPolicy");var Ws=s(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new g(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(t.headers);return o.forEach(u=>{i.delete(u)}),new L(t,{headers:i})},"RemoveHeadersInboundPolicy");var Ks=s(async(t,e,n,r,o)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new g(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return i.forEach(c=>{a.delete(c)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");var Js=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new g(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(t.url);return o.forEach(u=>{i.searchParams.delete(u)}),new L(i.toString(),t)},"RemoveQueryParamsInboundPolicy");var Ys=s(async(t,e,n,r)=>{let o=await t.text(),i=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(i,r.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");var Qs=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Xs=s(async(t,e,n)=>{let r=n.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let o=t.headers.get("content-length"),i=o!==null?parseInt(o):void 0;return i&&!isNaN(i)&&i>n.maxSizeInBytes?Qs():i&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?Qs():t},"RequestSizeLimitInboundPolicy");function ea(t,e,n){return`_${we(t+"_"+e+"_"+n)}`}s(ea,"getRawOperationDataIdentifierName");function En(t,e,n,r){return`_${we(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}s(En,"getIdForParameterSchema");function xn(t,e,n){return`_${we(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${we(n.toLowerCase())}`}s(xn,"getIdForRequestBodySchema");function ta(t,e){return`_${we(t)}__${we(e)}`}s(ta,"getIdForRefSchema");function we(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(t.charAt(n)):e.push("_")}return e.join("")}s(we,"sanitizedIdentifierName");var Ge=s(t=>{let e=t.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"),We=s((t,e,n,r,o)=>{let i=[],a=!0,u=[];return t.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=En(n,r,o,c.name),p=Z.instance.schemaValidator[d],y=p(e[c.name]),m=uo(p.errors);y||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${m.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),ee=s((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),te=s(t=>t==="log-only"||t==="reject-and-log","shouldLog"),ne=s(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),uo=s(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function na(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(m){let w=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,P=R.badRequest(e,t,{detail:`${w}, see errors property for more details`,errors:`${m}`});if(te(n.validateBody)&&ee(t,n.logLevel??"info",w,[r],m),ne(n.validateBody))return P}if(!e.headers.get("Content-Type")){let m=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,w=R.badRequest(e,t,{detail:m});return te(n.validateBody)&&ee(t,n.logLevel??"info",m,[r],[m]),ne(n.validateBody)?w:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=xn(t.route.path,e.method,o),u=Z.instance.schemaValidator[a];if(!u){let m=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,w=R.badRequest(e,t,{detail:m});return te(n.validateBody)&&ee(t,n.logLevel??"info",m,[r],[m]),ne(n.validateBody)?w:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=uo(l),y=R.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(te(n.validateBody)&&ee(t,n.logLevel??"info",d,[r],p),ne(n.validateBody))return y}s(na,"handleBodyValidation");function ra(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Ge(t),i=We(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=R.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:i.errors});if(te(n.validateHeaders)&&ee(t,n.logLevel??"info",a,i.invalidValues,i.errors),ne(n.validateHeaders))return u}}s(ra,"handleHeadersValidation");function oa(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=Ge(t),o=We(r.filter(i=>i.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let i="Path parameters validation failed",a=R.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(te(n.validatePathParameters)&&ee(t,n.logLevel??"info",i,o.invalidValues,o.errors),ne(n.validatePathParameters))return a}}s(oa,"handlePathParameterValidation");function ia(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=Ge(t),o=We(r.filter(i=>i.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let i="Query parameters validation failed",a=R.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(te(n.validateQueryParameters)&&ee(t,n.logLevel??"info",i,o.invalidValues,o.errors),ne(n.validateQueryParameters))return a}}s(ia,"handleQueryParameterValidation");var co=s(async(t,e,n)=>{let r=ia(e,t,n);if(r!==void 0||(r=oa(e,t,n),r!==void 0)||(r=ra(e,t,n),r!==void 0))return r;let o=await na(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),sa=co;var aa=s(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new g(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof n.origins=="string"?n.origins.split(","):n.origins;o=o.map(a=>a.trim());let i=t.headers.get("origin");if(!i||!o.includes(i)){let a=n.failureDetail??"Forbidden";return R.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var ua=s(async(t,e,n)=>new L(t,{body:n.body}),"SetBodyInboundPolicy");var ca=s(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new g(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new g(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new L(t,{headers:i})},"SetHeadersInboundPolicy");var la=s(async(t,e,n,r,o)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new g(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new g(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");var da=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new g(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new g(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new L(i.toString(),t)},"SetQueryParamsInboundPolicy");var pa=s(async(t,e,n,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(t.body,{headers:t.headers,status:r.status,statusText:r.statusText??t.statusText})},"SetStatusOutboundPolicy");var _l=s(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),ma=s(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new g(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await _l(n.sleepInMs),t},"SleepInboundPolicy");var ga=s(async(t,e,n,r)=>{D(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},i=await F(t,e,o,r);if(i instanceof Response)return i;if(!(i instanceof L))throw new T("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=n.requiredClaims;if(!a)return i;let u=t.user?.data.app_metadata;if(!u)throw new I(`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?R.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var fa=s(async(t,e,n,r)=>{D(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await $(r,n),i=new N(o,e),a=await i.get(r);if(!a){let u=await kl(n,e);i.put(r,u.access_token,u.expires_in-(n.expirationOffsetSeconds??300)),a=u.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");async function kl(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await V({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:n});if(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new I("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 I("Response returned from Azure AD is not in the expected format.")}s(kl,"getAccessToken");var ha="https://accounts.google.com/o/oauth2/token",lo,ya=s(async(t,e,n,r)=>{D(n,r).required("serviceAccountJson","string"),lo||(lo=await K.init(n.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(" ")},i=await $(r,n),a=new N(i,e),u=await a.get(r);if(!u){let c=await oe({serviceAccount:lo,audience:ha,payload:o}),l=await Bt(ha,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new I("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");var Dl="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Ul=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],po,ba=s(async(t,e,n,r)=>{if(D(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new g(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof n.developerClaims<"u"){for(let p in n.developerClaims)if(Object.prototype.hasOwnProperty.call(n.developerClaims,p)){if(Ul.indexOf(p)!==-1)throw new g(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}po||(po=await K.init(n.serviceAccountJson));let i=n.userId;if(!i&&!n.userIdPropertyPath){if(!t.user)throw new I("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");i=t.user?.sub}else if(n.userIdPropertyPath){if(!t.user)throw new I(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=xe(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new I(`Unable to determine user from for the policy ${r}`);let a=await $(r,n),u=new N(a,e),c={uid:i,claims:o},l=await hn(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await oe({serviceAccount:po,audience:Dl,payload:c}),y=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,m=await Ii(y,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!m.idToken)throw new I("Invalid token response from Firebase");d=m.idToken,u.put(l,d,(m.expiresIn?parseInt(m.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var mo,wa=s(async(t,e,n,r)=>{D(n,r).required("audience","string").required("serviceAccountJson","string"),mo||(mo=await K.init(n.serviceAccountJson));let o=await oe({serviceAccount:mo,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var Ra="https://www.googleapis.com/oauth2/v4/token",go,Pa=s(async(t,e,n,r)=>{D(n,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),go||(go=await K.init(n.serviceAccountJson));let o={};if(n.scopes&&n.audience)throw new g("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(n.scopes)try{let c=ve(n.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof g?new g(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}n.audience&&(o.target_audience=`${n.audience}`);let i=await $(r,n),a;n.useMemoryCacheOnly?a=new Le(i):a=new N(i,e);let u=await a.get(r);if(!u){let c=await oe({serviceAccount:go,audience:Ra,payload:o}),l=await Bt(Ra,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(n.audience){if(!l.id_token)throw new I("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new I("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamGcpServiceAuthInboundPolicy");var Ia=s(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return R.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(n.validator(o))return t;let{errors:a}=n.validator;if(!a)throw new T("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 R.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var vn=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(e,n){if(this.services.get(e))throw new T(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,n)}getService(e){return this.services.get(e)}};var fo=["sha-1","sha-256","sha-384","sha-512"],Sn=class{static{s(this,"BaseCryptoBeta")}};var Tn=class extends Sn{static{s(this,"WorkerCryptoBeta")}async digest(e,n){if(!fo.includes(e.toLowerCase()))throw new I(`Algorithm ${e} is not supported. Try using ${fo.join(", ")}`);let r=new TextEncoder().encode(n),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var On=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var Cn=class extends On{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=globalThis.ZUPLO_KV;if(!r)throw new wt("The Key Value Store feature is not enabled for this project.");this.#e=r}put(e,n,r){if(typeof e!="string")throw new g("value must be of type string");return this.#e.put(e,n,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,n){return this.#e.get(e,{type:"text",cacheTtl:n?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};
71
+ `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-n.timestamp;if(o>0&&p>o)throw new se(e,t,{message:"Timestamp outside the tolerance zone"});return!0}s(ol,"validateComputedSignature");function il(t,e){return typeof t!="string"?null:t.split(",").reduce((n,r)=>{let o=r.split("=");return o[0]==="t"&&(n.timestamp=parseInt(o[1],10)),o[0]===e&&n.signatures.push(o[1]),n},{timestamp:-1,signatures:[]})}s(il,"parseHeader");function sl(t,e){if(t.length!==e.length)return!1;let n=t.length,r=0;for(let o=0;o<n;++o)r|=t.charCodeAt(o)^e.charCodeAt(o);return r===0}s(sl,"secureCompare");async function al(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,n.encode(t)),i=new Uint8Array(o),a=new Array(i.length);for(let u=0;u<i.length;u++)a[u]=Gr[i[u]];return a.join("")}s(al,"computeHMACSignatureAsync");var Gr=new Array(256);for(let t=0;t<Gr.length;t++)Gr[t]=t.toString(16).padStart(2,"0");function H(t,e){if(!Ee(t))throw new m(`Options on policy '${e}' is expected to be an object. Received the type '${typeof t}'.`);let n=s((i,a,u)=>{let c=t[i];if(!(u&&c===void 0)){if(c===void 0)throw new m(`Value of '${String(i)}' on policy '${e}' is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(a==="array"&&Array.isArray(c))throw new m(`Value of '${String(i)}' on policy '${e}' must be an array. Received type ${typeof c}.`);if(typeof c!==a)throw new m(`Value of '${String(i)}' on policy '${e}' must be of type ${a}. Received type ${typeof c}.`);if(typeof c=="string"&&c.length===0)throw new m(`Value of '${String(i)}' on policy '${e}' must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof c=="number"&&isNaN(c))throw new m(`Value of '${String(i)}' on policy '${e}' must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),r=s((i,a)=>(n(i,a,!0),{optional:r,required:o}),"optional"),o=s((i,a)=>(n(i,a,!1),{optional:r,required:o}),"required");return{optional:r,required:o}}s(H,"optionValidator");var Be=class extends ue{static{s(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,n){H(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 rs(o,r,this.options.signingSecret)}catch(o){return n.log.error("Error validating stripe webhook",o),R.badRequest(e,n,{title:"Webhook Error",detail:o.message})}return e}};function os(t){return t!==null&&typeof t=="object"&&"id"in t&&W(t.id)&&"type"in t&&W(t.type)}s(os,"isStripeWebhookEvent");var mn=class extends ae{static{s(this,"MeteringPlugin")}};var ul={getSubscription:async({subscriptionId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/subscriptions/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving subscription from Stripe API.";throw n.error(i,o),new P(i)}return o},getCustomer:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await fetch(`https://api.stripe.com/v1/customers/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer from Stripe API.";throw n.error(i,o),new P(i)}return o}},is=ul;var Wr="https://api-key-management-service-eq7z4lly2a-ue.a.run.app";async function ss({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,managerSub:i,context:a}){let{authApiJWT:u}=h.instance,c=new URL(`/v1/buckets/${t}/consumers`,Wr);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:"API Subscription",tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[{sub:i,email:o}]},p=await V({retryDelayMs:5,retries:2,logger:O.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),b=await p.json();if(p.status!==200){let g="Error creating API Key Consumer";throw a.log.error(g,b),new P(g)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:n}),l}s(ss,"createConsumer");async function as({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,context:i}){let{authApiJWT:a}=h.instance,u=new URL(`/v1/buckets/${t}/consumers`,Wr);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:"API Subscription",tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[o]},d=await V({retryDelayMs:5,retries:2,logger:O.getLogger(i)},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 b="Error creating API Key Consumer";throw i.log.error(b,p),new P(b)}return i.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:n}),c}s(as,"createConsumerInvite");async function us({apiKeyBucketName:t,consumerId:e,context:n}){let{authApiJWT:r}=h.instance,o=new URL(`/v1/buckets/${t}/consumers/${e}`,Wr);o.searchParams.set("with-api-key","true");let i=await V({retryDelayMs:5,retries:2,logger:O.getLogger(n)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(i.status!==204){let a=await i.json(),u="Error deleting API Key Consumer";throw n.log.error(u,a),new P(u)}return n.log.info(`Successfully deleted API Key Consumer '${e}`),e}s(us,"deleteConsumer");async function cs({context:t,stripeSubscriptionId:e,stripeProductId:n,customerKey:r,meteringBucketId:o,meteringBucketRegion:i,customerExternalId:a,subscriptionStatus:u}){let c={status:u,type:"periodic",renewalStrategy:"monthly",region:i,subscriptionExternalId:e,planExternalIds:[n],customerKey:r,customerExternalId:a},{authApiJWT:l,meteringServiceUrl:d}=h.instance;if(!Ue(l))throw new T("No Zuplo JWT token set.");let p=await V({retryDelayMs:5,retries:2,logger:O.getLogger(t)},`${d}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(c)});if(!p.ok){let b="Error creating metering subscription.",g;try{g=await p.json()}catch{g={status:p.status,statusText:p.statusText}}throw t.log.error(b,g),new P(b)}t.log.info("Successfully created/updated metering subscription.",c)}s(cs,"createSubscription");async function mt({context:t,meteringSubscriptionId:e,meteringBucketId:n,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:i}=h.instance;if(!Ue(o))throw new T("No Zuplo JWT token set.");let a=await V({retryDelayMs:5,retries:2,logger:O.getLogger(t)},`${i}/internal/v1/metering/${n}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Error updating metering subscription to '${JSON.stringify(r)}'.`,c;try{c=await a.json()}catch{c={status:a.status,statusText:a.statusText}}throw t.log.error(u,c),new P(u)}t.log.info(`Successfully update metering subscription to '${JSON.stringify(r)}'.`)}s(mt,"updateSubscription");async function gt({context:t,stripeSubscriptionId:e,stripeCustomerId:n,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:i}=h.instance;if(!Ue(o))throw new T("No Zuplo JWT token set.");let a=await V({retryDelayMs:5,retries:2,logger:O.getLogger(t)},`${i}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":t.requestId},method:"GET"});if(!a.ok){let c="Error querying for metering subscription.",l;try{l=await a.json()}catch{l={status:a.status,statusText:a.statusText}}throw t.log.error(c,l),new P(c,l)}let u=await a.json();if(u.data.length===0){let c="Subscription was not found and the event was ignored by Stripe metering plugin webhook.";throw t.log.error(c),new P(c)}if(u.data[0].customerExternalId!==n){let c="A subscription was not found for the customer provided and the event was ignored by Stripe metering plugin webhook.";throw t.log.error(c),new P(c)}return u.data[0]}s(gt,"getSubscription");function gn(t){return t.replaceAll("_","-")}s(gn,"stripeStatusToMeteringStatus");async function Kr(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),R.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=n.data.object.plan;if(!i||!i.product)return e.log.warn(`Invalid Stripe API result. Expected event '${n.id}' to have a plan data.`),R.badRequest(t,e,{detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=n.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),R.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let u=i.product,c;if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_email&&n.data.object.metadata.zuplo_created_by_sub)c=await ss({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:n.data.object.metadata.zuplo_created_by_email,managerSub:n.data.object.metadata.zuplo_created_by_sub,context:e});else{let l=await is.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!l.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),R.badRequest(t,e,{detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await as({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l.email,context:e})}if(!c)return R.internalServerError(t,e,{detail:"No consumer was created, skipping creation of subscription"});try{let l=gn(n.data.object.status);await cs({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:l})}catch(l){return await us({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),R.internalServerError(t,e,{detail:l.message})}return R.ok(t,e)}s(Kr,"onCustomerSubscriptionCreated");async function Jr(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),R.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=n.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),R.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let a=await gt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId});return await mt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}}),R.ok(t,e)}s(Jr,"onCustomerSubscriptionDeleted");async function Yr(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to include '.data.object.id' as the subscription ID.`),R.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=n.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),R.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(n.data.previous_attributes){let a=n.data.previous_attributes;if(a.status&&a.status!==n.data.object.status){let u=await gt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=gn(n.data.object.status);return await mt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds}}),R.ok(t,e)}if(a.plan&&a.plan.product!==n.data.object.plan.product){let u=await gt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId});return await mt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[n.data.object.plan.product]}}),R.ok(t,e)}}return e.log.warn(`This update event '${n.id}' is not supported by Stripe metering plugin webhook.`),R.badRequest(t,e,{detail:"This update event is not supported by Stripe metering plugin webhook."})}s(Yr,"onCustomerSubscriptionUpdated");var Qr=class extends mn{constructor(n){super();this.options=n}static{s(this,"StripeMeteringPlugin")}registerRoutes(n,r){let o=s(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(j.ZUPLO_METERING_SERVICE_BUCKET_ID)d=j.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m("StripeMeteringPlugin - No 'meteringBucketId' property provided");if(!p)if(j.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=j.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m("StripeMeteringPlugin - No 'apiKeyBucketName' property provided");if(!h.instance.build.ACCOUNT_NAME)throw new T("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let b=this.options.meteringBucketRegion??"us-central1";if(!cl(b))throw new m(`StripeMeteringPlugin - The value '${b}' on the property 'meteringBucketRegion' is invalid.`);let g=await c.json();if(!os(g))return R.badRequest(c,l,{detail:"The received body was not in the expected format."});switch(l.log.info(`Received Stripe webhook event of type '${g.type}' with ID '${g.id}'.`),g.type){case"customer.subscription.created":return await Kr(c,l,g,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:b,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await Yr(c,l,g,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:b,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await Jr(c,l,g,{meteringBucketId:d});default:return R.badRequest(c,l,{detail:"Event is not supported by Stripe metering plugin webhook."})}},"stripeWebhookHandler"),i=di({inboundPolicies:[new Be({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]}),a=new D({processors:[B,i],handler:o,gateway:r}),u=new k({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});n.addRoute(u,a.execute)}};function cl(t){return t!==null&&typeof t=="string"&&["us-central1","europe-west4"].includes(t)}s(cl,"isMetricsRegion");var ds=new WeakMap,ls={},fn=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){ds.set(e,n)}};async function ps(t,e,n,r){if(!n.statusCodes)throw new m(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Array.isArray(n.statusCodes)?n.statusCodes:Dt(n.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=ds.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new P(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=xe(t.user,n.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??n.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??n.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(n.dimensions??{},a?.dimensions)},b=ls[n.apiKey];if(!b){let g=n.apiKey,w=t.headers.get("zm-test-id")??"";b=new C("amberflo-ingest-meter",10,async I=>{try{let E=n.url??"https://app.amberflo.io/ingest",x=await fetch(E,{method:"POST",body:JSON.stringify(I),headers:{"content-type":"application/json","x-api-key":g,"zm-test-id":w}});x.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${x.status}: ${await x.text()}`)}catch(E){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${E.message}`),E}}),ls[g]=b}b.enqueue(p),e.waitUntil(b.waitUntilFlushed())}}),t}s(ps,"AmberfloMeteringInboundPolicy");async function hn(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")}s(hn,"sha256");var ms=new Map;async function Z(t,e){let n,r=ms.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await hn(JSON.stringify({policyName:t,options:e}))}`,ms.set(t,n)),n}s(Z,"getPolicyCacheName");var gs="key-metadata-cache-type";function ll(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}s(ll,"getKeyValue");async function yn(t,e,n,r){if(!n.bucketName)if(j.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=j.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:n.authHeader??"authorization",authScheme:n.authScheme??"Bearer",bucketName:n.bucketName,cacheTtlSeconds:n.cacheTtlSeconds??60,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:n.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new m(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(E=>o.allowUnauthenticatedRequests?t:R.unauthorized(t,e,{detail:E}),"unauthorizedResponse"),a=t.headers.get(o.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let u=ll(a,o);if(!u||u==="")return i("No key present");let c=await dl(u),l=await Z(r,o),d=new M(l,e),p=await d.get(c);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==gs&&O.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let b={key:u},g=await V({retryDelayMs:5,retries:2,logger:O.getLogger(e)},`${h.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":h.instance.deploymentName??"unknown","User-Agent":h.instance.systemUserAgent},body:JSON.stringify(b)});if(g.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(g.status!==200){try{let E=await g.text(),x=JSON.parse(E);e.log.error("Unexpected response from key service",x)}catch{e.log.error("Invalid response from key service")}throw new P(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${g.status}`)}let w=await g.json(),I={isValid:!0,typeId:gs,user:{sub:w.name,data:w.metadata}};return t.user=I.user,d.put(c,I,o.cacheTtlSeconds),t}s(yn,"ApiKeyInboundPolicy");async function dl(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(dl,"hashValue");var fs=yn;var ft=require("jose");var Xr={},pl=s(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");Xr[e.jwkUrl]||(Xr[e.jwkUrl]=(0,ft.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,ft.jwtVerify)(t,Xr[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),ml=s(async(t,e)=>{let n;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let i=new TextEncoder().encode(e.secret);n=new Uint8Array(i)}else n=e.secret;let{payload:r}=await(0,ft.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),q=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),i="bearer ",a=s(b=>R.unauthorized(t,e,{detail:b}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?pl:ml,l=await s(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(i)!==0)return a("Invalid bearer token format for authorization header");let b=o.substring(i.length);if(!b||b.length===0)return a("No bearer token on authorization header");try{return await u(b,n)}catch(g){let w=new URL(t.url);return"code"in g&&g.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${w.pathname} `,g):e.log.warn(`Invalid token on: ${t.method} ${w.pathname}`,g),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return n.allowUnauthenticatedRequests===!0?t:l;let d=n.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var hs=s(async(t,e,n,r)=>q(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var ys=s(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",i=s(l=>R.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),u=await s(async()=>{if(!r)return await i("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await i("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await i("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let b=d.substring(0,p),g=d.substring(p+1),w=n.accounts.find(I=>I.username===b&&I.password===g);return w||await i("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return n.allowUnauthenticatedRequests?t:u;let c=u.username;return t.user={sub:c,data:u.data},t},"BasicAuthInboundPolicy");var gl=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function fl(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(fl,"digestMessage");var hl=s(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of t.headers.entries())n.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await fl(JSON.stringify(r)),i=new URL(t.url),a=new URLSearchParams(i.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",t.method);let c=`${i.origin}${i.pathname}?${a}`;return new Request(c,{method:u?"GET":t.method})},"createCacheKeyRequest");async function bs(t,e,n,r){let o=await Z(r,n),i=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await hl(t,n),c=await i.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=n.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let b=n?.expirationSecondsTtl??60,g=new Response(p.body,p);gl.forEach(w=>g.headers.delete(w)),g.headers.set("cache-control",`s-maxage=${b}`),e.waitUntil(i.put(u,g))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}s(bs,"CachingInboundPolicy");var ws=s(async(t,e,n,r)=>{if(!n.method)throw new m(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new A(t,{method:n.method})},"ChangeMethodInboundPolicy");var Rs=s(async(t,e,n)=>{let r=[...n.exclude??[]],o=new Headers;return r.forEach(a=>{let u=t.headers.get(a);u&&o.set(a,u)}),new A(t,{headers:o})},"ClearHeadersInboundPolicy");var Ps=s(async(t,e,n,r)=>{let o=[...r.exclude??[]],i=new Headers;return o.forEach(u=>{let c=t.headers.get(u);c&&i.set(u,c)}),new Response(t.body,{headers:i,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");var Is=s(async(t,e,n,r)=>{let o=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",q(t,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var Es=s(async(t,e,n,r)=>{if(!n.userPoolId)throw new m("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new m("region must be set in the options for CognitoJwtInboundPolicy");return q(t,e,{issuer:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}`,jwkUrl:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var xs=s(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new m(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=N.instance,i=ot(n.policies,o?.routeData.policies);return mr(i)(t,e)},"CompositeInboundPolicy");var vs=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization");if(!o)return R.unauthorized(t,e,{detail:"No authorization header"});let i=yl(o);if(!i)return R.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await Z(r,n),u=new M(a,e),c=await u.get(i);if(!c){let l=await fetch(n.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${n.clientId}:${n.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+i+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(i,c,n.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),R.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):R.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${c}`),t},"CurityPhantomTokenInboundPolicy");function yl(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}s(yl,"getToken");var Ss=s(async(t,e,n,r)=>(H(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),q(t,e,{issuer:`https://securetoken.google.com/${n.projectId}`,audience:n.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var Ts=s(async(t,e,n)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",i=t.headers.get("content-type")?.toLowerCase();if(!i||![o,r].includes(i))return n&&n.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(n&&n.optionalHoneypotName&&a.get(n.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(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new A(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var je="__unknown__",Os=s(async(t,e,n,r)=>{let o={allow:{countries:Ve(n.allow?.countries,"allow.countries",r),regionCodes:Ve(n.allow?.regionCodes,"allow.regionCode",r),asns:Ve(n.allow?.asns,"allow.asOrganization",r)},block:{countries:Ve(n.block?.countries,"block.countries",r),regionCodes:Ve(n.block?.regionCodes,"block.regionCode",r),asns:Ve(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??je,a=e.incomingRequestProperties.regionCode?.toLowerCase()??je,u=e.incomingRequestProperties.asn?.toString()??je,c=o.ignoreUnknown&&i===je,l=o.ignoreUnknown&&a===je,d=o.ignoreUnknown&&u===je,p=o.allow.countries,b=o.allow.regionCodes,g=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||b.length>0&&!b.includes(a)&&!l||g.length>0&&!g.includes(u)&&!d)return ze(t,e,r,i,a,u);let w=o.block.countries,I=o.block.regionCodes,E=o.block.asns;return w.length>0&&w.includes(i)&&!c||I.length>0&&I.includes(a)&&!l||E.length>0&&E.includes(u)&&!d?ze(t,e,r,i,a,u):t},"GeoFilterInboundPolicy");function ze(t,e,n,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),R.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(ze,"blockedResponse");function Ve(t,e,n){if(typeof t=="string")return t.split(",").map(r=>r.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(r=>r.trim().toLowerCase());throw new m(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}s(Ve,"toLowerStringArray");var Cs=s(async(t,e,n)=>{let r=t.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(u=>i.includes(u)),"scopeChecker")(r,n.scopes)){let i={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${n.scopes}`};return new Response(JSON.stringify(i),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");async function As(t,e,n,r){let o=O.getLogger(t),{authApiJWT:i,meteringServiceUrl:a}=h.instance,u;try{let l=await fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":t.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.";t.log.error(`MonetizationInboundPolicy '${n}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription`,l)}return u&&u.data&&u.data.length>0?u.data[0]:void 0}s(As,"loadSubscription");async function Ls(t,e,n,r,o){let{authApiJWT:i,meteringServiceUrl:a}=h.instance,u=O.getLogger(t);try{let c=await fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":t.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.";t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`,c)}}s(Ls,"consumeSubcriptionQuotas");var bl=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function _s(t,e){try{let n=[];for(let r in t)typeof t[r]!="number"&&!(Number.isInteger(t[r])&&/^-?\d+$/.test(t[r].toString()))&&n.push(r);if(n.length>0)throw new m(n.length>1?`The values found in these properties are not integers : ${n.join(", ")}`:`The value in property '${n[0]}' is not an integer`)}catch(n){throw n instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${n.message}`):n}}s(_s,"validateMeters");function ks(t,e){if(t)try{if(t.length===0)throw new m("Must set valid subscription statuses");let n=ve(t),r=[];for(let o of n)bl.has(o)||r.push(o);if(r.length>0)throw new m(`Found the following invalid statuses: ${r.join(", ")}`);return t}catch(n){throw n instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${n.message}`):n}else return["active","incomplete","trialing"]}s(ks,"parseAllowedSubscriptionStatuses");var Ds=s(async(t,e,n,r)=>{if(H(n,r).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),!n.meterOnStatusCodes)throw new m(`Invalid MonetizationInboundPolicy '${r}' - The property 'meterOnStatusCodes' must be an array of HTTP status code numbers`);let o=n.allowRequestsOverQuota??!1,i=Array.isArray(n.meterOnStatusCodes)?n.meterOnStatusCodes:Dt(n.meterOnStatusCodes);_s(n.meters,r);let a=n.allowRequestsWithoutSubscription??!1,u=ks(n.allowedSubscriptionStatuses,r);e.addResponseSendingFinalHook(async(w,I,E)=>{let x=ye.get(E,Rt);if((n.allowRequestsWithoutSubscription??!1)&&!x){E.log.debug(`MonetizationInboundPolicy '${r}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!n.bucketId)if(j.ZUPLO_METERING_SERVICE_BUCKET_ID)n.bucketId=j.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${r}' - No bucketId property provided`);i.includes(w.status)&&x&&n.meters&&(E.log.debug(`MonetizationInboundPolicy '${r}' - Updating subscription '${x.id}' with meters '${JSON.stringify(n.meters)} on response status '${w.status}'`),await Ls(E,x.id,r,n.bucketId,n.meters))});let c=t.user;if(!c)return a?t:R.unauthorized(t,e,{detail:"Unable to check subscription for anonymous user"});if(!n.bucketId)if(j.ZUPLO_METERING_SERVICE_BUCKET_ID)n.bucketId=j.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${r}' - No bucketId property provided`);let{sub:l}=c,d=await As(e,l,r,n.bucketId);if(!d)return e.log.warn("No valid subscription found"),a?t:R.unauthorized(t,e,{detail:"No valid subscription found"});if(!u.includes(d.status)&&!a)return e.log.warn(`Subscription '${d.id}' has status '${d.status}' which is not part of the allowed statuses.`),R.unauthorized(t,e,{detail:"No valid subscription found"});u.includes(d.status)&&(e.log.debug(`Loading subscription '${d.id}' for user sub '${l}' to ContextData`),ye.set(e,Rt,d));let p=ye.get(e,Rt);if(!p)return a?t:(e.log.warn("Subscription is not available for user"),R.paymentRequired(t,e,{detail:"Subscription is not available for user",title:"No Subscription"}));if(p&&Object.keys(p.quotas).length===0)return e.log.error(`Quota is not set up for subscription '${p.id}'`),R.tooManyRequests(t,e,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let g=Object.keys(n.meters).filter(w=>!Object.keys(p.quotas).includes(w));if(g.length>0)return e.log.warn(`The following policy meters are not present in the subscription: ${g.join(", ")}`),R.tooManyRequests(t,e,{detail:`The following policy meters are not present in the subscription: ${g.join(", ")}`,title:"Quota Exceeded"});for(let w of Object.keys(n.meters))if(p.quotas[w]<=0&&!o)return R.tooManyRequests(t,e,{detail:`Quota exceeded for meter '${w}'`,title:"Quota Exceeded"});return t},"MonetizationInboundPolicy");var Hs=s(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return eo(r,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return eo(r,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(i.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(b=>{a.push({responseName:u,contentName:l,exampleName:b,exampleValue:d[b]})})})}),a=a.filter(u=>!(n.responsePrefixFilter&&!u.responseName.startsWith(n.responsePrefixFilter)||n.contentType&&u.contentName!==n.contentType||n.exampleName&&u.exampleName!==n.exampleName)),n.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return Us(a[u])}else return a.length>0?Us(a[0]):eo(r,t,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 Us(t){let e=JSON.stringify(t.exampleValue,null,2),n=new Headers;switch(n.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:n});case"2XX":return new Response(e,{status:200,headers:n});case"3XX":return new Response(e,{status:300,headers:n});case"4XX":return new Response(e,{status:400,headers:n});case"5XX":case"default":return new Response(e,{status:500,headers:n});default:return new Response(e,{status:Number(t.responseName),headers:n})}}s(Us,"generateResponse");var eo=s((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return R.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var wl="Incoming",Rl={logRequestBody:!0,logResponseBody:!0};function Ms(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}s(Ms,"headersToObject");function Ns(){return new Date().toISOString()}s(Ns,"timestamp");var to=new WeakMap,Pl={};function $s(t,e){let n=to.get(t);n||(n=Pl);let r=Object.assign({...n},e);to.set(t,r)}s($s,"setMoesifContext");async function Zs(t,e){let n=t.headers.get("content-type");if(n&&n.indexOf("json")!==0)try{return await t.clone().json()}catch(o){e.log.error(o)}let r=await t.clone().text();return e.log.debug({textBody:r}),r}s(Zs,"readBody");var Il={},no;function qs(){if(!no)throw new P("Invalid State - no _lastLogger");return no}s(qs,"getLastLogger");function El(t){let e=Il[t];return e||(e=new C("moesif-inbound",100,async n=>{let r=JSON.stringify(n);qs().debug("posting",r);let o=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:r});o.ok||qs().error({status:o.status,body:await o.text()})})),e}s(El,"getDispatcher");async function Fs(t,e,n,r){no=e.log;let o=Ns(),i=Object.assign(Rl,n);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await Zs(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=El(i.applicationId),d=t.headers.get("true-client-ip"),p=to.get(e)??{},b={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Ms(t.headers)},g=i.logResponseBody?await Zs(u,e):void 0,w={time:Ns(),status:u.status,headers:Ms(u.headers),body:g},I={request:b,response:w,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:wl};l.enqueue(I),e.waitUntil(l.waitUntilFlushed())}),t}s(Fs,"MoesifInboundPolicy");var Bs=s(async(t,e,n,r)=>q(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var js=require("jose");var ro,zs=s(async(t,e,n,r)=>{if(!ro)try{ro=await(0,js.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return q(t,e,{issuer:n.authUrl,secret:ro,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Gs=Ae(Pe());var bn=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},oo=class extends bn{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},io=class extends bn{static{s(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function xl(t,e){if(ii(t))throw new oo(e)}s(xl,"throwIfUndefinedOrNull");function ht(t,e){if(xl(t,e),!W(t))throw new io(e,"string")}s(ht,"throwIfNotString");var wn=class t{static{s(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,n,r,o){this.redisClientUrl=e,this.clientAuthToken=n,this.deploymentName=r,this.userAgent=o}static initialize(e,n,r,o){return ht(e,"redisClientUrl"),ht(n,"clientAuthToken"),t.instance||(t.instance=new t(e,n,r,o)),t.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:n,method:r,requestId:o}){ht(e,"url");let i=await fetch(`${this.redisClientUrl}${e}`,{method:r,body:n,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=i.headers.get("Content-Type")?.includes("application/json")?await i.json():await i.text();if(i.ok)return a;throw i.status===401?new T("Redis client failed with 401: Unauthorized"):new T(`Redis client failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},Rn=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(ht(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:i,key:a}=JSON.parse(n),u=Date.now()+i*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new T("The in-memory redis client only supports /rate-limit calls")}};var Pn=(0,Gs.debug)("zuplo:policies:RateLimitInboundPolicy"),vl="strict",Sl=s(t=>{let e=t.headers.get("cf-connecting-ip")??t.headers.get("true-client-ip");if(e)return e;let n=t.headers.get("x-forwarded-for");return n?n.split(",")[0]:"127.0.0.1"},"getRealIP"),Tl=s(async t=>({key:`ip-${Sl(t)}`}),"getIP"),Ol=s(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),Cl=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),In;function Al(t,e){let n;if(In)return In;if(h.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new Rn,In=n,n;let{authApiJWT:r,redisURL:o}=h.instance;if(!W(o))throw new T(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!W(r))throw new T(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=wn.initialize(o,r,h.instance.deploymentName??"unknown",h.instance.systemUserAgent)),!n||!n.isEnabled())throw new T(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return In=n,n}s(Al,"getRedisClient");async function Vs(t,e,n,r,o){let i=Math.floor(e*60);return await n.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:i,key:t}),requestId:o})}s(Vs,"getCountAndUpdateExpiry");function Ll(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new m(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new m(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new m(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(n=t.identifier.module[t.identifier.export],!n||typeof n!="function")throw new m(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return s(async(o,i,a)=>{let u=await n(o,i,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw i.log.error(c),new P(c)}return u},"outerFunction")}s(Ll,"wrapUserFunction");var _l="Retry-After",so=s(async(t,e,n,r)=>{let o=Date.now(),i=O.getLogger(e),a=s((c,l)=>{if(n.throwOnFailure)throw new T(c,{cause:l});i.error(c,l)},"throwOrLog"),u=s((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[_l]=l.toString()),R.tooManyRequests(t,e,void 0,d)},"rateLimited");try{let l={function:Ll(n,r),user:Ol,ip:Tl,all:Cl}[n.rateLimitBy],d=await l(t,e,r),p=d.key,b=d.requestsAllowed??n.requestsAllowed,g=d.timeWindowMinutes??n.timeWindowMinutes,w=n.headerMode??"retry-after",I=Al(r,i),x=`bucket/${h.instance.build.BUILD_ID}/${r}/${p}`;if((n.mode??vl)==="async"){let _=await Z(r,n),G=new le(_,{logger:O.getLogger(e)}),Y=Vs(x,g,I,i,e.requestId),Q=await G.get(x);if(Q!==void 0&&Q<=Date.now()){Pn(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${x}' (async mode)`);let Oe=Math.round((Q-Date.now())/1e3);return u(w,Oe)}return e.addEventListener("responseSending",Oe=>{try{let Ce=Oe,An=Ce.mutableResponse;Ce.mutableResponse=(async()=>{let yt=await Y;if(yt.count>b){let Sa=Date.now()+yt.ttlSeconds*1e3,Ta=G.put(x,Sa,yt.ttlSeconds).catch(ho=>{throw i.error(new T("Error caching rate limit result.",{cause:ho})),ho});return e.waitUntil(Ta),Pn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${x}' (async mode)`),u(w,yt.ttlSeconds)}return An})()}catch(Ce){i.error(`RateLimitInboundPolicy '${r}' -error in responseSending`,Ce)}}),t}let $=await Vs(x,g,I,i,e.requestId);return $.count>b?(Pn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${x}' (strict mode)`),u(w,$.ttlSeconds)):t}catch(c){return a(c.message,c),t}finally{let c=Date.now()-o;Pn(`RateLimitInboundPolicy '${r}' - latency ${c}ms`)}},"RateLimitInboundPolicy");var ao;function Ws(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}s(Ws,"headersToNameValuePairs");function kl(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}s(kl,"queryToNameValueParis");function Dl(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}s(Dl,"parseIntOrUndefined");var Ks={};async function Js(t,e,n,r){let o=new Date,i=Date.now();return ao||(ao={name:"zuplo",version:h.instance.build.ZUPLO_VERSION,comment:`zuplo/${h.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?xe(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?xe(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:h.instance.isDeno,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:ao,entries:[{startedDateTime:o.toISOString(),time:Date.now()-i,request:{method:t.method,url:n.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:Ws(t.headers),queryString:kl(t.query)},response:{status:a.status,statusText:a.statusText,headers:Ws(a.headers),content:{size:Dl(t.headers.get("content-length"))}}}]}}},d=Ks[n.apiKey];if(!d){let p=n.apiKey;d=new C("readme-metering-inbound-policy",10,async b=>{try{let g=n.url??"https://metrics.readme.io/request",w=await fetch(g,{method:"POST",body:JSON.stringify(b),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});w.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${w.status}: '${await w.text()}'`)}catch(g){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${g.message}'`),g}}),Ks[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}s(Js,"ReadmeMetricsInboundPolicy");var Ys=s(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new m(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(t.headers);return o.forEach(u=>{i.delete(u)}),new A(t,{headers:i})},"RemoveHeadersInboundPolicy");var Qs=s(async(t,e,n,r,o)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new m(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return i.forEach(c=>{a.delete(c)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");var Xs=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new m(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(t.url);return o.forEach(u=>{i.searchParams.delete(u)}),new A(i.toString(),t)},"RemoveQueryParamsInboundPolicy");var ea=s(async(t,e,n,r)=>{let o=await t.text(),i=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(i,r.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");var ta=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),na=s(async(t,e,n)=>{let r=n.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let o=t.headers.get("content-length"),i=o!==null?parseInt(o):void 0;return i&&!isNaN(i)&&i>n.maxSizeInBytes?ta():i&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?ta():t},"RequestSizeLimitInboundPolicy");function ra(t,e,n){return`_${we(t+"_"+e+"_"+n)}`}s(ra,"getRawOperationDataIdentifierName");function En(t,e,n,r){return`_${we(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}s(En,"getIdForParameterSchema");function xn(t,e,n){return`_${we(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${we(n.toLowerCase())}`}s(xn,"getIdForRequestBodySchema");function oa(t,e){return`_${we(t)}__${we(e)}`}s(oa,"getIdForRefSchema");function we(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(t.charAt(n)):e.push("_")}return e.join("")}s(we,"sanitizedIdentifierName");var Ge=s(t=>{let e=t.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"),We=s((t,e,n,r,o)=>{let i=[],a=!0,u=[];return t.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=En(n,r,o,c.name),p=N.instance.schemaValidator[d],b=p(e[c.name]),g=uo(p.errors);b||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${g.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),ee=s((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),te=s(t=>t==="log-only"||t==="reject-and-log","shouldLog"),ne=s(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),uo=s(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function ia(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(g){let w=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,I=R.badRequest(e,t,{detail:`${w}, see errors property for more details`,errors:`${g}`});if(te(n.validateBody)&&ee(t,n.logLevel??"info",w,[r],g),ne(n.validateBody))return I}if(!e.headers.get("Content-Type")){let g=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,w=R.badRequest(e,t,{detail:g});return te(n.validateBody)&&ee(t,n.logLevel??"info",g,[r],[g]),ne(n.validateBody)?w:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=xn(t.route.path,e.method,o),u=N.instance.schemaValidator[a];if(!u){let g=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,w=R.badRequest(e,t,{detail:g});return te(n.validateBody)&&ee(t,n.logLevel??"info",g,[r],[g]),ne(n.validateBody)?w:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=uo(l),b=R.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(te(n.validateBody)&&ee(t,n.logLevel??"info",d,[r],p),ne(n.validateBody))return b}s(ia,"handleBodyValidation");function sa(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Ge(t),i=We(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=R.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:i.errors});if(te(n.validateHeaders)&&ee(t,n.logLevel??"info",a,i.invalidValues,i.errors),ne(n.validateHeaders))return u}}s(sa,"handleHeadersValidation");function aa(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=Ge(t),o=We(r.filter(i=>i.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let i="Path parameters validation failed",a=R.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(te(n.validatePathParameters)&&ee(t,n.logLevel??"info",i,o.invalidValues,o.errors),ne(n.validatePathParameters))return a}}s(aa,"handlePathParameterValidation");function ua(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=Ge(t),o=We(r.filter(i=>i.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let i="Query parameters validation failed",a=R.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(te(n.validateQueryParameters)&&ee(t,n.logLevel??"info",i,o.invalidValues,o.errors),ne(n.validateQueryParameters))return a}}s(ua,"handleQueryParameterValidation");var co=s(async(t,e,n)=>{let r=ua(e,t,n);if(r!==void 0||(r=aa(e,t,n),r!==void 0)||(r=sa(e,t,n),r!==void 0))return r;let o=await ia(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),ca=co;var la=s(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new m(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof n.origins=="string"?n.origins.split(","):n.origins;o=o.map(a=>a.trim());let i=t.headers.get("origin");if(!i||!o.includes(i)){let a=n.failureDetail??"Forbidden";return R.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var da=s(async(t,e,n)=>new A(t,{body:n.body}),"SetBodyInboundPolicy");var pa=s(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new m(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new A(t,{headers:i})},"SetHeadersInboundPolicy");var ma=s(async(t,e,n,r,o)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new m(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new m(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");var ga=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new m(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new A(i.toString(),t)},"SetQueryParamsInboundPolicy");var fa=s(async(t,e,n,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(t.body,{headers:t.headers,status:r.status,statusText:r.statusText??t.statusText})},"SetStatusOutboundPolicy");var Ul=s(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),ha=s(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new m(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await Ul(n.sleepInMs),t},"SleepInboundPolicy");var ya=s(async(t,e,n,r)=>{H(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},i=await q(t,e,o,r);if(i instanceof Response)return i;if(!(i instanceof A))throw new T("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=n.requiredClaims;if(!a)return i;let u=t.user?.data.app_metadata;if(!u)throw new P(`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?R.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var ba=s(async(t,e,n,r)=>{H(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await Z(r,n),i=new M(o,e),a=await i.get(r);if(!a){let u=await Hl(n,e);i.put(r,u.access_token,u.expires_in-(n.expirationOffsetSeconds??300)),a=u.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");async function Hl(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await V({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:n});if(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new P("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 P("Response returned from Azure AD is not in the expected format.")}s(Hl,"getAccessToken");var wa="https://accounts.google.com/o/oauth2/token",lo,Ra=s(async(t,e,n,r)=>{H(n,r).required("serviceAccountJson","string"),lo||(lo=await K.init(n.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(" ")},i=await Z(r,n),a=new M(i,e),u=await a.get(r);if(!u){let c=await oe({serviceAccount:lo,audience:wa,payload:o}),l=await Bt(wa,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new P("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");var Ml="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Nl=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],po,Pa=s(async(t,e,n,r)=>{if(H(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new m(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof n.developerClaims<"u"){for(let p in n.developerClaims)if(Object.prototype.hasOwnProperty.call(n.developerClaims,p)){if(Nl.indexOf(p)!==-1)throw new m(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}po||(po=await K.init(n.serviceAccountJson));let i=n.userId;if(!i&&!n.userIdPropertyPath){if(!t.user)throw new P("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");i=t.user?.sub}else if(n.userIdPropertyPath){if(!t.user)throw new P(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=xe(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new P(`Unable to determine user from for the policy ${r}`);let a=await Z(r,n),u=new M(a,e),c={uid:i,claims:o},l=await hn(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await oe({serviceAccount:po,audience:Ml,payload:c}),b=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,g=await Ii(b,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!g.idToken)throw new P("Invalid token response from Firebase");d=g.idToken,u.put(l,d,(g.expiresIn?parseInt(g.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var mo,Ia=s(async(t,e,n,r)=>{H(n,r).required("audience","string").required("serviceAccountJson","string"),mo||(mo=await K.init(n.serviceAccountJson));let o=await oe({serviceAccount:mo,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var Ea="https://www.googleapis.com/oauth2/v4/token",go,xa=s(async(t,e,n,r)=>{H(n,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),go||(go=await K.init(n.serviceAccountJson));let o={};if(n.scopes&&n.audience)throw new m("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(n.scopes)try{let c=ve(n.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof m?new m(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}n.audience&&(o.target_audience=`${n.audience}`);let i=await Z(r,n),a;n.useMemoryCacheOnly?a=new Le(i):a=new M(i,e);let u=await a.get(r);if(!u){let c=await oe({serviceAccount:go,audience:Ea,payload:o}),l=await Bt(Ea,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(n.audience){if(!l.id_token)throw new P("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new P("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamGcpServiceAuthInboundPolicy");var va=s(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return R.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(n.validator(o))return t;let{errors:a}=n.validator;if(!a)throw new T("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 R.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var vn=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(e,n){if(this.services.get(e))throw new T(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,n)}getService(e){return this.services.get(e)}};var fo=["sha-1","sha-256","sha-384","sha-512"],Sn=class{static{s(this,"BaseCryptoBeta")}};var Tn=class extends Sn{static{s(this,"WorkerCryptoBeta")}async digest(e,n){if(!fo.includes(e.toLowerCase()))throw new P(`Algorithm ${e} is not supported. Try using ${fo.join(", ")}`);let r=new TextEncoder().encode(n),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var On=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var Cn=class extends On{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=globalThis.ZUPLO_KV;if(!r)throw new bt("The Key Value Store feature is not enabled for this project.");this.#e=r}put(e,n,r){if(typeof e!="string")throw new m("value must be of type string");return this.#e.put(e,n,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,n){return this.#e.get(e,{type:"text",cacheTtl:n?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};
72
72
  /*! For license information please see index.minified.js.LEGAL.txt */