@zuplo/runtime 5.1724.0 → 5.1725.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,7 +22,7 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- "use strict";var ia=Object.create;var Be=Object.defineProperty;var sa=Object.getOwnPropertyDescriptor;var aa=Object.getOwnPropertyNames;var ua=Object.getPrototypeOf,ca=Object.prototype.hasOwnProperty;var s=(t,e)=>Be(t,"name",{value:e,configurable:!0});var ze=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),la=(t,e)=>{for(var n in e)Be(t,n,{get:e[n],enumerable:!0})},Xr=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of aa(e))!ca.call(t,o)&&o!==n&&Be(t,o,{get:()=>e[o],enumerable:!(r=sa(e,o))||r.enumerable});return t};var Oe=(t,e,n)=>(n=t!=null?ia(ua(t)):{},Xr(e||!t||!t.__esModule?Be(n,"default",{value:t,enumerable:!0}):n,t)),da=t=>Xr(Be({},"__esModule",{value:!0}),t);var Po=ze(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 mo=!0,Un=!mo;function pa(t){mo||(Un=t)}s(pa,"setColorEnabled");b.setColorEnabled=pa;function ma(){return Un}s(ma,"getColorEnabled");b.getColorEnabled=ma;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 O(t,e){return Un?`${e.open}${t.replace(e.regexp,e.open)}${e.close}`:t}s(O,"run");function ga(t){return O(t,v([0],0))}s(ga,"reset");b.reset=ga;function fa(t){return O(t,v([1],22))}s(fa,"bold");b.bold=fa;function ha(t){return O(t,v([2],22))}s(ha,"dim");b.dim=ha;function ya(t){return O(t,v([3],23))}s(ya,"italic");b.italic=ya;function ba(t){return O(t,v([4],24))}s(ba,"underline");b.underline=ba;function wa(t){return O(t,v([7],27))}s(wa,"inverse");b.inverse=wa;function Ra(t){return O(t,v([8],28))}s(Ra,"hidden");b.hidden=Ra;function Pa(t){return O(t,v([9],29))}s(Pa,"strikethrough");b.strikethrough=Pa;function Ea(t){return O(t,v([30],39))}s(Ea,"black");b.black=Ea;function go(t){return O(t,v([31],39))}s(go,"red");b.red=go;function fo(t){return O(t,v([32],39))}s(fo,"green");b.green=fo;function ho(t){return O(t,v([33],39))}s(ho,"yellow");b.yellow=ho;function yo(t){return O(t,v([34],39))}s(yo,"blue");b.blue=yo;function bo(t){return O(t,v([35],39))}s(bo,"magenta");b.magenta=bo;function wo(t){return O(t,v([36],39))}s(wo,"cyan");b.cyan=wo;function Ia(t){return O(t,v([37],39))}s(Ia,"white");b.white=Ia;function xa(t){return Ro(t)}s(xa,"gray");b.gray=xa;function Ro(t){return O(t,v([90],39))}s(Ro,"brightBlack");b.brightBlack=Ro;function va(t){return O(t,v([91],39))}s(va,"brightRed");b.brightRed=va;function Oa(t){return O(t,v([92],39))}s(Oa,"brightGreen");b.brightGreen=Oa;function Ta(t){return O(t,v([93],39))}s(Ta,"brightYellow");b.brightYellow=Ta;function Sa(t){return O(t,v([94],39))}s(Sa,"brightBlue");b.brightBlue=Sa;function Ca(t){return O(t,v([95],39))}s(Ca,"brightMagenta");b.brightMagenta=Ca;function Aa(t){return O(t,v([96],39))}s(Aa,"brightCyan");b.brightCyan=Aa;function La(t){return O(t,v([97],39))}s(La,"brightWhite");b.brightWhite=La;function _a(t){return O(t,v([40],49))}s(_a,"bgBlack");b.bgBlack=_a;function ka(t){return O(t,v([41],49))}s(ka,"bgRed");b.bgRed=ka;function Da(t){return O(t,v([42],49))}s(Da,"bgGreen");b.bgGreen=Da;function Ha(t){return O(t,v([43],49))}s(Ha,"bgYellow");b.bgYellow=Ha;function Ua(t){return O(t,v([44],49))}s(Ua,"bgBlue");b.bgBlue=Ua;function Na(t){return O(t,v([45],49))}s(Na,"bgMagenta");b.bgMagenta=Na;function Ma(t){return O(t,v([46],49))}s(Ma,"bgCyan");b.bgCyan=Ma;function Za(t){return O(t,v([47],49))}s(Za,"bgWhite");b.bgWhite=Za;function qa(t){return O(t,v([100],49))}s(qa,"bgBrightBlack");b.bgBrightBlack=qa;function $a(t){return O(t,v([101],49))}s($a,"bgBrightRed");b.bgBrightRed=$a;function Fa(t){return O(t,v([102],49))}s(Fa,"bgBrightGreen");b.bgBrightGreen=Fa;function Ba(t){return O(t,v([103],49))}s(Ba,"bgBrightYellow");b.bgBrightYellow=Ba;function za(t){return O(t,v([104],49))}s(za,"bgBrightBlue");b.bgBrightBlue=za;function ja(t){return O(t,v([105],49))}s(ja,"bgBrightMagenta");b.bgBrightMagenta=ja;function Va(t){return O(t,v([106],49))}s(Va,"bgBrightCyan");b.bgBrightCyan=Va;function Ga(t){return O(t,v([107],49))}s(Ga,"bgBrightWhite");b.bgBrightWhite=Ga;function me(t,e=255,n=0){return Math.trunc(Math.max(Math.min(t,e),n))}s(me,"clampAndTruncate");function Ka(t,e){return O(t,v([38,5,me(e)],39))}s(Ka,"rgb8");b.rgb8=Ka;function Wa(t,e){return O(t,v([48,5,me(e)],49))}s(Wa,"bgRgb8");b.bgRgb8=Wa;function Ja(t,e){return typeof e=="number"?O(t,v([38,2,e>>16&255,e>>8&255,e&255],39)):O(t,v([38,2,me(e.r),me(e.g),me(e.b)],39))}s(Ja,"rgb24");b.rgb24=Ja;function Ya(t,e){return typeof e=="number"?O(t,v([48,2,e>>16&255,e>>8&255,e&255],49)):O(t,v([48,2,me(e.r),me(e.g),me(e.b)],49))}s(Ya,"bgRgb24");b.bgRgb24=Ya;var Qa=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 Xa(t){return t.replace(Qa,"")}s(Xa,"stripColor");b.stripColor=Xa;b.colorFunctions=[go,fo,ho,yo,bo,wo];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 tu(t){let e=Math.abs(eu(t));return b.colorFunctions[e%b.colorFunctions.length]}s(tu,"generateColor");b.generateColor=tu});var Eo=ze(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.format=void 0;function nu(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(`
25
+ "use strict";var ia=Object.create;var Be=Object.defineProperty;var sa=Object.getOwnPropertyDescriptor;var aa=Object.getOwnPropertyNames;var ua=Object.getPrototypeOf,ca=Object.prototype.hasOwnProperty;var s=(t,e)=>Be(t,"name",{value:e,configurable:!0});var ze=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),la=(t,e)=>{for(var n in e)Be(t,n,{get:e[n],enumerable:!0})},Xr=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of aa(e))!ca.call(t,o)&&o!==n&&Be(t,o,{get:()=>e[o],enumerable:!(r=sa(e,o))||r.enumerable});return t};var Oe=(t,e,n)=>(n=t!=null?ia(ua(t)):{},Xr(e||!t||!t.__esModule?Be(n,"default",{value:t,enumerable:!0}):n,t)),da=t=>Xr(Be({},"__esModule",{value:!0}),t);var Po=ze(w=>{"use strict";Object.defineProperty(w,"__esModule",{value:!0});w.generateColor=w.colorFunctions=w.stripColor=w.bgRgb24=w.rgb24=w.bgRgb8=w.rgb8=w.bgBrightWhite=w.bgBrightCyan=w.bgBrightMagenta=w.bgBrightBlue=w.bgBrightYellow=w.bgBrightGreen=w.bgBrightRed=w.bgBrightBlack=w.bgWhite=w.bgCyan=w.bgMagenta=w.bgBlue=w.bgYellow=w.bgGreen=w.bgRed=w.bgBlack=w.brightWhite=w.brightCyan=w.brightMagenta=w.brightBlue=w.brightYellow=w.brightGreen=w.brightRed=w.brightBlack=w.gray=w.white=w.cyan=w.magenta=w.blue=w.yellow=w.green=w.red=w.black=w.strikethrough=w.hidden=w.inverse=w.underline=w.italic=w.dim=w.bold=w.reset=w.getColorEnabled=w.setColorEnabled=void 0;var mo=!0,Un=!mo;function pa(t){mo||(Un=t)}s(pa,"setColorEnabled");w.setColorEnabled=pa;function ma(){return Un}s(ma,"getColorEnabled");w.getColorEnabled=ma;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 O(t,e){return Un?`${e.open}${t.replace(e.regexp,e.open)}${e.close}`:t}s(O,"run");function ga(t){return O(t,v([0],0))}s(ga,"reset");w.reset=ga;function fa(t){return O(t,v([1],22))}s(fa,"bold");w.bold=fa;function ha(t){return O(t,v([2],22))}s(ha,"dim");w.dim=ha;function ya(t){return O(t,v([3],23))}s(ya,"italic");w.italic=ya;function ba(t){return O(t,v([4],24))}s(ba,"underline");w.underline=ba;function wa(t){return O(t,v([7],27))}s(wa,"inverse");w.inverse=wa;function Ra(t){return O(t,v([8],28))}s(Ra,"hidden");w.hidden=Ra;function Pa(t){return O(t,v([9],29))}s(Pa,"strikethrough");w.strikethrough=Pa;function Ea(t){return O(t,v([30],39))}s(Ea,"black");w.black=Ea;function go(t){return O(t,v([31],39))}s(go,"red");w.red=go;function fo(t){return O(t,v([32],39))}s(fo,"green");w.green=fo;function ho(t){return O(t,v([33],39))}s(ho,"yellow");w.yellow=ho;function yo(t){return O(t,v([34],39))}s(yo,"blue");w.blue=yo;function bo(t){return O(t,v([35],39))}s(bo,"magenta");w.magenta=bo;function wo(t){return O(t,v([36],39))}s(wo,"cyan");w.cyan=wo;function Ia(t){return O(t,v([37],39))}s(Ia,"white");w.white=Ia;function xa(t){return Ro(t)}s(xa,"gray");w.gray=xa;function Ro(t){return O(t,v([90],39))}s(Ro,"brightBlack");w.brightBlack=Ro;function va(t){return O(t,v([91],39))}s(va,"brightRed");w.brightRed=va;function Oa(t){return O(t,v([92],39))}s(Oa,"brightGreen");w.brightGreen=Oa;function Ta(t){return O(t,v([93],39))}s(Ta,"brightYellow");w.brightYellow=Ta;function Sa(t){return O(t,v([94],39))}s(Sa,"brightBlue");w.brightBlue=Sa;function Ca(t){return O(t,v([95],39))}s(Ca,"brightMagenta");w.brightMagenta=Ca;function Aa(t){return O(t,v([96],39))}s(Aa,"brightCyan");w.brightCyan=Aa;function La(t){return O(t,v([97],39))}s(La,"brightWhite");w.brightWhite=La;function _a(t){return O(t,v([40],49))}s(_a,"bgBlack");w.bgBlack=_a;function ka(t){return O(t,v([41],49))}s(ka,"bgRed");w.bgRed=ka;function Da(t){return O(t,v([42],49))}s(Da,"bgGreen");w.bgGreen=Da;function Ha(t){return O(t,v([43],49))}s(Ha,"bgYellow");w.bgYellow=Ha;function Ua(t){return O(t,v([44],49))}s(Ua,"bgBlue");w.bgBlue=Ua;function Na(t){return O(t,v([45],49))}s(Na,"bgMagenta");w.bgMagenta=Na;function Ma(t){return O(t,v([46],49))}s(Ma,"bgCyan");w.bgCyan=Ma;function Za(t){return O(t,v([47],49))}s(Za,"bgWhite");w.bgWhite=Za;function qa(t){return O(t,v([100],49))}s(qa,"bgBrightBlack");w.bgBrightBlack=qa;function $a(t){return O(t,v([101],49))}s($a,"bgBrightRed");w.bgBrightRed=$a;function Fa(t){return O(t,v([102],49))}s(Fa,"bgBrightGreen");w.bgBrightGreen=Fa;function Ba(t){return O(t,v([103],49))}s(Ba,"bgBrightYellow");w.bgBrightYellow=Ba;function za(t){return O(t,v([104],49))}s(za,"bgBrightBlue");w.bgBrightBlue=za;function ja(t){return O(t,v([105],49))}s(ja,"bgBrightMagenta");w.bgBrightMagenta=ja;function Va(t){return O(t,v([106],49))}s(Va,"bgBrightCyan");w.bgBrightCyan=Va;function Ga(t){return O(t,v([107],49))}s(Ga,"bgBrightWhite");w.bgBrightWhite=Ga;function me(t,e=255,n=0){return Math.trunc(Math.max(Math.min(t,e),n))}s(me,"clampAndTruncate");function Ka(t,e){return O(t,v([38,5,me(e)],39))}s(Ka,"rgb8");w.rgb8=Ka;function Wa(t,e){return O(t,v([48,5,me(e)],49))}s(Wa,"bgRgb8");w.bgRgb8=Wa;function Ja(t,e){return typeof e=="number"?O(t,v([38,2,e>>16&255,e>>8&255,e&255],39)):O(t,v([38,2,me(e.r),me(e.g),me(e.b)],39))}s(Ja,"rgb24");w.rgb24=Ja;function Ya(t,e){return typeof e=="number"?O(t,v([48,2,e>>16&255,e>>8&255,e&255],49)):O(t,v([48,2,me(e.r),me(e.g),me(e.b)],49))}s(Ya,"bgRgb24");w.bgRgb24=Ya;var Qa=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 Xa(t){return t.replace(Qa,"")}s(Xa,"stripColor");w.stripColor=Xa;w.colorFunctions=[go,fo,ho,yo,bo,wo];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 tu(t){let e=Math.abs(eu(t));return w.colorFunctions[e%w.colorFunctions.length]}s(tu,"generateColor");w.generateColor=tu});var Eo=ze(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.format=void 0;function nu(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
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(nu,"format");pt.format=nu});var So=ze(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.inspect=void 0;function Pe(t,e,n,r){let o={seen:[],stylize:ru,showHidden:e??!1,depth:n??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=iu),mt(o,t,o.depth)}s(Pe,"inspect");gt.inspect=Pe;Pe.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]};Pe.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function ru(t,e){return t}s(ru,"stylizeNoColor");function ou(t){return typeof t=="boolean"}s(ou,"isBoolean");function xo(t){return t===void 0}s(xo,"isUndefined");function iu(t,e){let n=Pe.styles[e];return n?"\x1B["+Pe.colors[n][0]+"m"+t+"\x1B["+Pe.colors[n][1]+"m":t}s(iu,"stylizeWithColor");function Nn(t){return typeof t=="function"}s(Nn,"isFunction");function vo(t){return typeof t=="string"}s(vo,"isString");function su(t){return typeof t=="number"}s(su,"isNumber");function Oo(t){return t===null}s(Oo,"isNull");function To(t,e){return Object.prototype.hasOwnProperty.call(t,e)}s(To,"hasOwn");function Mn(t){return Fn(t)&&Bn(t)==="[object RegExp]"}s(Mn,"isRegExp");function Fn(t){return typeof t=="object"&&t!==null}s(Fn,"isObject");function Zn(t){return Fn(t)&&(Bn(t)==="[object Error]"||t instanceof Error)}s(Zn,"isError");function Io(t){return Fn(t)&&Bn(t)==="[object Date]"}s(Io,"isDate");function Bn(t){return Object.prototype.toString.call(t)}s(Bn,"objectToString");function au(t){let e={};return t.forEach(function(n,r){e[n]=!0}),e}s(au,"arrayToHash");function uu(t,e,n,r,o){let i=[];for(let a=0,u=e.length;a<u;++a)To(e,String(a))?i.push($n(t,e,n,r,String(a),!0)):i.push("");return o.forEach(function(a){a.match(/^\d+$/)||i.push($n(t,e,n,r,a,!0))}),i}s(uu,"formatArray");function qn(t){return"["+Error.prototype.toString.call(t)+"]"}s(qn,"formatError");function mt(t,e,n){if(t.customInspect&&e&&Nn(e.inspect)&&e.inspect!==Pe&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(n,t);return vo(d)||(d=mt(t,d,n)),d}let r=cu(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(Zn(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return qn(e);if(o.length===0){if(Nn(e)){let d=e.name?": "+e.name:"";return t.stylize("[Function"+d+"]","special")}if(Mn(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(Io(e))return t.stylize(Date.prototype.toString.call(e),"date");if(Zn(e))return qn(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),Nn(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),Mn(e)&&(a=" "+RegExp.prototype.toString.call(e)),Io(e)&&(a=" "+Date.prototype.toUTCString.call(e)),Zn(e)&&(a=" "+qn(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(n<0)return Mn(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special");t.seen.push(e);let l;return u?l=uu(t,e,n,i,o):l=o.map(function(d){return $n(t,e,n,i,d,u)}),t.seen.pop(),lu(l,a,c)}s(mt,"formatValue");function $n(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")),To(r,o)||(a="["+o+"]"),u||(t.seen.indexOf(c.value)<0?(Oo(n)?u=mt(t,c.value,null):u=mt(t,c.value,n-1),u.indexOf(`
27
27
  `)>-1&&(i?u=u.split(`
28
28
  `).map(function(l){return" "+l}).join(`
@@ -32,7 +32,7 @@
32
32
  `))):u=t.stylize("[Circular]","special")),xo(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($n,"formatProperty");function cu(t,e){if(xo(e))return t.stylize("undefined","undefined");if(vo(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(ou(e))return t.stylize(""+e,"boolean");if(Oo(e))return t.stylize("null","null")}s(cu,"formatPrimitive");function lu(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(lu,"reduceToSingleString")});var Co=ze(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.format=void 0;var du=Eo(),pu=So(),mu=s((t,...e)=>(0,du.format)(pu.inspect,t,e),"format");ft.format=mu});var Ee=ze(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.debug=ge.withoutEnv=ge.Debugger=void 0;var gu=Po(),fu=Co(),ht=class{static{s(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,n){this.manager=e,this.ns=n,this.color=(0,gu.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,fu.format)(n,...e);let i=`${this.color(this.ns)} ${n} ${this.color(`+${o}ms`)}`;console.log(i),this.last=Date.now()}};ge.Debugger=ht;var yt=class{static{s(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function Ao(t){return!t||t.length===0?[]:(t=t.replace(/\s/g,"").replace(/\*/g,".+"),t.split(",").map(e=>new RegExp(`^${e}$`)))}s(Ao,"extract");var Ve;function hu(t){t||(t=[]),typeof t=="string"&&(t=Ao(t)),Ve=new yt(t)}s(hu,"withoutEnv");ge.withoutEnv=hu;function yu(t){let e=globalThis.DEBUG;Ve||(Ve=new yt(Ao(e)));let n=new ht(Ve,t);return Ve.debuggers.set(t,n),Object.assign(n.log.bind(n),{self:n})}s(yu,"debug");ge.debug=yu});var Pl={};la(Pl,{API_KEY:()=>ni,AWSLoggingPlugin:()=>Yt,AmberfloMeteringInboundPolicy:()=>Vi,AmberfloMeteringPolicy:()=>on,ApiAuthKeyInboundPolicy:()=>Wi,ApiKeyInboundPolicy:()=>an,AuditLogDataStaxProvider:()=>en,AuditLogPlugin:()=>tn,Auth0JwtInboundPolicy:()=>Ji,AwsLambdaHandlerExtensions:()=>Ai,BasicAuthInboundPolicy:()=>Yi,BasicRateLimitInboundPolicy:()=>Br,CachingInboundPolicy:()=>Qi,ChangeMethodInboundPolicy:()=>Xi,ClearHeadersInboundPolicy:()=>es,ClearHeadersOutboundPolicy:()=>ts,ClerkJwtInboundPolicy:()=>ns,CognitoJwtInboundPolicy:()=>rs,CompositeInboundPolicy:()=>os,ConfigurationError:()=>g,ContentTypes:()=>Rt,ContextData:()=>de,CreditsMeteringInboundPolicy:()=>is,CryptoBeta:()=>yn,CurityPhantomTokenInboundPolicy:()=>ss,DataDogLoggingPlugin:()=>Nt,DataDogMetricsPlugin:()=>Qt,DynaTraceLoggingPlugin:()=>Gt,DynatraceMetricsPlugin:()=>Xt,FirebaseJwtInboundPolicy:()=>as,FormDataToJsonInboundPolicy:()=>us,GeoFilterInboundPolicy:()=>cs,GoogleCloudLoggingPlugin:()=>Dt,Handler:()=>jt,HttpProblems:()=>R,HttpStatusCode:()=>It,JWTScopeValidationInboundPolicy:()=>ls,KeyValueStore:()=>wn,LoadSubscriptionInboundPolicy:()=>ra,LokiLoggingPlugin:()=>Kt,LookupResult:()=>_e,MemoryZoneReadThroughCache:()=>M,MeteringInboundPolicy:()=>na,MockApiInboundPolicy:()=>ps,MoesifInboundPolicy:()=>bs,OktaJwtInboundPolicy:()=>ws,OpenIdJwtInboundPolicy:()=>F,ProblemResponseFormatter:()=>fe,PropelAuthJwtInboundPolicy:()=>Ps,RateLimitInboundPolicy:()=>Br,ReadmeMetricsInboundPolicy:()=>Os,RemoveHeadersInboundPolicy:()=>Ts,RemoveHeadersOutboundPolicy:()=>Ss,RemoveQueryParamsInboundPolicy:()=>Cs,ReplaceStringOutboundPolicy:()=>As,RequestSizeLimitInboundPolicy:()=>_s,RequestValidationInboundPolicy:()=>Vr,RequireOriginInboundPolicy:()=>qs,ResponseSendingEvent:()=>Ce,ResponseSentEvent:()=>Ae,Router:()=>ke,SYSTEM_LOGGER:()=>Xe,SchemaBasedRequestValidation:()=>Zs,ServiceProviderImpl:()=>fn,SetBodyInboundPolicy:()=>$s,SetHeadersInboundPolicy:()=>Fs,SetHeadersOutboundPolicy:()=>Bs,SetQueryParamsInboundPolicy:()=>zs,SetStatusOutboundPolicy:()=>js,SleepInboundPolicy:()=>Vs,StripeMeteringPlugin:()=>Hr,StripeWebhookVerificationInboundPolicy:()=>nn,SumoLogicLoggingPlugin:()=>Wt,SupabaseJwtInboundPolicy:()=>Gs,SystemLogMap:()=>T,SystemRouteName:()=>oe,UpstreamAzureAdServiceAuthInboundPolicy:()=>Ks,UpstreamFirebaseAdminAuthInboundPolicy:()=>Js,UpstreamFirebaseUserAuthInboundPolicy:()=>Ys,UpstreamGcpJwtInboundPolicy:()=>Qs,UpstreamGcpServiceAuthInboundPolicy:()=>ea,VMWareLogInsightLoggingPlugin:()=>Jt,ValidateJsonSchemaInbound:()=>ta,ZoneCache:()=>pe,ZuploRequest:()=>_,awsLambdaHandler:()=>Li,environment:()=>Z,getIdForParameterSchema:()=>mn,getIdForRefSchema:()=>Ds,getIdForRequestBodySchema:()=>gn,getRawOperationDataIdentifierName:()=>ks,httpStatuses:()=>xt,isRestrictedEnvVariableName:()=>dr,isZuploReadableEnvVariableName:()=>pr,openApiSpecHandler:()=>_i,originalFetch:()=>De,purgeGatewayCache:()=>wi,redirectHandler:()=>ki,sanitizedIdentifierName:()=>Re,serialize:()=>Pt,setMoesifContext:()=>ys,urlForwardHandler:()=>Di,urlRewriteHandler:()=>Hi,webSocketHandler:()=>Ui,webSocketPipelineHandler:()=>Zi});module.exports=da(Pl);var L=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"}},g=class extends P{static{s(this,"ConfigurationError")}constructor(e,n){super(e,n),this.name="ConfigurationError"}},lt=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 L("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 dt=globalThis,eo=dt.caches;if(eo){let t=eo.open;dt.caches.open=function(e){let n=h.instance.deploymentName??h.instance.build.BUILD_ID;return t.call(this,`${n}-${e}`)},delete dt.caches.default,Object.freeze(dt.caches)}var to=new Map,Pn=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)})}},Te=class{static{s(this,"MemoryCache")}constructor(e,n={maxSize:1e3}){this.name=e;let r=to.get(e);r||(r=new Pn(n),to.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 En="__zuplo-expiry-header",pe=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(En);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(En,`${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(En,`${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 Te(r),this.#n=new pe(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};this.#n.put(e,o,r).catch(i=>{"logger"in this.#r?this.#r.logger?.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,i):"log"in this.#r&&this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,i)})}};var no="zuplo-request-id",je="zp-rid",ro="zp-body-removed",Se="cf-ray",In="cf-ipcity",xn="cf-ipcontinent",vn="cf-ipcountry",On="cf-iplongitude",Tn="cf-iplatitude",oo="zp-ipcity",io="zp-ipcontinent",so="zp-ipcountry",ao="zp-iplongitude",uo="zp-iplatitude",co="true-client-ip",Sn="zp-asn",Cn="zp-asorg",An="zp-colo",Ln="zp-postalcode",_n="zp-metrocode",kn="zp-region",Dn="zp-regioncode",Hn="zp-timezone",lo=[In,xn,vn,On,Tn,Sn,Cn,An,Ln,_n,kn,Dn,Hn],po=["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"];var li=Oe(Ee());var Ge=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})}})}},fe=class{static{s(this,"ProblemResponseFormatter")}static async format(e,n,r){return await Ge.problemResponseFormat(e,n,r)}};function bt(t){for(let e in t){let n=t[e];n&&typeof n=="object"&&bt(n)}return Object.freeze(t)}s(bt,"deepFreeze");var _=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 bt(this.#e)}get params(){return bt(this.#t)}user};var Ie=class{static{s(this,"RuntimePlugin")}},ue=class extends Ie{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,n){}},Ke={},he=[],Lo=[],_o=[],ko=[];var wt={addPlugin(t){he.push(t)},addRequestHook(t){Lo.push(t)},addResponseSendingHook(t){_o.push(t)},addResponseSendingFinalHook(t){ko.push(t)}},Do=s(async(t,e)=>{let n=t;for(let r of Lo){let o=await r(n,e);if(o instanceof _)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"),Ho=s(async(t,e,n)=>{let r=t;for(let o of _o){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"),Uo=s(async(t,e,n)=>{for(let r of ko)await r(t,e,n)},"invokeOnResponseSendingFinalExtensions");async function No(t=()=>Promise.resolve()){await t(wt),Ke.value=wt;for(let e of he)e instanceof ue&&await e.initialize(wt);Ge.setProblemResponseFormat(wt.problemResponseFormat)}s(No,"initializeRuntime");var Rt={Json:"application/json",Form:"application/x-www-form-urlencoded"};function Pt(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(Rt.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(Rt.Json)||!e?JSON.stringify(t):t}s(Pt,"serialize");var H=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 y=>{let I=a.pop();return I?I(o,i,n,u):await this.#e(async x=>{let C=await r(x,i);return bu(C)},n)(y,i)},"nextPipe"),l=await u(o),d=new Ce(o,l);i.dispatchEvent(d);let p=z.getContextExtensions(i),w=p.latestRequest,m;try{m=await d.mutableResponse}catch(y){return i.log.error(y),n.errorHandler(o,i,y)}try{m=await p.onResponseSending(m,w,i)}catch(y){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${y.message}'`,y),n.errorHandler(o,i,y)}try{m=await Ho(m,w,i)}catch(y){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${y.message}'`,y),n.errorHandler(o,i,y)}i.dispatchEvent(new Ae(o,m));try{await p.onResponseSendingFinal(l,w,i)}catch(y){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${y.message}'`,y),y}try{await Uo(l,w,i)}catch(y){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${y.message}'`,y),y}return m}};function bu(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response(Pt(t),{headers:{"content-type":"application/json"}})}s(bu,"resultToResponse");var ye=class extends Ie{static{s(this,"MetricsPlugin")}};var T=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 L(r)}return n}static addLogger(e,n){t.#e.set(e,n)}};var S=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 Et=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=h.instance.loggingId,this.#e=e,this.#t=new S("ellie-metrics-transport",10,this.dispatchFunction,T.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();T.getLogger(this.#e).error(`Metrics POST responded ${u.status}: ${u.statusText}`,c)}}}};var D=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=We.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},We={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(Se)??void 0,c=t.headers.get(co)??void 0,l=e.incomingRequestProperties,d;e.route instanceof D&&(d=e.route.systemRouteName);let p=z.getContextExtensions(e).latestRequest,w={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 Et(e)),he.forEach(y=>{if(y instanceof ye){let I=y.getTransport();m.push(I)}}),m.forEach(y=>{y.pushMetrics(w,e)}),a},"metricsProcessor");var oe=(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))(oe||{});var zn=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"&&T.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new H({processors:[j],handler:n,gateway:e}),o=new D({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});t.addRoute(o,r.execute)},"registerBuildRoute");var It=(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))(It||{}),Mo={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 wu={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"},xt=wu;function Ru(t){return`${new URL(t.url).pathname}`}s(Ru,"instance");function Pu(t,e){let n={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:h.instance.build.BUILD_ID},r=t.headers.get(Se);return r&&(n.rayId=r),n}s(Pu,"trace");var Eu=s((t,e,n,r,o)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:Ru(e),trace:Pu(e,n),...r},additionalHeaders:o,statusText:xt[t.status]}),"merge"),jn=class{static{s(this,"HttpProblemsBase")}static format=(e,n,r)=>"problem"in e?fe.format(e,n,r):fe.format({problem:e},n,r);static getProblemFromStatus(e,n){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:Mo[e],...n}}},R=class extends jn{static{s(this,"HttpProblems")}static#e(e,n,r,o,i){let a=Eu(this.getProblemFromStatus(e),n,r,o,i);return fe.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:Iu}=Object.prototype,{propertyIsEnumerable:xu}=Object.prototype;function Vn(t){return Iu.call(t)}s(Vn,"toString");function Q(t){return typeof t=="string"}s(Q,"isString");function vt(t){return Q(t)&&t!==""}s(vt,"isNonEmptyString");function Zo(t){return Vn(t)==="[object RegExp]"}s(Zo,"isRegexp");function qo(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>xu.call(t,e))]}s(qo,"getOwnEnumerableKeys");function Je(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof RegExp)&&!(t instanceof Date)}s(Je,"isObject");function Gn(t){return typeof t=="number"&&!isNaN(t)}s(Gn,"isNumber");function Kn(t){return t===!0||t===!1}s(Kn,"isBoolean");function $o(t){return typeof t>"u"}s($o,"isUndefined");function Fo(t){return $o(t)||t===null}s(Fo,"isUndefinedOrNull");function Ye(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}s(Ye,"isErrorLike");var Bo=new Map;function zo(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=Bo.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 Bo.set(t,r),r}s(zo,"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 P(`Error applying ${n} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(xe,"getValueFromRequestUser");function Wn(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(Q(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(Wn,"parseValueToStringArray");function jo(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(!Je(n))throw new g(`Invalid custom cors policy is set. Expected an object, received '${typeof n}'`);if(!vt(n.name))throw new g("Value of 'name' on custom cors policies must be a non-empty string.");if(n.maxAge!==void 0&&!Gn(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&&!Kn(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=Jn(n,"allowedHeaders"),o=Jn(n,"allowedMethods"),i=Jn(n,"exposeHeaders"),a;try{a=Wn(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(jo,"parseCorsPolicies");function Jn(t,e){let n;if(t[e]!==void 0)try{n=Wn(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(Jn,"parseOptionalProperty");var Ot=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"),Tt=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 Yn=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 w=t.lookup(l,c);if(!w)return R.notFound(a,u);let m=w.routeConfiguration,y=vu(l,d,p,m,n);return y.isValid?new Response(void 0,{status:200,statusText:"OK",headers:y.headers}):(y.error&&u.log.warn(y.error),R.notFound(a,u))},"optionsHandler"),o=new H({processors:[j],handler:r,gateway:e}),i=new D({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});t.addRoute(i,o.execute)},"registerCorsRoute"),vu=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=Ot(a.allowedOrigins,n);return u?{isValid:!0,headers:Tt(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${n}'`}},"validateAndBuildResponseHeaders");var Vo=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 H({processors:[j],handler:n,gateway:e}),o=new D({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 Qn=new D({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Go=s((t,e)=>{let n=s(async(o,i)=>{let a=Ke.value?.notFoundHandler;if(a){let u=z.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return R.notFound(o,i)},"notFoundHandler"),r=new H({processors:[j],handler:n,gateway:e});t.addRoute(Qn,r.execute)},"registerNotMatchedHandler");var Ou=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Ko=s(t=>{Ou.forEach(e=>t.delete(e))},"stripCorsHeaders"),St=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 Ko(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 L(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=Tu(o,n.routeData.corsPolicies),u=Su(t,a),c=new Headers(i.headers);return Ko(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"),Tu=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"),Su=s((t,e)=>{let n=Ot(e.allowedOrigins,t.headers.get("origin"));return n?Tt(e,n):{}},"getCorsHeaders");var Xn=s((t,e)=>{let n=s(async()=>new Response(null,{status:200}),"pingRouteHandler"),r=new H({processors:[St],handler:n,gateway:e}),o=new D({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});t.addRoute(o,r.execute)},"registerPingRoute");function Qe(t,e){let n,r;return Array.isArray(t)?n=t:(n=t.policies?.inbound??[],r=t.path),n.map(i=>{let a=e?.find(c=>c.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).`);let u;if(typeof a.handler?.module=="object"&&(u=a.handler?.module[a.handler.export]),typeof u!="function")throw new g(`Invalid state - invalid handler on policy '${i}' ${r&&`on route '${r}'`}. Expected a function, received '${typeof u}'`);return{exportName:a.handler.export,handler:u,options:a.handler.options,policyName:a.name}})}s(Qe,"getInboundPolicyHandlerAndOptions");function Cu(t,e){return(t.policies?.outbound??[]).map(o=>{let i=e?.find(u=>u.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).`);let a;if(typeof i.handler?.module=="object"&&(a=i.handler?.module[i.handler.export]),typeof a!="function")throw new g(`Invalid state - invalid handler on policy '${o}' on route '${t.path}'`);return{exportName:i.handler.export,handler:a,options:i.handler.options,policyName:i.name}})}s(Cu,"getOutboundPolicyHandlerAndOptions");var er=s(t=>async(e,n)=>{let r=z.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,a.options,a.policyName);if(u instanceof _)i=u;else if(u instanceof Request)i=new _(u);else{if(u instanceof Response)return u;throw new g(`Invalid state - invalid handler on policy '${a.policyName}'${a.routeName?` on route '${a.routeName}`:""}. The result of an inbound policy must be a Response or Request.`)}r.latestRequest=i}return i},"toStackedInboundHandler"),Au=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,a.options,a.policyName);if(!(u instanceof Response))throw new g(`Invalid state - invalid handler on policy '${a.policyName}'${a.routeName?` on route '${a.routeName}`:""}. The result of an outbound policy must be a Response.`);i=u}return i},"toStackedOutboundHandler"),Ct=s(async(t,e,n,r)=>{let o=Qe(e.route,n.routeData.policies),i=Cu(e.route,n.routeData.policies);return Jo({request:t,context:e,inboundPolicies:o,outboundPolicies:i,gateway:n,next:r})},"policyProcessor");function Wo({inboundPolicies:t=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>Jo({request:r,context:o,inboundPolicies:t.map(u=>({...u,exportName:"default",policyName:u.handler.name})),outboundPolicies:e.map(u=>({...u,exportName:"default",policyName:u.handler.name})),gateway:i,next:a}),"policyProcessor")}s(Wo,"createInternalPolicyProcessor");async function Jo({request:t,context:e,inboundPolicies:n,outboundPolicies:r,gateway:o,next:i}){let a=er(n);try{let u=await a(t,e);if(u instanceof Response)return u;let c=await i(u),l=Au(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(Jo,"executePolicyProcessor");function Yo(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");let n={},o=(e||{}).decode||Lu,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]=_u(l,o)}i=u+1}return n}s(Yo,"parse");function Lu(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}s(Lu,"decode");function _u(t,e){try{return e(t)}catch{return t}}s(_u,"tryDecode");function Qo(t,e){try{let n=/v\d+(-\d+)?/g,o=Yo(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&n.test(o)?`https://dev-portal-${o}.zuplo.com`:t}catch{}return t}s(Qo,"devPortalBaseURL");var Xo="/__zuplo/dev-portal",ku="dev-portal-id",Du="dev-portal-host",Hu="zp-account",Uu="zp-project",Nu="dev-portal-build",Mu=`
35
+ `)+" "+n[1]:n[0]+e+" "+t.join(", ")+" "+n[1]}s(lu,"reduceToSingleString")});var Co=ze(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.format=void 0;var du=Eo(),pu=So(),mu=s((t,...e)=>(0,du.format)(pu.inspect,t,e),"format");ft.format=mu});var Ee=ze(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.debug=ge.withoutEnv=ge.Debugger=void 0;var gu=Po(),fu=Co(),ht=class{static{s(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,n){this.manager=e,this.ns=n,this.color=(0,gu.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,fu.format)(n,...e);let i=`${this.color(this.ns)} ${n} ${this.color(`+${o}ms`)}`;console.log(i),this.last=Date.now()}};ge.Debugger=ht;var yt=class{static{s(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function Ao(t){return!t||t.length===0?[]:(t=t.replace(/\s/g,"").replace(/\*/g,".+"),t.split(",").map(e=>new RegExp(`^${e}$`)))}s(Ao,"extract");var Ve;function hu(t){t||(t=[]),typeof t=="string"&&(t=Ao(t)),Ve=new yt(t)}s(hu,"withoutEnv");ge.withoutEnv=hu;function yu(t){let e=globalThis.DEBUG;Ve||(Ve=new yt(Ao(e)));let n=new ht(Ve,t);return Ve.debuggers.set(t,n),Object.assign(n.log.bind(n),{self:n})}s(yu,"debug");ge.debug=yu});var Pl={};la(Pl,{API_KEY:()=>ni,AWSLoggingPlugin:()=>Yt,AmberfloMeteringInboundPolicy:()=>Vi,AmberfloMeteringPolicy:()=>on,ApiAuthKeyInboundPolicy:()=>Wi,ApiKeyInboundPolicy:()=>an,AuditLogDataStaxProvider:()=>en,AuditLogPlugin:()=>tn,Auth0JwtInboundPolicy:()=>Ji,AwsLambdaHandlerExtensions:()=>Ai,BasicAuthInboundPolicy:()=>Yi,BasicRateLimitInboundPolicy:()=>Br,CachingInboundPolicy:()=>Qi,ChangeMethodInboundPolicy:()=>Xi,ClearHeadersInboundPolicy:()=>es,ClearHeadersOutboundPolicy:()=>ts,ClerkJwtInboundPolicy:()=>ns,CognitoJwtInboundPolicy:()=>rs,CompositeInboundPolicy:()=>os,ConfigurationError:()=>g,ContentTypes:()=>Rt,ContextData:()=>de,CreditsMeteringInboundPolicy:()=>is,CryptoBeta:()=>yn,CurityPhantomTokenInboundPolicy:()=>ss,DataDogLoggingPlugin:()=>Nt,DataDogMetricsPlugin:()=>Qt,DynaTraceLoggingPlugin:()=>Gt,DynatraceMetricsPlugin:()=>Xt,FirebaseJwtInboundPolicy:()=>as,FormDataToJsonInboundPolicy:()=>us,GeoFilterInboundPolicy:()=>cs,GoogleCloudLoggingPlugin:()=>Dt,Handler:()=>jt,HttpProblems:()=>R,HttpStatusCode:()=>It,JWTScopeValidationInboundPolicy:()=>ls,KeyValueStore:()=>wn,LoadSubscriptionInboundPolicy:()=>ra,LokiLoggingPlugin:()=>Kt,LookupResult:()=>_e,MemoryZoneReadThroughCache:()=>M,MeteringInboundPolicy:()=>na,MockApiInboundPolicy:()=>ps,MoesifInboundPolicy:()=>bs,OktaJwtInboundPolicy:()=>ws,OpenIdJwtInboundPolicy:()=>F,ProblemResponseFormatter:()=>fe,PropelAuthJwtInboundPolicy:()=>Ps,RateLimitInboundPolicy:()=>Br,ReadmeMetricsInboundPolicy:()=>Os,RemoveHeadersInboundPolicy:()=>Ts,RemoveHeadersOutboundPolicy:()=>Ss,RemoveQueryParamsInboundPolicy:()=>Cs,ReplaceStringOutboundPolicy:()=>As,RequestSizeLimitInboundPolicy:()=>_s,RequestValidationInboundPolicy:()=>Vr,RequireOriginInboundPolicy:()=>qs,ResponseSendingEvent:()=>Ce,ResponseSentEvent:()=>Ae,Router:()=>ke,SYSTEM_LOGGER:()=>Xe,SchemaBasedRequestValidation:()=>Zs,ServiceProviderImpl:()=>fn,SetBodyInboundPolicy:()=>$s,SetHeadersInboundPolicy:()=>Fs,SetHeadersOutboundPolicy:()=>Bs,SetQueryParamsInboundPolicy:()=>zs,SetStatusOutboundPolicy:()=>js,SleepInboundPolicy:()=>Vs,StripeMeteringPlugin:()=>Hr,StripeWebhookVerificationInboundPolicy:()=>nn,SumoLogicLoggingPlugin:()=>Wt,SupabaseJwtInboundPolicy:()=>Gs,SystemLogMap:()=>T,SystemRouteName:()=>oe,UpstreamAzureAdServiceAuthInboundPolicy:()=>Ks,UpstreamFirebaseAdminAuthInboundPolicy:()=>Js,UpstreamFirebaseUserAuthInboundPolicy:()=>Ys,UpstreamGcpJwtInboundPolicy:()=>Qs,UpstreamGcpServiceAuthInboundPolicy:()=>ea,VMWareLogInsightLoggingPlugin:()=>Jt,ValidateJsonSchemaInbound:()=>ta,ZoneCache:()=>pe,ZuploRequest:()=>_,awsLambdaHandler:()=>Li,environment:()=>Z,getIdForParameterSchema:()=>mn,getIdForRefSchema:()=>Ds,getIdForRequestBodySchema:()=>gn,getRawOperationDataIdentifierName:()=>ks,httpStatuses:()=>xt,isRestrictedEnvVariableName:()=>dr,isZuploReadableEnvVariableName:()=>pr,openApiSpecHandler:()=>_i,originalFetch:()=>De,purgeGatewayCache:()=>wi,redirectHandler:()=>ki,sanitizedIdentifierName:()=>Re,serialize:()=>Pt,setMoesifContext:()=>ys,urlForwardHandler:()=>Di,urlRewriteHandler:()=>Hi,webSocketHandler:()=>Ui,webSocketPipelineHandler:()=>Zi});module.exports=da(Pl);var L=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"}},g=class extends P{static{s(this,"ConfigurationError")}constructor(e,n){super(e,n),this.name="ConfigurationError"}},lt=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 L("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 dt=globalThis,eo=dt.caches;if(eo){let t=eo.open;dt.caches.open=function(e){let n=h.instance.deploymentName??h.instance.build.BUILD_ID;return t.call(this,`${n}-${e}`)},delete dt.caches.default,Object.freeze(dt.caches)}var to=new Map,Pn=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)})}},Te=class{static{s(this,"MemoryCache")}constructor(e,n={maxSize:1e3}){this.name=e;let r=to.get(e);r||(r=new Pn(n),to.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 En="__zuplo-expiry-header",pe=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(En);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(En,`${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(En,`${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 Te(r),this.#n=new pe(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};this.#n.put(e,o,r).catch(i=>{"logger"in this.#r?this.#r.logger?.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,i):"log"in this.#r&&this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,i)})}};var no="zuplo-request-id",je="zp-rid",ro="zp-body-removed",Se="cf-ray",In="cf-ipcity",xn="cf-ipcontinent",vn="cf-ipcountry",On="cf-iplongitude",Tn="cf-iplatitude",oo="zp-ipcity",io="zp-ipcontinent",so="zp-ipcountry",ao="zp-iplongitude",uo="zp-iplatitude",co="true-client-ip",Sn="zp-asn",Cn="zp-asorg",An="zp-colo",Ln="zp-postalcode",_n="zp-metrocode",kn="zp-region",Dn="zp-regioncode",Hn="zp-timezone",lo=[In,xn,vn,On,Tn,Sn,Cn,An,Ln,_n,kn,Dn,Hn],po=["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"];var li=Oe(Ee());var Ge=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})}})}},fe=class{static{s(this,"ProblemResponseFormatter")}static async format(e,n,r){return await Ge.problemResponseFormat(e,n,r)}};function bt(t){for(let e in t){let n=t[e];n&&typeof n=="object"&&bt(n)}return Object.freeze(t)}s(bt,"deepFreeze");var _=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 bt(this.#e)}get params(){return bt(this.#t)}user};var Ie=class{static{s(this,"RuntimePlugin")}},ue=class extends Ie{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,n){}},Ke={},he=[],Lo=[],_o=[],ko=[];var wt={addPlugin(t){he.push(t)},addRequestHook(t){Lo.push(t)},addResponseSendingHook(t){_o.push(t)},addResponseSendingFinalHook(t){ko.push(t)}},Do=s(async(t,e)=>{let n=t;for(let r of Lo){let o=await r(n,e);if(o instanceof _)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"),Ho=s(async(t,e,n)=>{let r=t;for(let o of _o){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"),Uo=s(async(t,e,n)=>{for(let r of ko)await r(t,e,n)},"invokeOnResponseSendingFinalExtensions");async function No(t=()=>Promise.resolve()){await t(wt),Ke.value=wt;for(let e of he)e instanceof ue&&await e.initialize(wt);Ge.setProblemResponseFormat(wt.problemResponseFormat)}s(No,"initializeRuntime");var Rt={Json:"application/json",Form:"application/x-www-form-urlencoded"};function Pt(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(Rt.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(Rt.Json)||!e?JSON.stringify(t):t}s(Pt,"serialize");var H=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 y=>{let I=a.pop();return I?I(o,i,n,u):await this.#e(async x=>{let C=await r(x,i);return bu(C)},n)(y,i)},"nextPipe"),l=await u(o),d=new Ce(o,l);i.dispatchEvent(d);let p=z.getContextExtensions(i),b=p.latestRequest,m;try{m=await d.mutableResponse}catch(y){return i.log.error(y),n.errorHandler(o,i,y)}try{m=await p.onResponseSending(m,b,i)}catch(y){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${y.message}'`,y),n.errorHandler(o,i,y)}try{m=await Ho(m,b,i)}catch(y){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${y.message}'`,y),n.errorHandler(o,i,y)}i.dispatchEvent(new Ae(o,m));try{await p.onResponseSendingFinal(l,b,i)}catch(y){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${y.message}'`,y),y}try{await Uo(l,b,i)}catch(y){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${y.message}'`,y),y}return m}};function bu(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response(Pt(t),{headers:{"content-type":"application/json"}})}s(bu,"resultToResponse");var ye=class extends Ie{static{s(this,"MetricsPlugin")}};var T=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 L(r)}return n}static addLogger(e,n){t.#e.set(e,n)}};var S=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 Et=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=h.instance.loggingId,this.#e=e,this.#t=new S("ellie-metrics-transport",10,this.dispatchFunction,T.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();T.getLogger(this.#e).error(`Metrics POST responded ${u.status}: ${u.statusText}`,c)}}}};var D=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=We.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},We={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(Se)??void 0,c=t.headers.get(co)??void 0,l=e.incomingRequestProperties,d;e.route instanceof D&&(d=e.route.systemRouteName);let p=z.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},m=[];return m.push(new Et(e)),he.forEach(y=>{if(y instanceof ye){let I=y.getTransport();m.push(I)}}),m.forEach(y=>{y.pushMetrics(b,e)}),a},"metricsProcessor");var oe=(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))(oe||{});var zn=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"&&T.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new H({processors:[j],handler:n,gateway:e}),o=new D({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});t.addRoute(o,r.execute)},"registerBuildRoute");var It=(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))(It||{}),Mo={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 wu={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"},xt=wu;function Ru(t){return`${new URL(t.url).pathname}`}s(Ru,"instance");function Pu(t,e){let n={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:h.instance.build.BUILD_ID},r=t.headers.get(Se);return r&&(n.rayId=r),n}s(Pu,"trace");var Eu=s((t,e,n,r,o)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:Ru(e),trace:Pu(e,n),...r},additionalHeaders:o,statusText:xt[t.status]}),"merge"),jn=class{static{s(this,"HttpProblemsBase")}static format=(e,n,r)=>"problem"in e?fe.format(e,n,r):fe.format({problem:e},n,r);static getProblemFromStatus(e,n){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:Mo[e],...n}}},R=class extends jn{static{s(this,"HttpProblems")}static#e(e,n,r,o,i){let a=Eu(this.getProblemFromStatus(e),n,r,o,i);return fe.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:Iu}=Object.prototype,{propertyIsEnumerable:xu}=Object.prototype;function Vn(t){return Iu.call(t)}s(Vn,"toString");function Q(t){return typeof t=="string"}s(Q,"isString");function vt(t){return Q(t)&&t!==""}s(vt,"isNonEmptyString");function Zo(t){return Vn(t)==="[object RegExp]"}s(Zo,"isRegexp");function qo(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>xu.call(t,e))]}s(qo,"getOwnEnumerableKeys");function Je(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof RegExp)&&!(t instanceof Date)}s(Je,"isObject");function Gn(t){return typeof t=="number"&&!isNaN(t)}s(Gn,"isNumber");function Kn(t){return t===!0||t===!1}s(Kn,"isBoolean");function $o(t){return typeof t>"u"}s($o,"isUndefined");function Fo(t){return $o(t)||t===null}s(Fo,"isUndefinedOrNull");function Ye(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}s(Ye,"isErrorLike");var Bo=new Map;function zo(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=Bo.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 Bo.set(t,r),r}s(zo,"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 P(`Error applying ${n} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(xe,"getValueFromRequestUser");function Wn(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(Q(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(Wn,"parseValueToStringArray");function jo(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(!Je(n))throw new g(`Invalid custom cors policy is set. Expected an object, received '${typeof n}'`);if(!vt(n.name))throw new g("Value of 'name' on custom cors policies must be a non-empty string.");if(n.maxAge!==void 0&&!Gn(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&&!Kn(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=Jn(n,"allowedHeaders"),o=Jn(n,"allowedMethods"),i=Jn(n,"exposeHeaders"),a;try{a=Wn(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(jo,"parseCorsPolicies");function Jn(t,e){let n;if(t[e]!==void 0)try{n=Wn(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(Jn,"parseOptionalProperty");var Ot=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"),Tt=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 Yn=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 m=b.routeConfiguration,y=vu(l,d,p,m,n);return y.isValid?new Response(void 0,{status:200,statusText:"OK",headers:y.headers}):(y.error&&u.log.warn(y.error),R.notFound(a,u))},"optionsHandler"),o=new H({processors:[j],handler:r,gateway:e}),i=new D({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});t.addRoute(i,o.execute)},"registerCorsRoute"),vu=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=Ot(a.allowedOrigins,n);return u?{isValid:!0,headers:Tt(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${n}'`}},"validateAndBuildResponseHeaders");var Vo=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 H({processors:[j],handler:n,gateway:e}),o=new D({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 Qn=new D({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Go=s((t,e)=>{let n=s(async(o,i)=>{let a=Ke.value?.notFoundHandler;if(a){let u=z.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return R.notFound(o,i)},"notFoundHandler"),r=new H({processors:[j],handler:n,gateway:e});t.addRoute(Qn,r.execute)},"registerNotMatchedHandler");var Ou=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Ko=s(t=>{Ou.forEach(e=>t.delete(e))},"stripCorsHeaders"),St=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 Ko(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 L(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=Tu(o,n.routeData.corsPolicies),u=Su(t,a),c=new Headers(i.headers);return Ko(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"),Tu=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"),Su=s((t,e)=>{let n=Ot(e.allowedOrigins,t.headers.get("origin"));return n?Tt(e,n):{}},"getCorsHeaders");var Xn=s((t,e)=>{let n=s(async()=>new Response(null,{status:200}),"pingRouteHandler"),r=new H({processors:[St],handler:n,gateway:e}),o=new D({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});t.addRoute(o,r.execute)},"registerPingRoute");function Qe(t,e){let n,r;return Array.isArray(t)?n=t:(n=t.policies?.inbound??[],r=t.path),n.map(i=>{let a=e?.find(c=>c.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).`);let u;if(typeof a.handler?.module=="object"&&(u=a.handler?.module[a.handler.export]),typeof u!="function")throw new g(`Invalid state - invalid handler on policy '${i}' ${r&&`on route '${r}'`}. Expected a function, received '${typeof u}'`);return{exportName:a.handler.export,handler:u,options:a.handler.options,policyName:a.name}})}s(Qe,"getInboundPolicyHandlerAndOptions");function Cu(t,e){return(t.policies?.outbound??[]).map(o=>{let i=e?.find(u=>u.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).`);let a;if(typeof i.handler?.module=="object"&&(a=i.handler?.module[i.handler.export]),typeof a!="function")throw new g(`Invalid state - invalid handler on policy '${o}' on route '${t.path}'`);return{exportName:i.handler.export,handler:a,options:i.handler.options,policyName:i.name}})}s(Cu,"getOutboundPolicyHandlerAndOptions");var er=s(t=>async(e,n)=>{let r=z.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,a.options,a.policyName);if(u instanceof _)i=u;else if(u instanceof Request)i=new _(u);else{if(u instanceof Response)return u;throw new g(`Invalid state - invalid handler on policy '${a.policyName}'${a.routeName?` on route '${a.routeName}`:""}. The result of an inbound policy must be a Response or Request.`)}r.latestRequest=i}return i},"toStackedInboundHandler"),Au=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,a.options,a.policyName);if(!(u instanceof Response))throw new g(`Invalid state - invalid handler on policy '${a.policyName}'${a.routeName?` on route '${a.routeName}`:""}. The result of an outbound policy must be a Response.`);i=u}return i},"toStackedOutboundHandler"),Ct=s(async(t,e,n,r)=>{let o=Qe(e.route,n.routeData.policies),i=Cu(e.route,n.routeData.policies);return Jo({request:t,context:e,inboundPolicies:o,outboundPolicies:i,gateway:n,next:r})},"policyProcessor");function Wo({inboundPolicies:t=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>Jo({request:r,context:o,inboundPolicies:t.map(u=>({...u,exportName:"default",policyName:u.handler.name})),outboundPolicies:e.map(u=>({...u,exportName:"default",policyName:u.handler.name})),gateway:i,next:a}),"policyProcessor")}s(Wo,"createInternalPolicyProcessor");async function Jo({request:t,context:e,inboundPolicies:n,outboundPolicies:r,gateway:o,next:i}){let a=er(n);try{let u=await a(t,e);if(u instanceof Response)return u;let c=await i(u),l=Au(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(Jo,"executePolicyProcessor");function Yo(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");let n={},o=(e||{}).decode||Lu,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]=_u(l,o)}i=u+1}return n}s(Yo,"parse");function Lu(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}s(Lu,"decode");function _u(t,e){try{return e(t)}catch{return t}}s(_u,"tryDecode");function Qo(t,e){try{let n=/v\d+(-\d+)?/g,o=Yo(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&n.test(o)?`https://dev-portal-${o}.zuplo.com`:t}catch{}return t}s(Qo,"devPortalBaseURL");var Xo="/__zuplo/dev-portal",ku="dev-portal-id",Du="dev-portal-host",Hu="zp-account",Uu="zp-project",Nu="dev-portal-build",Mu=`
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
- `,ei=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(Mu,{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=Qo(o,c.headers),w=new URL(`${d.pathname}${d.search}`,p),{headers:m,method:y,body:I}=c;return h.instance.build.ACCOUNT_NAME&&m.set(Hu,h.instance.build.ACCOUNT_NAME),h.instance.build.PROJECT_NAME&&m.set(Uu,h.instance.build.PROJECT_NAME),m.set(ku,r),m.set(Du,d.host),m.set(Nu,h.instance.build.BUILD_ID),await fetch(w.toString(),{headers:m,method:y,body:I,redirect:"manual"})},"devPortalRoute"),a=new H({processors:[j,Ct],handler:i,gateway:e}),u=new D({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"),ti=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(Xo.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new H({processors:[j],handler:r,gateway:e}),i=new D({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${Xo}(.*)`,systemRouteName:"developer-portal-legacy"});t.addRoute(i,o.execute)},"registerDevPortalLegacyRedirectRoute");var ci=Oe(Ee());var Xe="system-logger",ni="api-key";var tr=0,et=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){tr>=Number.MAX_SAFE_INTEGER&&(tr=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:tr++};this.#t[e](u,a)}};var U=class extends Ie{static{s(this,"LogPlugin")}};var At=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 tt=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 Zu=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(t=>[t.name,t]),qu=new Map(Zu);var $u=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],nr=Symbol(".toJSON was called"),Fu=s(t=>{t[nr]=!0;let e=t.toJSON();return delete t[nr],e},"toJSON"),Bu=s(t=>qu.get(t)??Error,"getErrorConstructor"),ri=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&&Ye(t)){let l=Bu(t.name);n=new l}else n={};if(e.push(t),i>=o)return n;if(a&&typeof t.toJSON=="function"&&t[nr]!==!0)return Fu(t);let c=s(l=>ri({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 $u)typeof t[l]<"u"&&t[l]!==null&&Object.defineProperty(n,l,{value:Ye(t[l])?c(t[l]):t[l],enumerable:r?!0:d,configurable:!0,writable:!0});return n},"destroyCircular");function K(t,e){let n=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof t=="object"&&t!==null?ri({from:t,seen:[],forceEnumerable:!0,maxDepth:n,depth:0,useToJSON:r,serialize:!0}):typeof t=="function"?`[Function: ${t.name??"anonymous"}]`:t}s(K,"serializeError");var zu=/file:\/\/\/(.*?)\/dist\//g,ju=/\(https:\/\/raw\.githubusercontent\.com\/.*?\)/g,Vu="at async Event.respondWith";function oi(t){return typeof t!="string"?t:t.split(`
49
+ `,ei=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(Mu,{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=Qo(o,c.headers),b=new URL(`${d.pathname}${d.search}`,p),{headers:m,method:y,body:I}=c;return h.instance.build.ACCOUNT_NAME&&m.set(Hu,h.instance.build.ACCOUNT_NAME),h.instance.build.PROJECT_NAME&&m.set(Uu,h.instance.build.PROJECT_NAME),m.set(ku,r),m.set(Du,d.host),m.set(Nu,h.instance.build.BUILD_ID),await fetch(b.toString(),{headers:m,method:y,body:I,redirect:"manual"})},"devPortalRoute"),a=new H({processors:[j,Ct],handler:i,gateway:e}),u=new D({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"),ti=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(Xo.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new H({processors:[j],handler:r,gateway:e}),i=new D({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${Xo}(.*)`,systemRouteName:"developer-portal-legacy"});t.addRoute(i,o.execute)},"registerDevPortalLegacyRedirectRoute");var ci=Oe(Ee());var Xe="system-logger",ni="api-key";var tr=0,et=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){tr>=Number.MAX_SAFE_INTEGER&&(tr=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:tr++};this.#t[e](u,a)}};var U=class extends Ie{static{s(this,"LogPlugin")}};var At=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 tt=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 Zu=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(t=>[t.name,t]),qu=new Map(Zu);var $u=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],nr=Symbol(".toJSON was called"),Fu=s(t=>{t[nr]=!0;let e=t.toJSON();return delete t[nr],e},"toJSON"),Bu=s(t=>qu.get(t)??Error,"getErrorConstructor"),ri=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&&Ye(t)){let l=Bu(t.name);n=new l}else n={};if(e.push(t),i>=o)return n;if(a&&typeof t.toJSON=="function"&&t[nr]!==!0)return Fu(t);let c=s(l=>ri({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 $u)typeof t[l]<"u"&&t[l]!==null&&Object.defineProperty(n,l,{value:Ye(t[l])?c(t[l]):t[l],enumerable:r?!0:d,configurable:!0,writable:!0});return n},"destroyCircular");function K(t,e){let n=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof t=="object"&&t!==null?ri({from:t,seen:[],forceEnumerable:!0,maxDepth:n,depth:0,useToJSON:r,serialize:!0}):typeof t=="function"?`[Function: ${t.name??"anonymous"}]`:t}s(K,"serializeError");var zu=/file:\/\/\/(.*?)\/dist\//g,ju=/\(https:\/\/raw\.githubusercontent\.com\/.*?\)/g,Vu="at async Event.respondWith";function oi(t){return typeof t!="string"?t:t.split(`
50
50
  `).filter(e=>!e.trim().startsWith("at async file")).map((e,n)=>{let r=e.replaceAll(zu,"").replaceAll(ju,"").replaceAll(Vu,"").trim();return n===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
51
51
  `)}s(oi,"cleanStack");function Lt(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 w=s(m=>{if(u.inlineCharacterLimit===void 0)return m;let y=m.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return y.length<=u.inlineCharacterLimit?y: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"||Zo(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((y,I)=>{let E=a.length-1===I?p.newline:","+p.newlineOrSpace,x=i(y,u,c+d,l+1);return u.transform&&(x=u.transform(a,I,x)),p.indent+x+E}).join("")+p.pad+"]";return r.pop(),w(m)}if(Je(a)){let m=qo(a);if(u.filter&&(m=m.filter(I=>u.filter?.(a,I))),m.length===0)return"{}";r.push(a);let y="{"+p.newline+m.map((I,E)=>{let x=m.length-1===E?p.newline:","+p.newlineOrSpace,C=typeof I=="symbol",k=!C&&/^[a-z$_][$\w]*$/i.test(I),A=C||k?I:i(I,u,"",l+1),N=i(a[I],u,c+d,l+1);return u.transform&&(N=u.transform(a,I,N)),p.indent+String(A)+": "+N+x}).join("")+p.pad+"}";return r.pop(),w(y)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,m=>m===`
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(m=>{if(u.inlineCharacterLimit===void 0)return m;let y=m.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return y.length<=u.inlineCharacterLimit?y: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"||Zo(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((y,I)=>{let E=a.length-1===I?p.newline:","+p.newlineOrSpace,x=i(y,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(m)}if(Je(a)){let m=qo(a);if(u.filter&&(m=m.filter(I=>u.filter?.(a,I))),m.length===0)return"{}";r.push(a);let y="{"+p.newline+m.map((I,E)=>{let x=m.length-1===E?p.newline:","+p.newlineOrSpace,C=typeof I=="symbol",k=!C&&/^[a-z$_][$\w]*$/i.test(I),A=C||k?I:i(I,u,"",l+1),N=i(a[I],u,c+d,l+1);return u.transform&&(N=u.transform(a,I,N)),p.indent+String(A)+": "+N+x}).join("")+p.pad+"}";return r.pop(),b(y)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,m=>m===`
55
55
  `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(t,e,n,0)}s(Lt,"stringifyObject");function be(t){return t.map(e=>K(e))}s(be,"makeErrorsSerializable");function Le(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(K(e))}s(Le,"extractBestMessage");function ii(t){let e=[];return t.forEach(n=>{if(typeof n=="string")e.push(n);else if(Ye(n))if(n.stack)e.push(n.stack);else{let r=Lt(K(n));e.push(r)}else if(typeof n=="object"){let r=Lt(n);e.push(r)}else{let r=rr(n);e.push(r)}}),e.join(`
56
- `)}s(ii,"messagesToMultilineText");function ce(t){return typeof t=="string"?t:JSON.stringify(t)}s(ce,"stringifyNonString");function rr(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"?Vn(t):"unknown"}s(rr,"stringifyNonStringToText");var _t=require("jose");async function le(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(le,"fetchRetry");async function ie({serviceAccount:t,audience:e,expirationTime:n="1h",payload:r={}}){let{clientEmail:o,privateKeyId:i,privateKey:a}=t;return await new _t.SignJWT(r).setProtectedHeader({alg:"RS256",kid:i}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(n).sign(a)}s(ie,"getTokenFromGcpServiceAccount");async function si(t,e,n){return ai(t,{token:e,returnSecureToken:!0},n)}s(si,"exchangeFirebaseJwtForIdToken");async function kt(t,e,n){return ai(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},n)}s(kt,"exchangeGgpJwtForIdToken");async function ai(t,e,n){let r=await le(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(ai,"fetchToken");var W=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,_t.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 Dt=class extends U{constructor(n){super();this.options=n}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new nt(this.options)}},Gu="https://logging.googleapis.com/v2/entries:write?alt=json",or={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},nt=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 log(e,n){if(e.messages.length===0)return;let r={allMessages:be(e.messages)};this.#t||(this.#t=await W.init(this.#e));let o=this.#t.projectId??"zuplo-production",i={logName:this.#n,resource:{type:"global"},severity:or[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=Le(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 W.init(this.#e));let n=await ie({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await fetch(Gu,{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 S("google-log-transport",1,this.dispatchFunction)};var Ht="gcp";function Ut(t){let e={allMessages:be(t.messages)},n="zuplo-production",r=Le(e.allMessages),o={logName:`projects/${n}/logs/runtime-user`,message:r,severity:or[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(Ut,"gcpLogFormat");var rt=class{static{s(this,"ConsoleTransport")}constructor(e,n){this.#e=e??console,this.#t=n}#e;#t;async log(e){if(this.#t===Ht){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Ut(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 Nt=class extends U{constructor(n){super();this.options=n}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new ot(this.options)}},ir="__ddtags",sr="__ddattr",ar=s(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),Ku=s(t=>{let e=Object.keys(t),n=[];return e.forEach(r=>{let o=t[r];o==null?n.push(ar(r)):n.push(`${ar(r)}:${ar(o.toString())}`)}),n.join(",")},"formatTags"),ot=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;async log(e,n){let r={},o=n.custom[ir];o&&typeof o=="object"&&Object.assign(r,o);let i=[...e.messages],a=e.messages.findIndex(m=>m[ir]!==void 0);a>-1&&(Object.assign(r,i[a][ir]),i.splice(a,1));let u={},c=n.custom[sr];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(m=>m[sr]!==void 0);l>-1&&(Object.assign(u,i[l][sr]),i.splice(l,1));let d=be(i),w={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(n.originalRequest.url).hostname,msg:Le(d),service:e.loggingId,ddtags:Ku(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(w,u),this.batcher.enqueue(w),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 S("data-dog-transport",10,this.dispatchFunction)};var it=class{static{s(this,"ProcessTransport")}constructor(e,n){this.#e=e,this.#t=n}#e;#t;async log(e){if(this.#t===Ht){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Ut(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 Wu=s(({url:t,remoteLogToken:e,loggingId:n,sendOnlyErrors:r})=>async o=>{let i;r===!0?i=o.filter(a=>a.level==="error"):i=o,i.length!==0&&fetch(`${t}/publish/${n}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:i.map(a=>({...a,messages:be(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"),Mt,Zt=class{static{s(this,"RemoteLogTransport")}constructor(e){Mt||(Mt=new S("remote-log-transport",1,Wu(e)))}async log(e,n){Mt.enqueue(e),n.waitUntil(Mt.waitUntilFlushed())}};var Ju={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},ui=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:Ju[n.level],body:n.messages,attributes:r}},"unifiedFormatter");var Yu=s(({url:t,remoteLogToken:e,deploymentName:n,build:r})=>async o=>{if(o.length===0)return;let i=ui(n,r);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"),qt,$t=class{static{s(this,"UnifiedLogTransport")}constructor(e){qt||(qt=new S("unified-log-transport",1,Yu(e)))}async log(e,n){qt.enqueue(e),n.waitUntil(qt.waitUntilFlushed())}};var ur=(0,ci.debug)("zuplo:logging"),Ft=class{constructor(e){this.serviceProvider=e;this.systemCoreLogger=this.setupSystemCoreLogger(h.instance),this.userCoreLogger=this.setupUserCoreLogger(h.instance)}static{s(this,"LogInitializer")}systemCoreLogger;userCoreLogger;setupSystemCoreLogger(e){let{build:n}=e;ur("Gateway.setupSystemCoreLogger");let r=[],o=this.serviceProvider.getService(Xe);return o?r.push(new it(o.logger,e.logFormat)):e.isDeno&&r.push(new rt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new $t({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),new et(e.systemLogLevel,"system",e.loggingId,n.BUILD_ID,r)}setupUserCoreLogger(e){ur("Gateway.setupUserCoreLogger");let n=[],{runtime:r,build:o}=e,i=this.serviceProvider.getService(Xe);if(i&&i.captureUserLogs===!0?n.push(new it(i.logger,e.logFormat)):e.isDeno&&n.push(new rt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&n.push(new Zt({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:e.isCloudflare})),r.GCP_USER_LOG_NAME&&r.GCP_USER_LOG_SVC_ACCT_JSON&&n.push(new nt({serviceAccountJson:r.GCP_USER_LOG_SVC_ACCT_JSON,logName:r.GCP_USER_LOG_NAME})),r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let a=r.ZUPLO_USER_LOGGER_DATA_DOG_URL;n.push(new ot({apiKey:r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:a}))}return he.forEach(a=>{a instanceof U&&n.push(a.getTransport())}),new et(e.userLogLevel,"user",e.loggingId,o.BUILD_ID,n)}createRequestLoggers(e,n,r,o,i){ur("Gateway.createRequestLoggers");let a=new At(r,o,i),u=new tt(e,n,this.systemCoreLogger,a);return{userRequestLogger:new tt(e,n,this.userCoreLogger,a),systemRequestLogger:u}}};var ve=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 cr=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},_e=class{static{s(this,"LookupResult")}constructor(e,n,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=n}executableHandler;routeConfiguration;params},lr=class extends Error{static{s(this,"RouterError")}constructor(e,n){super(e,n)}},ke=class{static{s(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,n){if(!(e instanceof ve||e instanceof D))throw new L("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 cr(o,i,e,n);Object.freeze(a.config),this.routeEntries.push(a)}catch(i){throw new lr(`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 _e(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 _e(o.config,o.executableHandler,a.pathname.groups);n.push(u)}}return n}};var Qu=["/__zuplo/ping","/__zuplo/open-api","/__zuplo/docs","/__zuplo/consumers","/__zuplo/external-users","/__zuplo/assets","/__zuplo/config","/__zuplo/build","/favicon.ico"],se=(0,li.debug)("zuplo:runtime"),Xu=s(t=>{let e=t.findIndex(n=>n.name===We.name);return e>-1?[...t.splice(e),We]:[...t,We]},"setupSystemNoVersion"),J=class t{constructor(e,n,r,o){this.routeData=e;this.runtimeSettings=n;this.schemaValidator=o;se("Gateway.constructor"),this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=new Ft(r)}static{s(this,"Gateway")}static#e;static async initialize(e,n,r,o,i){if(se("Gateway.initialize"),!t.#e){await No(i);let a={...e,corsPolicies:jo(e.corsPolicies)},u=new t(a,n,r,o);t.#e=u}return t.#e}static purgeGatewayCache(){se("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new L("Gateway cannot be used before it is initialized");return t.#e}instanceId=crypto.randomUUID();#t;#n;#r=[Ct,St,j];#o;setupRoutes=()=>{se("Gateway.setupRoutes");let e=this.routeData,n=Xu(e.versions),r=new ke(n);if(e.routes.length===0)return zn(r,this),Xn(r,this),Yn(r,this),Vo(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(ti(r,this),ei(r,this)),zn(r,this),Xn(r,this),Yn(r,this);for(let i of he)i instanceof ue&&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 H({processors:this.#r,handler:a,gateway:this}),c=new ve(i);r.addRoute(c,u.execute)}),Go(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 se("An error occurred in the user's errorHandler",o),this.#i(e,n,o)}}#i(e,n,r){se("Gateway.internalErrorResponse");let o={};if(h.instance.isDeno){if(r instanceof P&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let i=K(r.cause);"stack"in i&&(i.stack=oi(i.stack)),o={cause:i}}}return R.internalServerError(e,n,{detail:r.message,...o})}#s(e){let n=new Headers(e.headers);return lo.forEach(r=>{n.delete(r)}),h.instance.isDeno&&po.forEach(r=>{n.delete(r)}),new Request(e,{headers:n})}async handleRequest(e,n){let r=e.headers.get(je)??e.headers.get(no),o=e.headers.get(Se);if(!r){r=crypto.randomUUID();let E=new Headers(e.headers);E.set(je,r),e=new Request(e,{headers:E})}if(["GET","HEAD"].includes(e.method)&&e.body){let E=new Headers(e.headers);E.set(ro,"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 L(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let p=new Bt(e.headers),w=this.#s(e),m=new _(w,{params:d.params}),y=new zt({logger:a,route:d.routeConfiguration,requestId:r,fetchEvent:n,custom:i,incomingRequestProperties:p}),I=z.initialize(y,m);if(d.routeConfiguration===Qn&&Ke.value?.notFoundHandler!==void 0){let E=this.#n.lookupByPathOnly(l);I.pathOnlyMatches=E.map(x=>x.routeConfiguration).filter(x=>x instanceof ve)}try{if(T.addLogger(y,u),!c.pathname.startsWith("/__zuplo")){let k=await Do(m,y);if(k instanceof Response)return k;{let A=z.getContextExtensions(y);m=k,A.latestRequest=m}}[...Qu,...this.runtimeSettings.developerPortal.enabled?[this.runtimeSettings.developerPortal.sitePathname]:[]].filter(k=>new RegExp(k).test(c.pathname)).length===0&&a.debug(`Request received '${c.pathname}'`,{method:e.method,url:c.pathname,hostname:c.hostname,route:d.routeConfiguration.path});let x=d.executableHandler;ec(x,d,e),se("Gateway.handleRequest - call user handler");let C=await x(m,y);if(se("Gateway.handleRequest - user handler"),!(C instanceof Response))throw new P(`Invalid Response type from the request handler: ${typeof C}`);if(C.bodyUsed)throw new P("The response object has already been used. Return a new response instead.");if(C.headers.get(je)===null&&!C.webSocket){let k=new Headers(C.headers);return k.set(je,r),new Response(C.body,{status:C.status,statusText:C.statusText,headers:k,cf:C.cf})}else return C}catch(E){return se("Gateway - error executing handler",E),E instanceof P?(a.error(E),u.warn(E)):u.error(E),await this.#i(m,y,E)}}};function ec(t,e,n){if(se("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(ec,"checkHandler");var di=s(async(t,e,n)=>{let r=J.instance.routeData.policies,o=Qe([t],r);if(o.length===0)throw new P(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);let i=o[0];return i.handler(e,n,i.options,t)},"invokeInboundPolicy");var Bt=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Sn);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Cn)??void 0}get city(){return this.#e.get(In)??this.#e.get(oo)??void 0}get continent(){return this.#e.get(xn)??this.#e.get(io)??void 0}get country(){return this.#e.get(vn)??this.#e.get(so)??void 0}get latitude(){return this.#e.get(Tn)??this.#e.get(uo)??void 0}get longitude(){return this.#e.get(On)??this.#e.get(ao)??void 0}get colo(){return this.#e.get(An)??void 0}get postalCode(){return this.#e.get(Ln)??void 0}get metroCode(){return this.#e.get(_n)??void 0}get region(){return this.#e.get(kn)??void 0}get regionCode(){return this.#e.get(Dn)??void 0}get timezone(){return this.#e.get(Hn)??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}}},Ce=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},Ae=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,n){super("responseSent"),this.request=e,this.response=n}request;response},z=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}},zt=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)=>di(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{z.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{z.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 de=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 tc=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function dr(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!tc.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}s(dr,"isRestrictedEnvVariableName");function pr(t){return!!t.startsWith("ZUPLO_")}s(pr,"isZuploReadableEnvVariableName");var Z=new Proxy({},{get(t,e){if(dr(String(e))&&!pr(String(e)))return;let n=globalThis,r;return n.process?r=n.process.env[e]:r=n[e],r}});var mi=Oe(Ee());var X=(0,mi.debug)("zuplo:runtime:external-service");function gi(){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(gi,"getServiceAuth");async function fi(t){let e=gi();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 yi(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(fi,"externalServiceTunnelConfig");async function hi(t,e){let n=gi();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 yi(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 De(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(hi,"externalServiceHandler");async function yi(t,e,n,r){let o=t.toLowerCase(),i=e.toLowerCase(),a=n.toLowerCase(),u=nc(r);X(`Hashing service name: ${i}-${o}.${i}-${a}-${u}`);let c=await pi(`${i}-${o}`),l=await pi(`${i}-${a}-${u}`);return`${c}.${l}`}s(yi,"hashServiceName");async function pi(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(pi,"hashSegment");function nc(t){let e=t.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}s(nc,"sanitizeEnvironmentType");var bi=new Map;bi.set("service:",hi);var De=globalThis.fetch;globalThis.fetch=function(t,e){let n=rc(e);if(typeof t=="string"){let r=new URL(t),o=bi.get(r.protocol);return o?o(t,n):De(t,n)}else return De(t,n)};var rc=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 wi=s(()=>{J.purgeGatewayCache()},"purgeGatewayCache"),jt=class{constructor(e,n,r,o,i,a,u){this.routeData=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 J.initialize(this.routeData,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 Si=Oe(Ee());function oc(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(oc,"lexer");function mr(t,e){e===void 0&&(e={});for(var n=oc(t),r=e.prefixes,o=r===void 0?"./":r,i="[^".concat(sc(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=s(function(B){if(c<n.length&&n[c].type===B)return n[c++].value},"tryConsume"),p=s(function(B){var V=d(B);if(V!==void 0)return V;var G=n[c],re=G.type,Rn=G.index;throw new TypeError("Unexpected ".concat(re," at ").concat(Rn,", expected ").concat(B))},"mustConsume"),w=s(function(){for(var B="",V;V=d("CHAR")||d("ESCAPED_CHAR");)B+=V;return B},"consumeText");c<n.length;){var m=d("CHAR"),y=d("NAME"),I=d("PATTERN");if(y||I){var E=m||"";o.indexOf(E)===-1&&(l+=E,E=""),l&&(a.push(l),l=""),a.push({name:y||u++,prefix:E,suffix:"",pattern:I||i,modifier:d("MODIFIER")||""});continue}var x=m||d("ESCAPED_CHAR");if(x){l+=x;continue}l&&(a.push(l),l="");var C=d("OPEN");if(C){var E=w(),k=d("NAME")||"",A=d("PATTERN")||"",N=w();p("CLOSE"),a.push({name:k||(A?u++:""),pattern:k&&!A?i:A,prefix:E,suffix:N,modifier:d("MODIFIER")||""});continue}p("END")}return a}s(mr,"parse");function Ri(t,e){return ic(mr(t,e),e)}s(Ri,"compile");function ic(t,e){e===void 0&&(e={});var n=ac(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 w=c?c[p.name]:void 0,m=p.modifier==="?"||p.modifier==="*",y=p.modifier==="*"||p.modifier==="+";if(Array.isArray(w)){if(!y)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(w.length===0){if(m)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var I=0;I<w.length;I++){var E=o(w[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 w=="string"||typeof w=="number"){var E=o(String(w),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=y?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(x))}}return l}}s(ic,"tokensToFunction");function sc(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(sc,"escapeString");function ac(t){return t&&t.sensitive?"":"i"}s(ac,"flags");var xi=Oe(Ee());var uc=(0,xi.debug)("zuplo:runtime"),fr=new TextEncoder,Pi={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"},cc=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],He=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 hr(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){uc("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")}},hr=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:w,appendSessionToken:m,allHeaders:y,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]=lc(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=w,this.appendSessionToken=m||this.service==="iotdevicegateway",this.headers.delete("Host");let C=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"),C.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&C.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(A=>y||!cc.includes(A)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(A=>A+":"+(A==="host"?this.url.host:(this.headers.get(A)||"").replace(/\s+/g," "))).join(`
56
+ `)}s(ii,"messagesToMultilineText");function ce(t){return typeof t=="string"?t:JSON.stringify(t)}s(ce,"stringifyNonString");function rr(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"?Vn(t):"unknown"}s(rr,"stringifyNonStringToText");var _t=require("jose");async function le(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(le,"fetchRetry");async function ie({serviceAccount:t,audience:e,expirationTime:n="1h",payload:r={}}){let{clientEmail:o,privateKeyId:i,privateKey:a}=t;return await new _t.SignJWT(r).setProtectedHeader({alg:"RS256",kid:i}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(n).sign(a)}s(ie,"getTokenFromGcpServiceAccount");async function si(t,e,n){return ai(t,{token:e,returnSecureToken:!0},n)}s(si,"exchangeFirebaseJwtForIdToken");async function kt(t,e,n){return ai(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},n)}s(kt,"exchangeGgpJwtForIdToken");async function ai(t,e,n){let r=await le(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(ai,"fetchToken");var W=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,_t.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 Dt=class extends U{constructor(n){super();this.options=n}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new nt(this.options)}},Gu="https://logging.googleapis.com/v2/entries:write?alt=json",or={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},nt=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 log(e,n){if(e.messages.length===0)return;let r={allMessages:be(e.messages)};this.#t||(this.#t=await W.init(this.#e));let o=this.#t.projectId??"zuplo-production",i={logName:this.#n,resource:{type:"global"},severity:or[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=Le(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 W.init(this.#e));let n=await ie({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await fetch(Gu,{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 S("google-log-transport",1,this.dispatchFunction)};var Ht="gcp";function Ut(t){let e={allMessages:be(t.messages)},n="zuplo-production",r=Le(e.allMessages),o={logName:`projects/${n}/logs/runtime-user`,message:r,severity:or[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(Ut,"gcpLogFormat");var rt=class{static{s(this,"ConsoleTransport")}constructor(e,n){this.#e=e??console,this.#t=n}#e;#t;async log(e){if(this.#t===Ht){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Ut(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 Nt=class extends U{constructor(n){super();this.options=n}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new ot(this.options)}},ir="__ddtags",sr="__ddattr",ar=s(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),Ku=s(t=>{let e=Object.keys(t),n=[];return e.forEach(r=>{let o=t[r];o==null?n.push(ar(r)):n.push(`${ar(r)}:${ar(o.toString())}`)}),n.join(",")},"formatTags"),ot=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;async log(e,n){let r={},o=n.custom[ir];o&&typeof o=="object"&&Object.assign(r,o);let i=[...e.messages],a=e.messages.findIndex(m=>m[ir]!==void 0);a>-1&&(Object.assign(r,i[a][ir]),i.splice(a,1));let u={},c=n.custom[sr];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(m=>m[sr]!==void 0);l>-1&&(Object.assign(u,i[l][sr]),i.splice(l,1));let d=be(i),b={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(n.originalRequest.url).hostname,msg:Le(d),service:e.loggingId,ddtags:Ku(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 S("data-dog-transport",10,this.dispatchFunction)};var it=class{static{s(this,"ProcessTransport")}constructor(e,n){this.#e=e,this.#t=n}#e;#t;async log(e){if(this.#t===Ht){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Ut(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 Wu=s(({url:t,remoteLogToken:e,loggingId:n,sendOnlyErrors:r})=>async o=>{let i;r===!0?i=o.filter(a=>a.level==="error"):i=o,i.length!==0&&fetch(`${t}/publish/${n}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:i.map(a=>({...a,messages:be(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"),Mt,Zt=class{static{s(this,"RemoteLogTransport")}constructor(e){Mt||(Mt=new S("remote-log-transport",1,Wu(e)))}async log(e,n){Mt.enqueue(e),n.waitUntil(Mt.waitUntilFlushed())}};var Ju={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},ui=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:Ju[n.level],body:n.messages,attributes:r}},"unifiedFormatter");var Yu=s(({url:t,remoteLogToken:e,deploymentName:n,build:r})=>async o=>{if(o.length===0)return;let i=ui(n,r);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"),qt,$t=class{static{s(this,"UnifiedLogTransport")}constructor(e){qt||(qt=new S("unified-log-transport",1,Yu(e)))}async log(e,n){qt.enqueue(e),n.waitUntil(qt.waitUntilFlushed())}};var ur=(0,ci.debug)("zuplo:logging"),Ft=class{constructor(e){this.serviceProvider=e;this.systemCoreLogger=this.setupSystemCoreLogger(h.instance),this.userCoreLogger=this.setupUserCoreLogger(h.instance)}static{s(this,"LogInitializer")}systemCoreLogger;userCoreLogger;setupSystemCoreLogger(e){let{build:n}=e;ur("Gateway.setupSystemCoreLogger");let r=[],o=this.serviceProvider.getService(Xe);return o?r.push(new it(o.logger,e.logFormat)):e.isDeno&&r.push(new rt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new $t({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),new et(e.systemLogLevel,"system",e.loggingId,n.BUILD_ID,r)}setupUserCoreLogger(e){ur("Gateway.setupUserCoreLogger");let n=[],{runtime:r,build:o}=e,i=this.serviceProvider.getService(Xe);if(i&&i.captureUserLogs===!0?n.push(new it(i.logger,e.logFormat)):e.isDeno&&n.push(new rt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&n.push(new Zt({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:e.isCloudflare})),r.GCP_USER_LOG_NAME&&r.GCP_USER_LOG_SVC_ACCT_JSON&&n.push(new nt({serviceAccountJson:r.GCP_USER_LOG_SVC_ACCT_JSON,logName:r.GCP_USER_LOG_NAME})),r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let a=r.ZUPLO_USER_LOGGER_DATA_DOG_URL;n.push(new ot({apiKey:r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:a}))}return he.forEach(a=>{a instanceof U&&n.push(a.getTransport())}),new et(e.userLogLevel,"user",e.loggingId,o.BUILD_ID,n)}createRequestLoggers(e,n,r,o,i){ur("Gateway.createRequestLoggers");let a=new At(r,o,i),u=new tt(e,n,this.systemCoreLogger,a);return{userRequestLogger:new tt(e,n,this.userCoreLogger,a),systemRequestLogger:u}}};var ve=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 cr=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},_e=class{static{s(this,"LookupResult")}constructor(e,n,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=n}executableHandler;routeConfiguration;params},lr=class extends Error{static{s(this,"RouterError")}constructor(e,n){super(e,n)}},ke=class{static{s(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,n){if(!(e instanceof ve||e instanceof D))throw new L("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 cr(o,i,e,n);Object.freeze(a.config),this.routeEntries.push(a)}catch(i){throw new lr(`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 _e(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 _e(o.config,o.executableHandler,a.pathname.groups);n.push(u)}}return n}};var Qu=["/__zuplo/ping","/__zuplo/open-api","/__zuplo/docs","/__zuplo/consumers","/__zuplo/external-users","/__zuplo/assets","/__zuplo/config","/__zuplo/build","/favicon.ico"],se=(0,li.debug)("zuplo:runtime"),Xu=s(t=>{let e=t.findIndex(n=>n.name===We.name);return e>-1?[...t.splice(e),We]:[...t,We]},"setupSystemNoVersion"),J=class t{constructor(e,n,r,o){this.routeData=e;this.runtimeSettings=n;this.schemaValidator=o;se("Gateway.constructor"),this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=new Ft(r)}static{s(this,"Gateway")}static#e;static async initialize(e,n,r,o,i){if(se("Gateway.initialize"),!t.#e){await No(i);let a={...e,corsPolicies:jo(e.corsPolicies)},u=new t(a,n,r,o);t.#e=u}return t.#e}static purgeGatewayCache(){se("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new L("Gateway cannot be used before it is initialized");return t.#e}instanceId=crypto.randomUUID();#t;#n;#r=[Ct,St,j];#o;setupRoutes=()=>{se("Gateway.setupRoutes");let e=this.routeData,n=Xu(e.versions),r=new ke(n);if(e.routes.length===0)return zn(r,this),Xn(r,this),Yn(r,this),Vo(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(ti(r,this),ei(r,this)),zn(r,this),Xn(r,this),Yn(r,this);for(let i of he)i instanceof ue&&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 H({processors:this.#r,handler:a,gateway:this}),c=new ve(i);r.addRoute(c,u.execute)}),Go(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 se("An error occurred in the user's errorHandler",o),this.#i(e,n,o)}}#i(e,n,r){se("Gateway.internalErrorResponse");let o={};if(h.instance.isDeno){if(r instanceof P&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let i=K(r.cause);"stack"in i&&(i.stack=oi(i.stack)),o={cause:i}}}return R.internalServerError(e,n,{detail:r.message,...o})}#s(e){let n=new Headers(e.headers);return lo.forEach(r=>{n.delete(r)}),h.instance.isDeno&&po.forEach(r=>{n.delete(r)}),new Request(e,{headers:n})}async handleRequest(e,n){let r=e.headers.get(je)??e.headers.get(no),o=e.headers.get(Se);if(!r){r=crypto.randomUUID();let E=new Headers(e.headers);E.set(je,r),e=new Request(e,{headers:E})}if(["GET","HEAD"].includes(e.method)&&e.body){let E=new Headers(e.headers);E.set(ro,"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 L(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let p=new Bt(e.headers),b=this.#s(e),m=new _(b,{params:d.params}),y=new zt({logger:a,route:d.routeConfiguration,requestId:r,fetchEvent:n,custom:i,incomingRequestProperties:p}),I=z.initialize(y,m);if(d.routeConfiguration===Qn&&Ke.value?.notFoundHandler!==void 0){let E=this.#n.lookupByPathOnly(l);I.pathOnlyMatches=E.map(x=>x.routeConfiguration).filter(x=>x instanceof ve)}try{if(T.addLogger(y,u),!c.pathname.startsWith("/__zuplo")){let k=await Do(m,y);if(k instanceof Response)return k;{let A=z.getContextExtensions(y);m=k,A.latestRequest=m}}[...Qu,...this.runtimeSettings.developerPortal.enabled?[this.runtimeSettings.developerPortal.sitePathname]:[]].filter(k=>new RegExp(k).test(c.pathname)).length===0&&a.debug(`Request received '${c.pathname}'`,{method:e.method,url:c.pathname,hostname:c.hostname,route:d.routeConfiguration.path});let x=d.executableHandler;ec(x,d,e),se("Gateway.handleRequest - call user handler");let C=await x(m,y);if(se("Gateway.handleRequest - user handler"),!(C instanceof Response))throw new P(`Invalid Response type from the request handler: ${typeof C}`);if(C.bodyUsed)throw new P("The response object has already been used. Return a new response instead.");if(C.headers.get(je)===null&&!C.webSocket){let k=new Headers(C.headers);return k.set(je,r),new Response(C.body,{status:C.status,statusText:C.statusText,headers:k,cf:C.cf})}else return C}catch(E){return se("Gateway - error executing handler",E),E instanceof P?(a.error(E),u.warn(E)):u.error(E),await this.#i(m,y,E)}}};function ec(t,e,n){if(se("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(ec,"checkHandler");var di=s(async(t,e,n)=>{let r=J.instance.routeData.policies,o=Qe([t],r);if(o.length===0)throw new P(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);let i=o[0];return i.handler(e,n,i.options,t)},"invokeInboundPolicy");var Bt=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Sn);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Cn)??void 0}get city(){return this.#e.get(In)??this.#e.get(oo)??void 0}get continent(){return this.#e.get(xn)??this.#e.get(io)??void 0}get country(){return this.#e.get(vn)??this.#e.get(so)??void 0}get latitude(){return this.#e.get(Tn)??this.#e.get(uo)??void 0}get longitude(){return this.#e.get(On)??this.#e.get(ao)??void 0}get colo(){return this.#e.get(An)??void 0}get postalCode(){return this.#e.get(Ln)??void 0}get metroCode(){return this.#e.get(_n)??void 0}get region(){return this.#e.get(kn)??void 0}get regionCode(){return this.#e.get(Dn)??void 0}get timezone(){return this.#e.get(Hn)??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}}},Ce=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},Ae=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,n){super("responseSent"),this.request=e,this.response=n}request;response},z=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}},zt=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)=>di(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{z.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{z.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 de=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 tc=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function dr(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!tc.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}s(dr,"isRestrictedEnvVariableName");function pr(t){return!!t.startsWith("ZUPLO_")}s(pr,"isZuploReadableEnvVariableName");var Z=new Proxy({},{get(t,e){if(dr(String(e))&&!pr(String(e)))return;let n=globalThis,r;return n.process?r=n.process.env[e]:r=n[e],r}});var mi=Oe(Ee());var X=(0,mi.debug)("zuplo:runtime:external-service");function gi(){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(gi,"getServiceAuth");async function fi(t){let e=gi();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 yi(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(fi,"externalServiceTunnelConfig");async function hi(t,e){let n=gi();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 yi(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 De(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(hi,"externalServiceHandler");async function yi(t,e,n,r){let o=t.toLowerCase(),i=e.toLowerCase(),a=n.toLowerCase(),u=nc(r);X(`Hashing service name: ${i}-${o}.${i}-${a}-${u}`);let c=await pi(`${i}-${o}`),l=await pi(`${i}-${a}-${u}`);return`${c}.${l}`}s(yi,"hashServiceName");async function pi(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(pi,"hashSegment");function nc(t){let e=t.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}s(nc,"sanitizeEnvironmentType");var bi=new Map;bi.set("service:",hi);var De=globalThis.fetch;globalThis.fetch=function(t,e){let n=rc(e);if(typeof t=="string"){let r=new URL(t),o=bi.get(r.protocol);return o?o(t,n):De(t,n)}else return De(t,n)};var rc=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 wi=s(()=>{J.purgeGatewayCache()},"purgeGatewayCache"),jt=class{constructor(e,n,r,o,i,a,u){this.routeData=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 J.initialize(this.routeData,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 Si=Oe(Ee());function oc(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(oc,"lexer");function mr(t,e){e===void 0&&(e={});for(var n=oc(t),r=e.prefixes,o=r===void 0?"./":r,i="[^".concat(sc(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=s(function(B){if(c<n.length&&n[c].type===B)return n[c++].value},"tryConsume"),p=s(function(B){var V=d(B);if(V!==void 0)return V;var G=n[c],re=G.type,Rn=G.index;throw new TypeError("Unexpected ".concat(re," at ").concat(Rn,", expected ").concat(B))},"mustConsume"),b=s(function(){for(var B="",V;V=d("CHAR")||d("ESCAPED_CHAR");)B+=V;return B},"consumeText");c<n.length;){var m=d("CHAR"),y=d("NAME"),I=d("PATTERN");if(y||I){var E=m||"";o.indexOf(E)===-1&&(l+=E,E=""),l&&(a.push(l),l=""),a.push({name:y||u++,prefix:E,suffix:"",pattern:I||i,modifier:d("MODIFIER")||""});continue}var x=m||d("ESCAPED_CHAR");if(x){l+=x;continue}l&&(a.push(l),l="");var C=d("OPEN");if(C){var E=b(),k=d("NAME")||"",A=d("PATTERN")||"",N=b();p("CLOSE"),a.push({name:k||(A?u++:""),pattern:k&&!A?i:A,prefix:E,suffix:N,modifier:d("MODIFIER")||""});continue}p("END")}return a}s(mr,"parse");function Ri(t,e){return ic(mr(t,e),e)}s(Ri,"compile");function ic(t,e){e===void 0&&(e={});var n=ac(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,m=p.modifier==="?"||p.modifier==="*",y=p.modifier==="*"||p.modifier==="+";if(Array.isArray(b)){if(!y)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(b.length===0){if(m)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(!m){var x=y?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(x))}}return l}}s(ic,"tokensToFunction");function sc(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(sc,"escapeString");function ac(t){return t&&t.sensitive?"":"i"}s(ac,"flags");var xi=Oe(Ee());var uc=(0,xi.debug)("zuplo:runtime"),fr=new TextEncoder,Pi={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"},cc=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],He=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 hr(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){uc("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")}},hr=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:m,allHeaders:y,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]=lc(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=m||this.service==="iotdevicegateway",this.headers.delete("Host");let C=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"),C.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&C.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(A=>y||!cc.includes(A)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(A=>A+":"+(A==="host"?this.url.host:(this.headers.get(A)||"").replace(/\s+/g," "))).join(`
57
57
  `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!C.has("X-Amz-Expires")&&C.set("X-Amz-Expires","86400"),C.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),C.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),C.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=Ii(this.encodedPath);let k=new Set;this.encodedSearch=[...this.url.searchParams].filter(([A])=>{if(!A)return!1;if(this.service==="s3"){if(k.has(A))return!1;k.add(A)}return!0}).map(A=>A.map(N=>Ii(encodeURIComponent(N)))).sort(([A,N],[B,V])=>A<B?-1:A>B?1:N<V?-1:N>V?1:0).map(A=>A.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 st("AWS4"+this.secretAccessKey,e),i=await st(o,this.region),a=await st(i,this.service);r=await st(a,"aws4_request"),this.cache.set(n,r)}return gr(await st(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,gr(await Ei(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 P("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=gr(await Ei(this.body||""))}return e}};async function st(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?fr.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",n,fr.encode(e))}s(st,"hmac");async function Ei(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?fr.encode(t):t)}s(Ei,"hash");function gr(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}s(gr,"buf2hex");function Ii(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}s(Ii,"encodeRfc3986");function lc(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 Pi?[Pi[i],a]:[i,a]}s(lc,"guessServiceRegion");function dc(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(dc,"b64ToUint6");function vi(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|=dc(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(vi,"base64Decode");function Vt(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}s(Vt,"uint6ToB64");function Oi(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(Vt(o>>>18&63),Vt(o>>>12&63),Vt(o>>>6&63),Vt(o&63)),o=0);return n.substring(0,n.length-2+e)+(e===2?"":e===1?"=":"==")}s(Oi,"base64Encode");function Ue(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}s(Ue,"numberToString");function pc(t){let e=t.getTimezoneOffset(),n=Math.abs(e),r=e>0?"-":"+",o=Ue(Math.floor(n/60)),i=Ue(n%60);return`${r}${o}${i}`}s(pc,"getCLFOffset");function yr(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=Ue(t.getDate()),r=e[t.getMonth()],o=t.getFullYear(),i=Ue(t.getHours()),a=Ue(t.getMinutes()),u=Ue(t.getSeconds()),c=pc(t);return`${n}/${r}/${o}:${i}:${a}:${u} ${c}`}s(yr,"toCLFDate");var Ti=(0,Si.debug)("zuplo:runtime"),mc="X-Amzn-Trace-Id",gc="x-amzn-errortype",Ci=[],fc=s(async(t,e,n)=>{let r=n;for await(let o of Ci)r=await o(t,e,n);return r},"onSendingAwsLambdaEvent"),Y=class extends P{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,n){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=n.get(mc)??void 0,this.errorType=n.get(gc)??void 0}},Ai={addSendingAwsLambdaEventHook:t=>{Ci.push(t)}};async function Li(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 He({accessKeyId:n,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(Ti(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,w]=await wc(t,{binaryMediaTypes:c}),{options:m}=e.route.handler,y;m&&typeof m=="object"&&"payloadFormatVersion"in m&&m.payloadFormatVersion==="2.0"?y=bc(t,e):y=await yc(t,e,{useAwsResourcePathStyle:u}),Ti("Calling onSendingAwsLambdaEvent hook");let I=await fc(t,e,y);I.body=p,I.isBase64Encoded=w;let E=await l.fetch(d,{body:JSON.stringify(I)});try{return hc(E)}catch(x){if(x instanceof Y){let C=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,C)}throw x}}s(Li,"awsLambdaHandler");async function hc(t){let e;try{e=await t.json()}catch{throw new Y("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 Y(e.message,t.headers):new Y(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new Y(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 Y(`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 Y(`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 Y(`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 Y("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new Y("Response was set to base64 encoded but body was not a string",t.headers);r=vi(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 Y(`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(hc,"getResponse");async function yc(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:yr(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Pc(e.route.path,n),stage:null},pathParameters:t.params,stageVariables:null}}s(yc,"buildEventVersion1");function bc(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:yr(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}s(bc,"buildEventVersion2");async function wc(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&&Rc(e,o)){let i=await t.arrayBuffer();n=Oi(new Uint8Array(i)),r=!0}else n=await t.clone().text();return[n,r]}s(wc,"getBodyResult");function Rc(t,e){let n=e.split(";")[0].trim().toLowerCase();return t.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===n)>-1}s(Rc,"matchesContentType");function Pc(t,e=!1){if(!e)return t;let n=mr(t),r=Ri(t),o={};return n.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),r(o)}s(Pc,"getResourcePath");var Ec=[502,503,504];async function Ne(t,e){if(Ec.includes(t.status)){let n=T.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(Ne,"logBadGatewayResponses");var br;function we(t){if(br===void 0){let n=h.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(n??"")||(n="debug"),br=n}return t.log[br]}s(we,"getHandlerUserLogFunction");async function _i(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=Ic(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 Ne(l,e),l}s(_i,"openApiSpecHandler");var Ic=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 xc(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(xc,"join");async function Di(t,e){let n=we(e),r=e.route.handler.options,o=r.forwardSearch!==!1;if(!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new 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=xc(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}),w=Date.now()-d;return n(`URL Forward received response ${p.status} - ${p.statusText} in ${w}ms`),Ne(p,e),p}s(Di,"urlForwardHandler");var vc=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 Hi(t,e){let n=we(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?vc(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`),Ne(d,e),d}s(Hi,"urlRewriteHandler");async function Ui(t,e){let n=h.instance,r=e.route.handler.options,o=we(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 fi(u),y=new URL(u);u=new URL(`${m.serviceBaseUrl}${y.pathname}${y.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 w=JSON.stringify({url:u});return new Response(w,{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(),w=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${p}'`;throw new Error(w)}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(Ui,"webSocketHandler");var wr=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"),Ni=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 Mi(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{s(async u=>{let c=await Ni(u,t,e,n,r,o);c!==void 0&&e.send(c)},"innerPipeline")(i).catch(r.log.error)}catch(a){r.log.error(a)}})}s(Mi,"wireUpListeners");async function Zi(t,e){let n=h.instance,r=e.route.handler.options,o=we(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(),C=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${x}'`;throw new Error(C)}let d=new WebSocketPair,[p,w]=Object.values(d),m=Date.now()-c;o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${m}ms`);let y=l.webSocket;y.accept(),w.accept();let I=r.policies&&r.policies.inbound?wr(r.policies.inbound,"inbound"):[],E=r.policies&&r.policies.outbound?wr(r.policies.outbound,"outbound"):[];return Mi(w,y,t,e,I),Mi(y,w,t,e,E),new Response(null,{status:101,webSocket:p})}s(Zi,"webSocketPipelineHandler");var Gt=class extends U{constructor(n){super();this.options=n}static{s(this,"DynaTraceLoggingPlugin")}getTransport(){return new Rr(this.options)}},Rr=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;async log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:ce(K(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 S("dyna-trace-log-transport",10,this.#i)};var Kt=class extends U{constructor(n){super();this.options=n}static{s(this,"LokiLoggingPlugin")}getTransport(){return new Er(this.options)}},Pr=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 Oc(t,e){return btoa(`${t}:${e}`)}s(Oc,"createBasicDigest");var Er=class{static{s(this,"LokiTransport")}constructor(e){this.#e=e.url,this.#t=Oc(e.username,e.password),this.#r=h.instance.loggingEnvironmentType,this.#o=h.instance.loggingEnvironmentStage,this.#n=h.instance.deploymentName}#e;#t;#n;#r;#o;async log(e,n){let r=new Pr(e.level,this.#n,this.#r,this.#o,e.requestId);e.messages.forEach(o=>{let i={stream:r,message:ce(K(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 S("loki-log-transport",10,this.#s)};var Wt=class extends U{constructor(n){super();this.options=n}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new Ir(this.options)}},Ir=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;async log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:ce(K(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(`
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=gr(await Ei(this.body||""))}return e}};async function st(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?fr.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",n,fr.encode(e))}s(st,"hmac");async function Ei(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?fr.encode(t):t)}s(Ei,"hash");function gr(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}s(gr,"buf2hex");function Ii(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}s(Ii,"encodeRfc3986");function lc(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 Pi?[Pi[i],a]:[i,a]}s(lc,"guessServiceRegion");function dc(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(dc,"b64ToUint6");function vi(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|=dc(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(vi,"base64Decode");function Vt(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}s(Vt,"uint6ToB64");function Oi(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(Vt(o>>>18&63),Vt(o>>>12&63),Vt(o>>>6&63),Vt(o&63)),o=0);return n.substring(0,n.length-2+e)+(e===2?"":e===1?"=":"==")}s(Oi,"base64Encode");function Ue(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}s(Ue,"numberToString");function pc(t){let e=t.getTimezoneOffset(),n=Math.abs(e),r=e>0?"-":"+",o=Ue(Math.floor(n/60)),i=Ue(n%60);return`${r}${o}${i}`}s(pc,"getCLFOffset");function yr(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=Ue(t.getDate()),r=e[t.getMonth()],o=t.getFullYear(),i=Ue(t.getHours()),a=Ue(t.getMinutes()),u=Ue(t.getSeconds()),c=pc(t);return`${n}/${r}/${o}:${i}:${a}:${u} ${c}`}s(yr,"toCLFDate");var Ti=(0,Si.debug)("zuplo:runtime"),mc="X-Amzn-Trace-Id",gc="x-amzn-errortype",Ci=[],fc=s(async(t,e,n)=>{let r=n;for await(let o of Ci)r=await o(t,e,n);return r},"onSendingAwsLambdaEvent"),Y=class extends P{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,n){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=n.get(mc)??void 0,this.errorType=n.get(gc)??void 0}},Ai={addSendingAwsLambdaEventHook:t=>{Ci.push(t)}};async function Li(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 He({accessKeyId:n,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(Ti(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,b]=await wc(t,{binaryMediaTypes:c}),{options:m}=e.route.handler,y;m&&typeof m=="object"&&"payloadFormatVersion"in m&&m.payloadFormatVersion==="2.0"?y=bc(t,e):y=await yc(t,e,{useAwsResourcePathStyle:u}),Ti("Calling onSendingAwsLambdaEvent hook");let I=await fc(t,e,y);I.body=p,I.isBase64Encoded=b;let E=await l.fetch(d,{body:JSON.stringify(I)});try{return hc(E)}catch(x){if(x instanceof Y){let C=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,C)}throw x}}s(Li,"awsLambdaHandler");async function hc(t){let e;try{e=await t.json()}catch{throw new Y("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 Y(e.message,t.headers):new Y(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new Y(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 Y(`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 Y(`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 Y(`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 Y("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new Y("Response was set to base64 encoded but body was not a string",t.headers);r=vi(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 Y(`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(hc,"getResponse");async function yc(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:yr(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Pc(e.route.path,n),stage:null},pathParameters:t.params,stageVariables:null}}s(yc,"buildEventVersion1");function bc(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:yr(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}s(bc,"buildEventVersion2");async function wc(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&&Rc(e,o)){let i=await t.arrayBuffer();n=Oi(new Uint8Array(i)),r=!0}else n=await t.clone().text();return[n,r]}s(wc,"getBodyResult");function Rc(t,e){let n=e.split(";")[0].trim().toLowerCase();return t.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===n)>-1}s(Rc,"matchesContentType");function Pc(t,e=!1){if(!e)return t;let n=mr(t),r=Ri(t),o={};return n.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),r(o)}s(Pc,"getResourcePath");var Ec=[502,503,504];async function Ne(t,e){if(Ec.includes(t.status)){let n=T.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(Ne,"logBadGatewayResponses");var br;function we(t){if(br===void 0){let n=h.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(n??"")||(n="debug"),br=n}return t.log[br]}s(we,"getHandlerUserLogFunction");async function _i(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=Ic(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 Ne(l,e),l}s(_i,"openApiSpecHandler");var Ic=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 xc(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(xc,"join");async function Di(t,e){let n=we(e),r=e.route.handler.options,o=r.forwardSearch!==!1;if(!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new 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=xc(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`),Ne(p,e),p}s(Di,"urlForwardHandler");var vc=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 Hi(t,e){let n=we(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?vc(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`),Ne(d,e),d}s(Hi,"urlRewriteHandler");async function Ui(t,e){let n=h.instance,r=e.route.handler.options,o=we(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 fi(u),y=new URL(u);u=new URL(`${m.serviceBaseUrl}${y.pathname}${y.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 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(Ui,"webSocketHandler");var wr=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"),Ni=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 Mi(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{s(async u=>{let c=await Ni(u,t,e,n,r,o);c!==void 0&&e.send(c)},"innerPipeline")(i).catch(r.log.error)}catch(a){r.log.error(a)}})}s(Mi,"wireUpListeners");async function Zi(t,e){let n=h.instance,r=e.route.handler.options,o=we(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(),C=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${x}'`;throw new Error(C)}let d=new WebSocketPair,[p,b]=Object.values(d),m=Date.now()-c;o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${m}ms`);let y=l.webSocket;y.accept(),b.accept();let I=r.policies&&r.policies.inbound?wr(r.policies.inbound,"inbound"):[],E=r.policies&&r.policies.outbound?wr(r.policies.outbound,"outbound"):[];return Mi(b,y,t,e,I),Mi(y,b,t,e,E),new Response(null,{status:101,webSocket:p})}s(Zi,"webSocketPipelineHandler");var Gt=class extends U{constructor(n){super();this.options=n}static{s(this,"DynaTraceLoggingPlugin")}getTransport(){return new Rr(this.options)}},Rr=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;async log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:ce(K(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 S("dyna-trace-log-transport",10,this.#i)};var Kt=class extends U{constructor(n){super();this.options=n}static{s(this,"LokiLoggingPlugin")}getTransport(){return new Er(this.options)}},Pr=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 Oc(t,e){return btoa(`${t}:${e}`)}s(Oc,"createBasicDigest");var Er=class{static{s(this,"LokiTransport")}constructor(e){this.#e=e.url,this.#t=Oc(e.username,e.password),this.#r=h.instance.loggingEnvironmentType,this.#o=h.instance.loggingEnvironmentStage,this.#n=h.instance.deploymentName}#e;#t;#n;#r;#o;async log(e,n){let r=new Pr(e.level,this.#n,this.#r,this.#o,e.requestId);e.messages.forEach(o=>{let i={stream:r,message:ce(K(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 S("loki-log-transport",10,this.#s)};var Wt=class extends U{constructor(n){super();this.options=n}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new Ir(this.options)}},Ir=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;async log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:ce(K(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
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 S("sumo-logic-log-transport",10,this.#s)};var Tc="d3a5b78f-8236-48f5-b1df-4fe269d41172",Jt=class extends U{constructor(n){super();this.options=n}static{s(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new xr(this.options)}},xr=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;async log(e,n){let r=this.buildEntry(e,n);this.batcher.enqueue(r),n.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,n){let r=ii(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=rr(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/${Tc}`,{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 S("vmware-log-insights-log-transport",10,this.#s)};var Yt=class extends U{constructor(n){super();this.options=n}static{s(this,"AWSLoggingPlugin")}getTransport(){return new vr(this.options)}},vr=class{static{s(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new S("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 He({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}async log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:ce(K(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 Or=new WeakMap,Sc={tags:[]},Qt=class extends ye{constructor(n){super();this.options=n}static{s(this,"DataDogMetricsPlugin")}getTransport(){return new Tr(this.options)}static setContext(n,r){let o=Or.get(n);o||(o=Sc);let i=Object.assign({...o},r);Or.set(n,i)}},Tr=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 S("data-dog-metrics-transport",10,this.dispatchFunction,T.getLogger(n)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(Or.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 Sr(await r.text())}},Sr=class t extends Error{static{s(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var Cr=new WeakMap,Cc={dimensions:[]},Xt=class extends ye{constructor(n){super();this.options=n}static{s(this,"DynatraceMetricsPlugin")}getTransport(){return new Ar(this.options)}static setContext(n,r){let o=Cr.get(n);o||(o=Cc);let i=Object.assign({...o},r);Cr.set(n,i)}},Ar=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 S("dynatrace-metrics-transport",10,this.dispatchFunction,T.getLogger(n)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(Cr.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 Lr(await r.text())}},Lr=class t extends Error{static{s(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var en=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 tn=class extends ue{static{s(this,"AuditLogPlugin")}constructor(e,n){super(),this.#e=e,this.#t=n}#e;#t;async initialize(e){new _r(e,this.#e,this.#t)}},qi=s(t=>{let e={};return t.forEach((n,r)=>{e[r]=n}),e},"serializableHeaders"),Ac={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},_r=class{static{s(this,"AuditPluginImpl")}constructor(e,n,r){this.#t=n;let o={...Ac};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 S("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?qi(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?qi(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(w=>{n.log.error(w)});n.waitUntil(p)}),e}catch(r){return n.log.error(r),e}}};var kr=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}},ae=class extends kr{static{s(this,"StripeSignatureVerificationError")}header;payload;constructor(e,n,r={}){super(r),this.header=e,this.payload=n}};var Lc="v1",_c=300;async function $i(t,e,n,r=_c,o){return await Dc(t,e,n,r,o),t instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(t)):JSON.parse(t)}s($i,"constructEventAsync");function kc(t,e){return`${e.timestamp}.${t}`}s(kc,"makeHMACContent");async function Dc(t,e,n,r,o){let{decodedHeader:i,decodedPayload:a,details:u,suspectPayloadType:c}=Hc(t,e,Lc),l=/\s/.test(n),d=await Zc(kc(a,u),n);return Uc(a,i,u,d,r,c,l,o)}s(Dc,"verifyHeaderAsync");function Hc(t,e,n){if(!t)throw new ae(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 ae(e,t,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=Nc(a,n);if(!u||u.timestamp===-1)throw new ae(a,i,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new ae(a,i,{message:"No signatures found with expected scheme"});return{decodedPayload:i,decodedHeader:a,details:u,suspectPayloadType:r}}s(Hc,"parseEventDetails");function Uc(t,e,n,r,o,i,a,u){let c=!!n.signatures.filter(w=>Mc(w,r)).length,l=`
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 Lr(await r.text())}},Lr=class t extends Error{static{s(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var en=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 tn=class extends ue{static{s(this,"AuditLogPlugin")}constructor(e,n){super(),this.#e=e,this.#t=n}#e;#t;async initialize(e){new _r(e,this.#e,this.#t)}},qi=s(t=>{let e={};return t.forEach((n,r)=>{e[r]=n}),e},"serializableHeaders"),Ac={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},_r=class{static{s(this,"AuditPluginImpl")}constructor(e,n,r){this.#t=n;let o={...Ac};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 S("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?qi(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?qi(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 kr=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}},ae=class extends kr{static{s(this,"StripeSignatureVerificationError")}header;payload;constructor(e,n,r={}){super(r),this.header=e,this.payload=n}};var Lc="v1",_c=300;async function $i(t,e,n,r=_c,o){return await Dc(t,e,n,r,o),t instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(t)):JSON.parse(t)}s($i,"constructEventAsync");function kc(t,e){return`${e.timestamp}.${t}`}s(kc,"makeHMACContent");async function Dc(t,e,n,r,o){let{decodedHeader:i,decodedPayload:a,details:u,suspectPayloadType:c}=Hc(t,e,Lc),l=/\s/.test(n),d=await Zc(kc(a,u),n);return Uc(a,i,u,d,r,c,l,o)}s(Dc,"verifyHeaderAsync");function Hc(t,e,n){if(!t)throw new ae(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 ae(e,t,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=Nc(a,n);if(!u||u.timestamp===-1)throw new ae(a,i,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new ae(a,i,{message:"No signatures found with expected scheme"});return{decodedPayload:i,decodedHeader:a,details:u,suspectPayloadType:r}}s(Hc,"parseEventDetails");function Uc(t,e,n,r,o,i,a,u){let c=!!n.signatures.filter(b=>Mc(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 ae(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 ae(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 ae(e,t,{message:"Timestamp outside the tolerance zone"});return!0}s(Uc,"validateComputedSignature");function Nc(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(Nc,"parseHeader");function Mc(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(Mc,"secureCompare");async function Zc(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]=Dr[i[u]];return a.join("")}s(Zc,"computeHMACSignatureAsync");var Dr=new Array(256);for(let t=0;t<Dr.length;t++)Dr[t]=t.toString(16).padStart(2,"0");function q(t,e){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(q,"optionValidator");var nn=s(async(t,e,n,r)=>{q(n,r).required("signingSecret","string").optional("tolerance","number");let o=t.headers.get("stripe-signature");try{let i=await t.clone().text();await $i(i,o,n.signingSecret)}catch(i){return e.log.error("Error validating stripe webhook",i),R.badRequest(t,e,{title:"Webhook Error",detail:i.message})}return t},"StripeWebhookVerificationInboundPolicy");var qc={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)}}},Fi=qc;function Bi(t){return t!==null&&typeof t=="object"&&"id"in t&&Q(t.id)&&"type"in t&&Q(t.type)}s(Bi,"isStripeWebhookEvent");var rn=class extends ue{static{s(this,"MeteringPlugin")}};var $c="checkout.session.completed",Hr=class extends rn{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(Z.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Z.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g("StripeMeteringPlugin - No 'meteringBucketId' property provided");if(!p)if(Z.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=Z.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new g("StripeMeteringPlugin - No 'apiKeyBucketName' property provided");if(!this.options.zuploAccountApiKey)throw new g("StripeMeteringPlugin - No 'zuploAccountApiKey' property provided");if(!h.instance.build.ACCOUNT_NAME)throw new L("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let w=this.options.meteringBucketRegion??"us-central1";if(!zc(w))throw new g(`StripeMeteringPlugin - The value '${w}' on the property 'meteringBucketRegion' is invalid.`);let m=await c.json();if(!Bi(m))return R.badRequest(c,l,{detail:"The received body was not in the expected format."});l.log.info(`Received Stripe webhook event of type '${m.type}' with ID '${m.id}'.`);let y,I,E;if(m.type===$c){let G=m,re=G.data?.object?.subscription;if(!re)throw new P("Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID.");if(I=G.data?.object?.client_reference_id,E=G.data?.object?.customer_email,!I)throw new P("Invalid Stripe webhook event. Expected '.data.object.client_reference_id' to be the customer sub.");if(!E)throw new P("Invalid Stripe webhook event. Expected '.data.object.customer_email' to be the customer email.");if(!re)throw new P("Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID.");y=await Fi.getSubscription({logger:l.log,stripeSecretKey:this.options.stripeSecretKey,subscriptionId:re})}else return R.ok(c,l,{detail:"Event was ignored by Stripe metering plugin webhook."});let x=y.id,C=y.customer,k=y.items?.data.find(G=>G.object==="subscription_item");if(!k||!k.id)throw new P("Invalid Stripe API result. Expected subscription to contain at least one subscription_item.");let A=k.plan;if(!A||!A.product)throw new P("Invalid Stripe API result. Expected subscription_item to have a plan.");let N=A.product,B=await Fc({apiKeyBucketName:p,accountName:h.instance.build.ACCOUNT_NAME,stripeProductId:N,stripeSubscriptionId:x,stripeCustomerId:C,managerEmail:E,managerSub:I,zuploAccountApiKey:this.options.zuploAccountApiKey,context:l});if(!B)return R.internalServerError(c,l,{detail:"No consumer was created, skipping creation of subscription"});let V="routes.oas.json";try{await Bc({context:l,stripeProductId:N,stripeSubscriptionId:x,customerKey:B,productKey:V,meteringBucketId:d,meteringBucketRegion:w})}catch(G){return R.internalServerError(c,l,{detail:G.message})}return R.ok(c,l)},"stripeWebhookHandler"),i=Wo({inboundPolicies:[{handler:nn,options:{signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance}}]}),a=new H({processors:[j,i],handler:o,gateway:r}),u=new D({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});n.addRoute(u,a.execute)}};async function Fc({accountName:t,apiKeyBucketName:e,zuploAccountApiKey:n,stripeSubscriptionId:r,stripeProductId:o,stripeCustomerId:i,managerEmail:a,managerSub:u,context:c}){let l=new URL(`/v1/accounts/${t}/key-buckets/${e}/consumers`,"https://dev.zuplo.com");l.searchParams.set("with-api-key","true");let d=crypto.randomUUID(),p={name:d,description:`Consumer for Stripe subscription ${r}`,tags:{providerSubscriptionKey:r,planProviderKey:o},metadata:{stripeSubscriptionId:r,stripeProductId:o,stripeCustomerId:i},managers:[{sub:u,email:a}]},w=await le({retryDelayMs:5,retries:2,logger:T.getLogger(c)},l.toString(),{method:"POST",headers:{Authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify(p)}),m=await w.json();if(w.status!==200){let y="Error creating API Key Consumer";throw c.log.error(y,m),new P(y)}return c.log.info("Successfully created API Key Consumer",{consumerId:d,stripeSubscriptionId:r,stripeProductId:o}),d}s(Fc,"createConsumer");async function Bc({context:t,stripeSubscriptionId:e,stripeProductId:n,customerKey:r,productKey:o,meteringBucketId:i,meteringBucketRegion:a}){let u={status:"active",type:"periodic",renewalStrategy:"monthly",region:a,providerKey:e,planProviderKey:n,customerKey:r,productKey:o},{authApiJWT:c,meteringServiceUrl:l}=h.instance;if(!vt(c))throw new L("No Zuplo JWT token set.");let d=await le({retryDelayMs:5,retries:2,logger:T.getLogger(t)},`${l}/internal/v1/metering/${i}/subscriptions`,{headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(u)});if(!d.ok){let p="Error creating metering subscription.",w;try{w=await d.json()}catch{w={status:d.status,statusText:d.statusText}}throw t.log.error(p,w),new P(p)}t.log.info("Successfully created/updated metering subscription.",u)}s(Bc,"saveSubscription");function zc(t){return t!==null&&typeof t=="string"&&["us-central1","europe-west4"].includes(t)}s(zc,"isMetricsRegion");var ji=new WeakMap,zi={},on=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){ji.set(e,n)}};async function Vi(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:zo(n.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=ji.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)},w=zi[n.apiKey];if(!w){let m=n.apiKey,y=t.headers.get("zm-test-id")??"";w=new S("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":m,"zm-test-id":y}});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}}),zi[m]=w}w.enqueue(p),e.waitUntil(w.waitUntilFlushed())}}),t}s(Vi,"AmberfloMeteringInboundPolicy");async function sn(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(sn,"sha256");var Gi=new Map;async function $(t,e){let n,r=Gi.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await sn(JSON.stringify({policyName:t,options:e}))}`,Gi.set(t,n)),n}s($,"getPolicyCacheName");var Ki="key-metadata-cache-type";function jc(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}s(jc,"getKeyValue");async function an(t,e,n,r){if(!n.bucketName)if(Z.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=Z.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=jc(a,o);if(!u||u==="")return i("No key present");let c=await Vc(u),l=await $(r,o),d=new M(l,{logger:T.getLogger(e)}),p=await d.get(c);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==Ki&&T.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let w={key:u},m=await le({retryDelayMs:5,retries:2,logger:T.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(w)});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 P(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${m.status}`)}let y=await m.json(),I={isValid:!0,typeId:Ki,user:{sub:y.name,data:y.metadata}};return t.user=I.user,d.put(c,I,o.cacheTtlSeconds),t}s(an,"ApiKeyInboundPolicy");async function Vc(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(Vc,"hashValue");var Wi=an;var at=require("jose");var Ur={},Gc=s(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new g("Invalid State - jwkUrl not set");Ur[e.jwkUrl]||(Ur[e.jwkUrl]=(0,at.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,at.jwtVerify)(t,Ur[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),Kc=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,at.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(w=>R.unauthorized(t,e,{detail:w}),"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?Gc:Kc,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 w=o.substring(i.length);if(!w||w.length===0)return a("No bearer token on authorization header");try{return await u(w,n)}catch(m){let y=new URL(t.url);return"code"in m&&m.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${y.pathname} `,m):e.log.warn(`Invalid token on: ${t.method} ${y.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 Ji=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 Yi=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 w=d.substring(0,p),m=d.substring(p+1),y=n.accounts.find(I=>I.username===w&&I.password===m);return y||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 Wc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Jc(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(Jc,"digestMessage");var Yc=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 Jc(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 Qi(t,e,n,r){let o=await $(r,n),i=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Yc(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 w=n?.expirationSecondsTtl??60,m=new Response(p.body,p);Wc.forEach(y=>m.headers.delete(y)),m.headers.set("cache-control",`s-maxage=${w}`),e.waitUntil(i.put(u,m))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}s(Qi,"CachingInboundPolicy");var Xi=s(async(t,e,n,r)=>{if(!n.method)throw new g(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new _(t,{method:n.method})},"ChangeMethodInboundPolicy");var es=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 _(t,{headers:o})},"ClearHeadersInboundPolicy");var ts=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 ns=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 rs=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 os=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=J.instance,i=Qe(n.policies,o?.routeData.policies);return er(i)(t,e)},"CompositeInboundPolicy");var is=s(async(t,e,n)=>{let r=t.user;if(!r)return R.unauthorized(t,e,{title:"Unable to check subscription for anonymous user",detail:"No user data on request"});let{sub:o}=r;if(!n.bucketId)return R.unauthorized(t,e,{title:"Metering bucket not configured",detail:"Specify one using the bucketId option on the policy"});let i=n.bucketId,a=await Qc(i,o,e);if(!a)return R.unauthorized(t,e,{title:"No valid, active subscription found"});if(!a.quotas)return R.forbidden(t,e,{title:"Insufficient credits"});for(let u of Object.keys(a.quotas))if(a.quotas[u]<=0)return R.forbidden(t,e,{title:"Insufficient credits"});return e.custom.subscription=a,e.addResponseSendingFinalHook(async()=>{let u=e.custom.meters,c={};for(let l of Object.keys(u))c[l]=u[l];await Xc(i,a.id,c,e)}),t},"CreditsMeteringInboundPolicy");async function Qc(t,e,n){let{authApiJWT:r,meteringServiceUrl:o}=h.instance,i=new URL(`${o}/internal/v1/metering/${t}/subscriptions`);i.search=new URLSearchParams({customerKey:e,status:"active"}).toString();let a=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${r}`,"zp-rid":n.requestId}});if(!a.ok)throw new Error(`Error retrieving subscriptions for credits metering ': ${a.status} - ${await a.text()}`);let u=await a.json();if(u.data.length!==0)return u.data.length>1&&n.log.warn(`Found more than one active subscription for customer ${e} -- using the first one.`),u.data[0]}s(Qc,"getSubscription");async function Xc(t,e,n,r){let{authApiJWT:o,meteringServiceUrl:i}=h.instance,a=new URL(`${i}/internal/v1/metering/${t}/subscriptions/${e}/quotas/consume`),u=await fetch(a,{method:"POST",body:JSON.stringify({meters:n}),headers:{Authorization:`Bearer ${o}`,"zp-rid":r.requestId}});u.ok||r.log.error(`Error consuming subscription quotas for credits metering ': ${u.status} - ${await u.text()}`)}s(Xc,"consumeSubscription");var ss=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=el(o);if(!i)return R.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await $(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 el(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}s(el,"getToken");var as=s(async(t,e,n,r)=>(q(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 us=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 _(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var Me="__unknown__",cs=s(async(t,e,n,r)=>{let o={allow:{countries:qe(n.allow?.countries,"allow.countries",r),regionCodes:qe(n.allow?.regionCodes,"allow.regionCode",r),asns:qe(n.allow?.asns,"allow.asOrganization",r)},block:{countries:qe(n.block?.countries,"block.countries",r),regionCodes:qe(n.block?.regionCodes,"block.regionCode",r),asns:qe(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??Me,a=e.incomingRequestProperties.regionCode?.toLowerCase()??Me,u=e.incomingRequestProperties.asn?.toString()??Me,c=o.ignoreUnknown&&i===Me,l=o.ignoreUnknown&&a===Me,d=o.ignoreUnknown&&u===Me,p=o.allow.countries,w=o.allow.regionCodes,m=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||w.length>0&&!w.includes(a)&&!l||m.length>0&&!m.includes(u)&&!d)return Ze(t,e,r,i,a,u);let y=o.block.countries,I=o.block.regionCodes,E=o.block.asns;return y.length>0&&y.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 qe(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(qe,"toLowerStringArray");var ls=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 ps=s(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return Nr(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 Nr(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(w=>{a.push({responseName:u,contentName:l,exampleName:w,exampleValue:d[w]})})})}),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 ds(a[u])}else return a.length>0?ds(a[0]):Nr(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 ds(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(ds,"generateResponse");var Nr=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 tl="Incoming",nl={logRequestBody:!0,logResponseBody:!0};function ms(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}s(ms,"headersToObject");function gs(){return new Date().toISOString()}s(gs,"timestamp");var Mr=new WeakMap,rl={};function ys(t,e){let n=Mr.get(t);n||(n=rl);let r=Object.assign({...n},e);Mr.set(t,r)}s(ys,"setMoesifContext");async function fs(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(fs,"readBody");var ol={},Zr;function hs(){if(!Zr)throw new P("Invalid State - no _lastLogger");return Zr}s(hs,"getLastLogger");function il(t){let e=ol[t];return e||(e=new S("moesif-inbound",100,async n=>{let r=JSON.stringify(n);hs().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||hs().error({status:o.status,body:await o.text()})})),e}s(il,"getDispatcher");async function bs(t,e,n,r){Zr=e.log;let o=gs(),i=Object.assign(nl,n);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await fs(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=il(i.applicationId),d=t.headers.get("true-client-ip"),p=Mr.get(e)??{},w={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:ms(t.headers)},m=i.logResponseBody?await fs(u,e):void 0,y={time:gs(),status:u.status,headers:ms(u.headers),body:m},I={request:w,response:y,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:tl};l.enqueue(I),e.waitUntil(l.waitUntilFlushed())}),t}s(bs,"MoesifInboundPolicy");var ws=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 Rs=require("jose");var qr,Ps=s(async(t,e,n,r)=>{if(!qr)try{qr=await(0,Rs.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return F(t,e,{issuer:n.authUrl,secret:qr,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Is=Oe(Ee());var un=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},$r=class extends un{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Fr=class extends un{static{s(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function sl(t,e){if(Fo(t))throw new $r(e)}s(sl,"throwIfUndefinedOrNull");function ut(t,e){if(sl(t,e),!Q(t))throw new Fr(e,"string")}s(ut,"throwIfNotString");var cn=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 ut(e,"redisClientUrl"),ut(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}){ut(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 L("Redis client failed with 401: Unauthorized"):new L(`Redis client failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},ln=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(ut(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 L("The in-memory redis client only supports /rate-limit calls")}};var dn=(0,Is.debug)("zuplo:policies:RateLimitInboundPolicy"),al="strict",ul=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"),cl=s(async t=>({key:`ip-${ul(t)}`}),"getIP"),ll=s(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),dl=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),pn;function pl(t,e){let n;if(pn)return pn;if(h.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new ln,pn=n,n;let{authApiJWT:r,redisURL:o}=h.instance;if(!Q(o))throw new L(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!Q(r))throw new L(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=cn.initialize(o,r,h.instance.deploymentName??"unknown",h.instance.systemUserAgent)),!n||!n.isEnabled())throw new L(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return pn=n,n}s(pl,"getRedisClient");async function Es(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(Es,"getCountAndUpdateExpiry");function ml(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 P(c)}return u},"outerFunction")}s(ml,"wrapUserFunction");var gl="Retry-After",Br=s(async(t,e,n,r)=>{let o=Date.now(),i=T.getLogger(e),a=s((c,l)=>{if(n.throwOnFailure)throw new L(c,{cause:l});i.error(c,l)},"throwOrLog"),u=s((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[gl]=l.toString()),R.tooManyRequests(t,e,void 0,d)},"rateLimited");try{let l={function:ml(n,r),user:ll,ip:cl,all:dl}[n.rateLimitBy],d=await l(t,e,r),p=d.key,w=d.requestsAllowed??n.requestsAllowed,m=d.timeWindowMinutes??n.timeWindowMinutes,y=n.headerMode??"retry-after",I=pl(r,i),x=`bucket/${h.instance.build.BUILD_ID}/${r}/${p}`;if((n.mode??al)==="async"){let A=await $(r,n),N=new pe(A,{logger:T.getLogger(e)}),B=Es(x,m,I,i,e.requestId),V=await N.get(x);if(V!==void 0&&V<=Date.now()){dn(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${x}' (async mode)`);let G=Math.round((V-Date.now())/1e3);return u(y,G)}return e.addEventListener("responseSending",G=>{try{let re=G,Rn=re.mutableResponse;re.mutableResponse=(async()=>{let ct=await B;if(ct.count>w){let oa=Date.now()+ct.ttlSeconds*1e3;return N.put(x,oa,ct.ttlSeconds).catch(Qr=>{throw i.error(Qr),Qr}),dn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${x}' (async mode)`),u(y,ct.ttlSeconds)}return Rn})()}catch(re){i.error(`RateLimitInboundPolicy '${r}' -error in responseSending`,re)}}),t}let k=await Es(x,m,I,i,e.requestId);return k.count>w?(dn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${x}' (strict mode)`),u(y,k.ttlSeconds)):t}catch(c){return a(c.message,c),t}finally{let c=Date.now()-o;dn(`RateLimitInboundPolicy '${r}' - latency ${c}ms`)}},"RateLimitInboundPolicy");var zr;function xs(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}s(xs,"headersToNameValuePairs");function fl(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}s(fl,"queryToNameValueParis");function hl(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}s(hl,"parseIntOrUndefined");var vs={};async function Os(t,e,n,r){let o=new Date,i=Date.now();return zr||(zr={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:zr,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:xs(t.headers),queryString:fl(t.query)},response:{status:a.status,statusText:a.statusText,headers:xs(a.headers),content:{size:hl(t.headers.get("content-length"))}}}]}}},d=vs[n.apiKey];if(!d){let p=n.apiKey;d=new S("readme-metering-inbound-policy",10,async w=>{try{let m=n.url??"https://metrics.readme.io/request",y=await fetch(m,{method:"POST",body:JSON.stringify(w),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});y.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${y.status}: '${await y.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(Os,"ReadmeMetricsInboundPolicy");var Ts=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 _(t,{headers:i})},"RemoveHeadersInboundPolicy");var Ss=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 Cs=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 _(i.toString(),t)},"RemoveQueryParamsInboundPolicy");var As=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 Ls=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),_s=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?Ls():i&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?Ls():t},"RequestSizeLimitInboundPolicy");function ks(t,e,n){return`_${Re(t+"_"+e+"_"+n)}`}s(ks,"getRawOperationDataIdentifierName");function mn(t,e,n,r){return`_${Re(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}s(mn,"getIdForParameterSchema");function gn(t,e,n){return`_${Re(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${Re(n.toLowerCase())}`}s(gn,"getIdForRequestBodySchema");function Ds(t,e){return`_${Re(t)}__${Re(e)}`}s(Ds,"getIdForRefSchema");function Re(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(Re,"sanitizedIdentifierName");var $e=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"),Fe=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=mn(n,r,o,c.name),p=J.instance.schemaValidator[d],w=p(e[c.name]),m=jr(p.errors);w||(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"),jr=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 Hs(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(m){let y=`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:`${y}, see errors property for more details`,errors:`${m}`});if(te(n.validateBody)&&ee(t,n.logLevel??"info",y,[r],m),ne(n.validateBody))return I}if(!e.headers.get("Content-Type")){let m=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,y=R.badRequest(e,t,{detail:m});return te(n.validateBody)&&ee(t,n.logLevel??"info",m,[r],[m]),ne(n.validateBody)?y:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=gn(t.route.path,e.method,o),u=J.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")}`,y=R.badRequest(e,t,{detail:m});return te(n.validateBody)&&ee(t,n.logLevel??"info",m,[r],[m]),ne(n.validateBody)?y:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=jr(l),w=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 w}s(Hs,"handleBodyValidation");function Us(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=$e(t),i=Fe(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(Us,"handleHeadersValidation");function Ns(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=$e(t),o=Fe(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(Ns,"handlePathParameterValidation");function Ms(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=$e(t),o=Fe(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(Ms,"handleQueryParameterValidation");var Vr=s(async(t,e,n)=>{let r=Ms(e,t,n);if(r!==void 0||(r=Ns(e,t,n),r!==void 0)||(r=Us(e,t,n),r!==void 0))return r;let o=await Hs(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),Zs=Vr;var qs=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 $s=s(async(t,e,n)=>new _(t,{body:n.body}),"SetBodyInboundPolicy");var Fs=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 _(t,{headers:i})},"SetHeadersInboundPolicy");var Bs=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 zs=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 _(i.toString(),t)},"SetQueryParamsInboundPolicy");var js=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 yl=s(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),Vs=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 yl(n.sleepInMs),t},"SleepInboundPolicy");var Gs=s(async(t,e,n,r)=>{q(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 _))throw new L("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 Ks=s(async(t,e,n,r)=>{q(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await $(r,n),i=new M(o,{logger:T.getLogger(e)}),a=await i.get(r);if(!a){let u=await bl(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 bl(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await le({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(bl,"getAccessToken");var Ws="https://accounts.google.com/o/oauth2/token",Gr,Js=s(async(t,e,n,r)=>{q(n,r).required("serviceAccountJson","string"),Gr||(Gr=await W.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 M(i,{logger:T.getLogger(e)}),u=await a.get(r);if(!u){let c=await ie({serviceAccount:Gr,audience:Ws,payload:o}),l=await kt(Ws,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 wl="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Rl=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Kr,Ys=s(async(t,e,n,r)=>{if(q(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(Rl.indexOf(p)!==-1)throw new g(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}Kr||(Kr=await W.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 $(r,n),u=new M(a,{logger:T.getLogger(e)}),c={uid:i,claims:o},l=await sn(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await ie({serviceAccount:Kr,audience:wl,payload:c}),w=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,m=await si(w,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!m.idToken)throw new P("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 Wr,Qs=s(async(t,e,n,r)=>{q(n,r).required("audience","string").required("serviceAccountJson","string"),Wr||(Wr=await W.init(n.serviceAccountJson));let o=await ie({serviceAccount:Wr,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var Xs="https://www.googleapis.com/oauth2/v4/token",Jr,ea=s(async(t,e,n,r)=>{q(n,r).required("audience","string").required("serviceAccountJson","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Jr||(Jr=await W.init(n.serviceAccountJson));let o=await $(r,n),i;n.useMemoryCacheOnly?i=new Te(o):i=new M(o,e);let a=await i.get(r);if(!a){let u=await ie({serviceAccount:Jr,audience:Xs,payload:{target_audience:`${n.audience}`}}),{id_token:c}=await kt(Xs,u,{retries:n.tokenRetries??3,retryDelayMs:10});if(!c)throw new P("Invalid token response from GCP");a=c,i.put(r,a,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamGcpServiceAuthInboundPolicy");var ta=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 L("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 na=s(async(t,e,n,r)=>{let o=T.getLogger(e);e.addResponseSendingFinalHook(async(d,p,w)=>{let m=de.get(w,"subscription");if((n.allowRequestsWithoutSubscription??!1)&&!m)return;if(!n.bucketId)if(Z.ZUPLO_METERING_SERVICE_BUCKET_ID)n.bucketId=Z.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`MeteringInboundPolicy '${r}' - no bucketId property provided`);let{authApiJWT:I,meteringServiceUrl:E}=h.instance;d.ok&&m&&n.meters&&fetch(`${E}/internal/v1/metering/${n.bucketId}/subscriptions/${m.id}/quotas/consume`,{headers:{Authorization:`Bearer ${I}`,"zp-rid":w.requestId},method:"POST",body:JSON.stringify({meters:n.meters})}).catch(x=>{w.log.error(`MeteringInboundPolicy '${r}' -error in serviceResponse`),o.error(`MeteringInboundPolicy '${r}' -error in serviceResponse`,x)})});let i=de.get(e,"subscription"),a=n.allowRequestsWithoutSubscription??!1,u=n.allowRequestsOverQuota??!1;if(!i){if(a)return t;throw new g("Subscription is not available for user")}if(i&&Object.keys(i.quotas).length===0)throw new g("Quota is not set up for the user's subscription");let l=Object.keys(n.meters).filter(d=>!Object.keys(i.quotas).includes(d));if(l.length>0)throw new g(`The following policy meters are not present in the subscription: ${l.join(", ")}`);for(let d of Object.keys(i.quotas))if(i.quotas[d]<=0&&!u)return R.tooManyRequests(t,e,{detail:`Quota exceeded for meter '${d}'`,title:"Quota Exceeded"});return t},"MeteringInboundPolicy");var ra=s(async(t,e,n,r)=>{let o=T.getLogger(e),i=n.allowRequestsWithoutSubscription??!1,a=t.user;if(!a)return i?t:R.unauthorized(t,e,{detail:"Unable to check subscription for anonymous user"});if(!n.bucketId)if(Z.ZUPLO_METERING_SERVICE_BUCKET_ID)n.bucketId=Z.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`LoadSubscriptionInboundPolicy '${r}' - no bucketId property provided`);let{authApiJWT:u,meteringServiceUrl:c}=h.instance,{sub:l}=a,d,p;try{if(d=await fetch(`${c}/internal/v1/metering/${n.bucketId}/subscriptions?customerKey=${l}&status=active`,{headers:{Authorization:`Bearer ${u}`,"zp-rid":e.requestId},method:"GET"}),!d.ok)return e.log.error(await d.text()),R.forbidden(t,e);p=await d.json()}catch(m){o.error(`LoadSubscriptionInboundPolicy '${r}' -error in serviceResponse`,m)}if((!p||!p.data||p.data.length===0)&&!i)return R.unauthorized(t,e,{detail:"No valid, active subscription found"});if((!p||!p.data||p.data.length===0)&&i)return t;let w=p&&p.data?p.data[0]:void 0;return de.set(e,"subscription",w),t},"LoadSubscriptionInboundPolicy");var fn=class t{static{s(this,"ServiceProviderImpl")}static#e;services=new Map;constructor(){}static getInstance(){return t.#e||(t.#e=new t),t.#e}setInstance(e){t.#e=e}addService(e,n){if(this.services.get(e))throw new L(`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 Yr=["sha-1","sha-256","sha-384","sha-512"],hn=class{static{s(this,"BaseCryptoBeta")}};var yn=class extends hn{static{s(this,"WorkerCryptoBeta")}async digest(e,n){if(!Yr.includes(e.toLowerCase()))throw new P(`Algorithm ${e} is not supported. Try using ${Yr.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 bn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var wn=class extends bn{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=globalThis.ZUPLO_KV;if(!r)throw new lt("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 ae(e,t,{message:"Timestamp outside the tolerance zone"});return!0}s(Uc,"validateComputedSignature");function Nc(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(Nc,"parseHeader");function Mc(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(Mc,"secureCompare");async function Zc(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]=Dr[i[u]];return a.join("")}s(Zc,"computeHMACSignatureAsync");var Dr=new Array(256);for(let t=0;t<Dr.length;t++)Dr[t]=t.toString(16).padStart(2,"0");function q(t,e){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(q,"optionValidator");var nn=s(async(t,e,n,r)=>{q(n,r).required("signingSecret","string").optional("tolerance","number");let o=t.headers.get("stripe-signature");try{let i=await t.clone().text();await $i(i,o,n.signingSecret)}catch(i){return e.log.error("Error validating stripe webhook",i),R.badRequest(t,e,{title:"Webhook Error",detail:i.message})}return t},"StripeWebhookVerificationInboundPolicy");var qc={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)}}},Fi=qc;function Bi(t){return t!==null&&typeof t=="object"&&"id"in t&&Q(t.id)&&"type"in t&&Q(t.type)}s(Bi,"isStripeWebhookEvent");var rn=class extends ue{static{s(this,"MeteringPlugin")}};var $c="checkout.session.completed",Hr=class extends rn{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(Z.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Z.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g("StripeMeteringPlugin - No 'meteringBucketId' property provided");if(!p)if(Z.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=Z.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new g("StripeMeteringPlugin - No 'apiKeyBucketName' property provided");if(!this.options.zuploAccountApiKey)throw new g("StripeMeteringPlugin - No 'zuploAccountApiKey' property provided");if(!h.instance.build.ACCOUNT_NAME)throw new L("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let b=this.options.meteringBucketRegion??"us-central1";if(!zc(b))throw new g(`StripeMeteringPlugin - The value '${b}' on the property 'meteringBucketRegion' is invalid.`);let m=await c.json();if(!Bi(m))return R.badRequest(c,l,{detail:"The received body was not in the expected format."});l.log.info(`Received Stripe webhook event of type '${m.type}' with ID '${m.id}'.`);let y,I,E;if(m.type===$c){let G=m,re=G.data?.object?.subscription;if(!re)throw new P("Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID.");if(I=G.data?.object?.client_reference_id,E=G.data?.object?.customer_email,!I)throw new P("Invalid Stripe webhook event. Expected '.data.object.client_reference_id' to be the customer sub.");if(!E)throw new P("Invalid Stripe webhook event. Expected '.data.object.customer_email' to be the customer email.");if(!re)throw new P("Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID.");y=await Fi.getSubscription({logger:l.log,stripeSecretKey:this.options.stripeSecretKey,subscriptionId:re})}else return R.ok(c,l,{detail:"Event was ignored by Stripe metering plugin webhook."});let x=y.id,C=y.customer,k=y.items?.data.find(G=>G.object==="subscription_item");if(!k||!k.id)throw new P("Invalid Stripe API result. Expected subscription to contain at least one subscription_item.");let A=k.plan;if(!A||!A.product)throw new P("Invalid Stripe API result. Expected subscription_item to have a plan.");let N=A.product,B=await Fc({apiKeyBucketName:p,accountName:h.instance.build.ACCOUNT_NAME,stripeProductId:N,stripeSubscriptionId:x,stripeCustomerId:C,managerEmail:E,managerSub:I,zuploAccountApiKey:this.options.zuploAccountApiKey,context:l});if(!B)return R.internalServerError(c,l,{detail:"No consumer was created, skipping creation of subscription"});let V="routes.oas.json";try{await Bc({context:l,stripeProductId:N,stripeSubscriptionId:x,customerKey:B,productKey:V,meteringBucketId:d,meteringBucketRegion:b})}catch(G){return R.internalServerError(c,l,{detail:G.message})}return R.ok(c,l)},"stripeWebhookHandler"),i=Wo({inboundPolicies:[{handler:nn,options:{signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance}}]}),a=new H({processors:[j,i],handler:o,gateway:r}),u=new D({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});n.addRoute(u,a.execute)}};async function Fc({accountName:t,apiKeyBucketName:e,zuploAccountApiKey:n,stripeSubscriptionId:r,stripeProductId:o,stripeCustomerId:i,managerEmail:a,managerSub:u,context:c}){let l=new URL(`/v1/accounts/${t}/key-buckets/${e}/consumers`,"https://dev.zuplo.com");l.searchParams.set("with-api-key","true");let d=crypto.randomUUID(),p={name:d,description:`Consumer for Stripe subscription ${r}`,tags:{providerSubscriptionKey:r,planProviderKey:o},metadata:{stripeSubscriptionId:r,stripeProductId:o,stripeCustomerId:i},managers:[{sub:u,email:a}]},b=await le({retryDelayMs:5,retries:2,logger:T.getLogger(c)},l.toString(),{method:"POST",headers:{Authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify(p)}),m=await b.json();if(b.status!==200){let y="Error creating API Key Consumer";throw c.log.error(y,m),new P(y)}return c.log.info("Successfully created API Key Consumer",{consumerId:d,stripeSubscriptionId:r,stripeProductId:o}),d}s(Fc,"createConsumer");async function Bc({context:t,stripeSubscriptionId:e,stripeProductId:n,customerKey:r,productKey:o,meteringBucketId:i,meteringBucketRegion:a}){let u={status:"active",type:"periodic",renewalStrategy:"monthly",region:a,providerKey:e,planProviderKey:n,customerKey:r,productKey:o},{authApiJWT:c,meteringServiceUrl:l}=h.instance;if(!vt(c))throw new L("No Zuplo JWT token set.");let d=await le({retryDelayMs:5,retries:2,logger:T.getLogger(t)},`${l}/internal/v1/metering/${i}/subscriptions`,{headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(u)});if(!d.ok){let p="Error creating metering subscription.",b;try{b=await d.json()}catch{b={status:d.status,statusText:d.statusText}}throw t.log.error(p,b),new P(p)}t.log.info("Successfully created/updated metering subscription.",u)}s(Bc,"saveSubscription");function zc(t){return t!==null&&typeof t=="string"&&["us-central1","europe-west4"].includes(t)}s(zc,"isMetricsRegion");var ji=new WeakMap,zi={},on=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){ji.set(e,n)}};async function Vi(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:zo(n.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=ji.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=zi[n.apiKey];if(!b){let m=n.apiKey,y=t.headers.get("zm-test-id")??"";b=new S("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":m,"zm-test-id":y}});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}}),zi[m]=b}b.enqueue(p),e.waitUntil(b.waitUntilFlushed())}}),t}s(Vi,"AmberfloMeteringInboundPolicy");async function sn(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(sn,"sha256");var Gi=new Map;async function $(t,e){let n,r=Gi.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await sn(JSON.stringify({policyName:t,options:e}))}`,Gi.set(t,n)),n}s($,"getPolicyCacheName");var Ki="key-metadata-cache-type";function jc(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}s(jc,"getKeyValue");async function an(t,e,n,r){if(!n.bucketName)if(Z.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=Z.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=jc(a,o);if(!u||u==="")return i("No key present");let c=await Vc(u),l=await $(r,o),d=new M(l,{logger:T.getLogger(e)}),p=await d.get(c);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==Ki&&T.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let b={key:u},m=await le({retryDelayMs:5,retries:2,logger:T.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(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 P(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${m.status}`)}let y=await m.json(),I={isValid:!0,typeId:Ki,user:{sub:y.name,data:y.metadata}};return t.user=I.user,d.put(c,I,o.cacheTtlSeconds),t}s(an,"ApiKeyInboundPolicy");async function Vc(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(Vc,"hashValue");var Wi=an;var at=require("jose");var Ur={},Gc=s(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new g("Invalid State - jwkUrl not set");Ur[e.jwkUrl]||(Ur[e.jwkUrl]=(0,at.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,at.jwtVerify)(t,Ur[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),Kc=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,at.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(b=>R.unauthorized(t,e,{detail:b}),"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?Gc:Kc,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(m){let y=new URL(t.url);return"code"in m&&m.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${y.pathname} `,m):e.log.warn(`Invalid token on: ${t.method} ${y.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 Ji=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 Yi=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),m=d.substring(p+1),y=n.accounts.find(I=>I.username===b&&I.password===m);return y||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 Wc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Jc(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(Jc,"digestMessage");var Yc=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 Jc(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 Qi(t,e,n,r){let o=await $(r,n),i=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Yc(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,m=new Response(p.body,p);Wc.forEach(y=>m.headers.delete(y)),m.headers.set("cache-control",`s-maxage=${b}`),e.waitUntil(i.put(u,m))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}s(Qi,"CachingInboundPolicy");var Xi=s(async(t,e,n,r)=>{if(!n.method)throw new g(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new _(t,{method:n.method})},"ChangeMethodInboundPolicy");var es=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 _(t,{headers:o})},"ClearHeadersInboundPolicy");var ts=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 ns=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 rs=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 os=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=J.instance,i=Qe(n.policies,o?.routeData.policies);return er(i)(t,e)},"CompositeInboundPolicy");var is=s(async(t,e,n)=>{let r=t.user;if(!r)return R.unauthorized(t,e,{title:"Unable to check subscription for anonymous user",detail:"No user data on request"});let{sub:o}=r;if(!n.bucketId)return R.unauthorized(t,e,{title:"Metering bucket not configured",detail:"Specify one using the bucketId option on the policy"});let i=n.bucketId,a=await Qc(i,o,e);if(!a)return R.unauthorized(t,e,{title:"No valid, active subscription found"});if(!a.quotas)return R.forbidden(t,e,{title:"Insufficient credits"});for(let u of Object.keys(a.quotas))if(a.quotas[u]<=0)return R.forbidden(t,e,{title:"Insufficient credits"});return e.custom.subscription=a,e.addResponseSendingFinalHook(async()=>{let u=e.custom.meters,c={};for(let l of Object.keys(u))c[l]=u[l];await Xc(i,a.id,c,e)}),t},"CreditsMeteringInboundPolicy");async function Qc(t,e,n){let{authApiJWT:r,meteringServiceUrl:o}=h.instance,i=new URL(`${o}/internal/v1/metering/${t}/subscriptions`);i.search=new URLSearchParams({customerKey:e,status:"active"}).toString();let a=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${r}`,"zp-rid":n.requestId}});if(!a.ok)throw new Error(`Error retrieving subscriptions for credits metering ': ${a.status} - ${await a.text()}`);let u=await a.json();if(u.data.length!==0)return u.data.length>1&&n.log.warn(`Found more than one active subscription for customer ${e} -- using the first one.`),u.data[0]}s(Qc,"getSubscription");async function Xc(t,e,n,r){let{authApiJWT:o,meteringServiceUrl:i}=h.instance,a=new URL(`${i}/internal/v1/metering/${t}/subscriptions/${e}/quotas/consume`),u=await fetch(a,{method:"POST",body:JSON.stringify({meters:n}),headers:{Authorization:`Bearer ${o}`,"zp-rid":r.requestId}});u.ok||r.log.error(`Error consuming subscription quotas for credits metering ': ${u.status} - ${await u.text()}`)}s(Xc,"consumeSubscription");var ss=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=el(o);if(!i)return R.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await $(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 el(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}s(el,"getToken");var as=s(async(t,e,n,r)=>(q(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 us=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 _(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var Me="__unknown__",cs=s(async(t,e,n,r)=>{let o={allow:{countries:qe(n.allow?.countries,"allow.countries",r),regionCodes:qe(n.allow?.regionCodes,"allow.regionCode",r),asns:qe(n.allow?.asns,"allow.asOrganization",r)},block:{countries:qe(n.block?.countries,"block.countries",r),regionCodes:qe(n.block?.regionCodes,"block.regionCode",r),asns:qe(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??Me,a=e.incomingRequestProperties.regionCode?.toLowerCase()??Me,u=e.incomingRequestProperties.asn?.toString()??Me,c=o.ignoreUnknown&&i===Me,l=o.ignoreUnknown&&a===Me,d=o.ignoreUnknown&&u===Me,p=o.allow.countries,b=o.allow.regionCodes,m=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||b.length>0&&!b.includes(a)&&!l||m.length>0&&!m.includes(u)&&!d)return Ze(t,e,r,i,a,u);let y=o.block.countries,I=o.block.regionCodes,E=o.block.asns;return y.length>0&&y.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 qe(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(qe,"toLowerStringArray");var ls=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 ps=s(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return Nr(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 Nr(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 ds(a[u])}else return a.length>0?ds(a[0]):Nr(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 ds(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(ds,"generateResponse");var Nr=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 tl="Incoming",nl={logRequestBody:!0,logResponseBody:!0};function ms(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}s(ms,"headersToObject");function gs(){return new Date().toISOString()}s(gs,"timestamp");var Mr=new WeakMap,rl={};function ys(t,e){let n=Mr.get(t);n||(n=rl);let r=Object.assign({...n},e);Mr.set(t,r)}s(ys,"setMoesifContext");async function fs(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(fs,"readBody");var ol={},Zr;function hs(){if(!Zr)throw new P("Invalid State - no _lastLogger");return Zr}s(hs,"getLastLogger");function il(t){let e=ol[t];return e||(e=new S("moesif-inbound",100,async n=>{let r=JSON.stringify(n);hs().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||hs().error({status:o.status,body:await o.text()})})),e}s(il,"getDispatcher");async function bs(t,e,n,r){Zr=e.log;let o=gs(),i=Object.assign(nl,n);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await fs(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=il(i.applicationId),d=t.headers.get("true-client-ip"),p=Mr.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)},m=i.logResponseBody?await fs(u,e):void 0,y={time:gs(),status:u.status,headers:ms(u.headers),body:m},I={request:b,response:y,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:tl};l.enqueue(I),e.waitUntil(l.waitUntilFlushed())}),t}s(bs,"MoesifInboundPolicy");var ws=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 Rs=require("jose");var qr,Ps=s(async(t,e,n,r)=>{if(!qr)try{qr=await(0,Rs.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return F(t,e,{issuer:n.authUrl,secret:qr,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Is=Oe(Ee());var un=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},$r=class extends un{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Fr=class extends un{static{s(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function sl(t,e){if(Fo(t))throw new $r(e)}s(sl,"throwIfUndefinedOrNull");function ut(t,e){if(sl(t,e),!Q(t))throw new Fr(e,"string")}s(ut,"throwIfNotString");var cn=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 ut(e,"redisClientUrl"),ut(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}){ut(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 L("Redis client failed with 401: Unauthorized"):new L(`Redis client failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},ln=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(ut(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 L("The in-memory redis client only supports /rate-limit calls")}};var dn=(0,Is.debug)("zuplo:policies:RateLimitInboundPolicy"),al="strict",ul=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"),cl=s(async t=>({key:`ip-${ul(t)}`}),"getIP"),ll=s(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),dl=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),pn;function pl(t,e){let n;if(pn)return pn;if(h.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new ln,pn=n,n;let{authApiJWT:r,redisURL:o}=h.instance;if(!Q(o))throw new L(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!Q(r))throw new L(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=cn.initialize(o,r,h.instance.deploymentName??"unknown",h.instance.systemUserAgent)),!n||!n.isEnabled())throw new L(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return pn=n,n}s(pl,"getRedisClient");async function Es(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(Es,"getCountAndUpdateExpiry");function ml(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 P(c)}return u},"outerFunction")}s(ml,"wrapUserFunction");var gl="Retry-After",Br=s(async(t,e,n,r)=>{let o=Date.now(),i=T.getLogger(e),a=s((c,l)=>{if(n.throwOnFailure)throw new L(c,{cause:l});i.error(c,l)},"throwOrLog"),u=s((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[gl]=l.toString()),R.tooManyRequests(t,e,void 0,d)},"rateLimited");try{let l={function:ml(n,r),user:ll,ip:cl,all:dl}[n.rateLimitBy],d=await l(t,e,r),p=d.key,b=d.requestsAllowed??n.requestsAllowed,m=d.timeWindowMinutes??n.timeWindowMinutes,y=n.headerMode??"retry-after",I=pl(r,i),x=`bucket/${h.instance.build.BUILD_ID}/${r}/${p}`;if((n.mode??al)==="async"){let A=await $(r,n),N=new pe(A,{logger:T.getLogger(e)}),B=Es(x,m,I,i,e.requestId),V=await N.get(x);if(V!==void 0&&V<=Date.now()){dn(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${x}' (async mode)`);let G=Math.round((V-Date.now())/1e3);return u(y,G)}return e.addEventListener("responseSending",G=>{try{let re=G,Rn=re.mutableResponse;re.mutableResponse=(async()=>{let ct=await B;if(ct.count>b){let oa=Date.now()+ct.ttlSeconds*1e3;return N.put(x,oa,ct.ttlSeconds).catch(Qr=>{throw i.error(Qr),Qr}),dn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${x}' (async mode)`),u(y,ct.ttlSeconds)}return Rn})()}catch(re){i.error(`RateLimitInboundPolicy '${r}' -error in responseSending`,re)}}),t}let k=await Es(x,m,I,i,e.requestId);return k.count>b?(dn(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${x}' (strict mode)`),u(y,k.ttlSeconds)):t}catch(c){return a(c.message,c),t}finally{let c=Date.now()-o;dn(`RateLimitInboundPolicy '${r}' - latency ${c}ms`)}},"RateLimitInboundPolicy");var zr;function xs(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}s(xs,"headersToNameValuePairs");function fl(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}s(fl,"queryToNameValueParis");function hl(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}s(hl,"parseIntOrUndefined");var vs={};async function Os(t,e,n,r){let o=new Date,i=Date.now();return zr||(zr={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:zr,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:xs(t.headers),queryString:fl(t.query)},response:{status:a.status,statusText:a.statusText,headers:xs(a.headers),content:{size:hl(t.headers.get("content-length"))}}}]}}},d=vs[n.apiKey];if(!d){let p=n.apiKey;d=new S("readme-metering-inbound-policy",10,async b=>{try{let m=n.url??"https://metrics.readme.io/request",y=await fetch(m,{method:"POST",body:JSON.stringify(b),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});y.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${y.status}: '${await y.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(Os,"ReadmeMetricsInboundPolicy");var Ts=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 _(t,{headers:i})},"RemoveHeadersInboundPolicy");var Ss=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 Cs=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 _(i.toString(),t)},"RemoveQueryParamsInboundPolicy");var As=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 Ls=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),_s=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?Ls():i&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?Ls():t},"RequestSizeLimitInboundPolicy");function ks(t,e,n){return`_${Re(t+"_"+e+"_"+n)}`}s(ks,"getRawOperationDataIdentifierName");function mn(t,e,n,r){return`_${Re(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}s(mn,"getIdForParameterSchema");function gn(t,e,n){return`_${Re(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${Re(n.toLowerCase())}`}s(gn,"getIdForRequestBodySchema");function Ds(t,e){return`_${Re(t)}__${Re(e)}`}s(Ds,"getIdForRefSchema");function Re(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(Re,"sanitizedIdentifierName");var $e=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"),Fe=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=mn(n,r,o,c.name),p=J.instance.schemaValidator[d],b=p(e[c.name]),m=jr(p.errors);b||(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"),jr=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 Hs(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(m){let y=`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:`${y}, see errors property for more details`,errors:`${m}`});if(te(n.validateBody)&&ee(t,n.logLevel??"info",y,[r],m),ne(n.validateBody))return I}if(!e.headers.get("Content-Type")){let m=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,y=R.badRequest(e,t,{detail:m});return te(n.validateBody)&&ee(t,n.logLevel??"info",m,[r],[m]),ne(n.validateBody)?y:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=gn(t.route.path,e.method,o),u=J.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")}`,y=R.badRequest(e,t,{detail:m});return te(n.validateBody)&&ee(t,n.logLevel??"info",m,[r],[m]),ne(n.validateBody)?y:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=jr(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(Hs,"handleBodyValidation");function Us(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=$e(t),i=Fe(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(Us,"handleHeadersValidation");function Ns(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=$e(t),o=Fe(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(Ns,"handlePathParameterValidation");function Ms(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=$e(t),o=Fe(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(Ms,"handleQueryParameterValidation");var Vr=s(async(t,e,n)=>{let r=Ms(e,t,n);if(r!==void 0||(r=Ns(e,t,n),r!==void 0)||(r=Us(e,t,n),r!==void 0))return r;let o=await Hs(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),Zs=Vr;var qs=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 $s=s(async(t,e,n)=>new _(t,{body:n.body}),"SetBodyInboundPolicy");var Fs=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 _(t,{headers:i})},"SetHeadersInboundPolicy");var Bs=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 zs=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 _(i.toString(),t)},"SetQueryParamsInboundPolicy");var js=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 yl=s(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),Vs=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 yl(n.sleepInMs),t},"SleepInboundPolicy");var Gs=s(async(t,e,n,r)=>{q(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 _))throw new L("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 Ks=s(async(t,e,n,r)=>{q(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await $(r,n),i=new M(o,{logger:T.getLogger(e)}),a=await i.get(r);if(!a){let u=await bl(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 bl(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await le({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(bl,"getAccessToken");var Ws="https://accounts.google.com/o/oauth2/token",Gr,Js=s(async(t,e,n,r)=>{q(n,r).required("serviceAccountJson","string"),Gr||(Gr=await W.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 M(i,{logger:T.getLogger(e)}),u=await a.get(r);if(!u){let c=await ie({serviceAccount:Gr,audience:Ws,payload:o}),l=await kt(Ws,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 wl="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Rl=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Kr,Ys=s(async(t,e,n,r)=>{if(q(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(Rl.indexOf(p)!==-1)throw new g(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}Kr||(Kr=await W.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 $(r,n),u=new M(a,{logger:T.getLogger(e)}),c={uid:i,claims:o},l=await sn(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await ie({serviceAccount:Kr,audience:wl,payload:c}),b=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,m=await si(b,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!m.idToken)throw new P("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 Wr,Qs=s(async(t,e,n,r)=>{q(n,r).required("audience","string").required("serviceAccountJson","string"),Wr||(Wr=await W.init(n.serviceAccountJson));let o=await ie({serviceAccount:Wr,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var Xs="https://www.googleapis.com/oauth2/v4/token",Jr,ea=s(async(t,e,n,r)=>{q(n,r).required("audience","string").required("serviceAccountJson","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Jr||(Jr=await W.init(n.serviceAccountJson));let o=await $(r,n),i;n.useMemoryCacheOnly?i=new Te(o):i=new M(o,e);let a=await i.get(r);if(!a){let u=await ie({serviceAccount:Jr,audience:Xs,payload:{target_audience:`${n.audience}`}}),{id_token:c}=await kt(Xs,u,{retries:n.tokenRetries??3,retryDelayMs:10});if(!c)throw new P("Invalid token response from GCP");a=c,i.put(r,a,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamGcpServiceAuthInboundPolicy");var ta=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 L("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 na=s(async(t,e,n,r)=>{let o=T.getLogger(e);e.addResponseSendingFinalHook(async(d,p,b)=>{let m=de.get(b,"subscription");if((n.allowRequestsWithoutSubscription??!1)&&!m)return;if(!n.bucketId)if(Z.ZUPLO_METERING_SERVICE_BUCKET_ID)n.bucketId=Z.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`MeteringInboundPolicy '${r}' - no bucketId property provided`);let{authApiJWT:I,meteringServiceUrl:E}=h.instance;if(d.ok&&m&&n.meters)try{let x=await fetch(`${E}/internal/v1/metering/${n.bucketId}/subscriptions/${m.id}/quotas/consume`,{headers:{Authorization:`Bearer ${I}`,"zp-rid":b.requestId},method:"POST",body:JSON.stringify({meters:n.meters})});x.ok||(b.log.error(`MeteringInboundPolicy '${r}' -error in serviceResponse: ${x.status} - ${x.statusText}`),o.error(`MeteringInboundPolicy '${r}' -error in serviceResponse: ${x.status} - ${x.statusText}`))}catch(x){b.log.error(`MeteringInboundPolicy '${r}' -error in serviceResponse`),o.error(`MeteringInboundPolicy '${r}' -error in serviceResponse`,x)}});let i=de.get(e,"subscription"),a=n.allowRequestsWithoutSubscription??!1,u=n.allowRequestsOverQuota??!1;if(!i){if(a)return t;throw new g("Subscription is not available for user")}if(i&&Object.keys(i.quotas).length===0)throw new g("Quota is not set up for the user's subscription");let l=Object.keys(n.meters).filter(d=>!Object.keys(i.quotas).includes(d));if(l.length>0)throw new g(`The following policy meters are not present in the subscription: ${l.join(", ")}`);for(let d of Object.keys(i.quotas))if(i.quotas[d]<=0&&!u)return R.tooManyRequests(t,e,{detail:`Quota exceeded for meter '${d}'`,title:"Quota Exceeded"});return t},"MeteringInboundPolicy");var ra=s(async(t,e,n,r)=>{let o=T.getLogger(e),i=n.allowRequestsWithoutSubscription??!1,a=t.user;if(!a)return i?t:R.unauthorized(t,e,{detail:"Unable to check subscription for anonymous user"});if(!n.bucketId)if(Z.ZUPLO_METERING_SERVICE_BUCKET_ID)n.bucketId=Z.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`LoadSubscriptionInboundPolicy '${r}' - no bucketId property provided`);let{authApiJWT:u,meteringServiceUrl:c}=h.instance,{sub:l}=a,d,p;try{if(d=await fetch(`${c}/internal/v1/metering/${n.bucketId}/subscriptions?customerKey=${l}&status=active`,{headers:{Authorization:`Bearer ${u}`,"zp-rid":e.requestId},method:"GET"}),!d.ok)return e.log.error(await d.text()),R.forbidden(t,e);p=await d.json()}catch(m){o.error(`LoadSubscriptionInboundPolicy '${r}' -error in serviceResponse`,m)}if((!p||!p.data||p.data.length===0)&&!i)return R.unauthorized(t,e,{detail:"No valid, active subscription found"});if((!p||!p.data||p.data.length===0)&&i)return t;let b=p&&p.data?p.data[0]:void 0;return de.set(e,"subscription",b),t},"LoadSubscriptionInboundPolicy");var fn=class t{static{s(this,"ServiceProviderImpl")}static#e;services=new Map;constructor(){}static getInstance(){return t.#e||(t.#e=new t),t.#e}setInstance(e){t.#e=e}addService(e,n){if(this.services.get(e))throw new L(`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 Yr=["sha-1","sha-256","sha-384","sha-512"],hn=class{static{s(this,"BaseCryptoBeta")}};var yn=class extends hn{static{s(this,"WorkerCryptoBeta")}async digest(e,n){if(!Yr.includes(e.toLowerCase()))throw new P(`Algorithm ${e} is not supported. Try using ${Yr.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 bn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var wn=class extends bn{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=globalThis.ZUPLO_KV;if(!r)throw new lt("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)}};
72
72
  /*! For license information please see index.minified.js.LEGAL.txt */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zuplo/runtime",
3
- "version": "5.1724.0",
3
+ "version": "5.1725.0",
4
4
  "repository": "https://github.com/zuplo/zuplo",
5
5
  "author": "Zuplo, Inc.",
6
6
  "exports": {