@zuplo/runtime 5.1680.0 → 5.1682.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.d.ts CHANGED
@@ -2297,6 +2297,34 @@ declare interface KeyValueStorePutOptions {
2297
2297
  expirationSecondsTtl?: number;
2298
2298
  }
2299
2299
 
2300
+ /**
2301
+ * Load subscription on requests.
2302
+ *
2303
+ * @title Load Subscription
2304
+ * @public
2305
+ * @paidAddOn
2306
+ * @param request - The ZuploRequest
2307
+ * @param context - The ZuploContext
2308
+ * @param options - The policy options set in policies.json
2309
+ * @param policyName - The name of the policy as set in policies.json
2310
+ * @returns A Request or a Response
2311
+ */
2312
+ export declare const LoadSubscriptionInboundPolicy: InboundPolicyHandler<LoadSubscriptionInboundPolicyOptions>;
2313
+
2314
+ /**
2315
+ * The options for this policy.
2316
+ */
2317
+ export declare interface LoadSubscriptionInboundPolicyOptions {
2318
+ /**
2319
+ * Indicates if requests without subscription should be allowed or not.
2320
+ */
2321
+ allowRequestsWithoutSubscription?: boolean;
2322
+ /**
2323
+ * Indicates the bucket to be used, overrides the default one.
2324
+ */
2325
+ bucketId?: string;
2326
+ }
2327
+
2300
2328
  /**
2301
2329
  * @beta
2302
2330
  */
@@ -2387,6 +2415,44 @@ export declare class MemoryZoneReadThroughCache<T = unknown> {
2387
2415
  put(key: string, data: T, ttlSeconds: number): void;
2388
2416
  }
2389
2417
 
2418
+ /**
2419
+ * Enforce metering policies on requests.
2420
+ *
2421
+ * @title Metering
2422
+ * @public
2423
+ * @paidAddOn
2424
+ * @param request - The ZuploRequest
2425
+ * @param context - The ZuploContext
2426
+ * @param options - The policy options set in policies.json
2427
+ * @param policyName - The name of the policy as set in policies.json
2428
+ * @returns A Request or a Response
2429
+ */
2430
+ export declare const MeteringInboundPolicy: InboundPolicyHandler<MeteringInboundPolicyOptions>;
2431
+
2432
+ /**
2433
+ * The options for this policy.
2434
+ */
2435
+ export declare interface MeteringInboundPolicyOptions {
2436
+ /**
2437
+ * Indicates if requests without subscription should be allowed or not..
2438
+ */
2439
+ allowRequestsWithoutSubscription?: boolean;
2440
+ /**
2441
+ * Indicates the bucket to be used, overrides the default one.
2442
+ */
2443
+ bucketId?: string;
2444
+ /**
2445
+ * The meters to be used by the policy against the subscription quota.
2446
+ */
2447
+ meters: {
2448
+ /**
2449
+ * This interface was referenced by `undefined`'s JSON-Schema definition
2450
+ * via the `patternProperty` "^.*$".
2451
+ */
2452
+ [k: string]: number;
2453
+ };
2454
+ }
2455
+
2390
2456
  /* Excluded from this release type: MeteringPlugin */
2391
2457
 
2392
2458
  /* Excluded from this release type: MetricsData */
package/index.minified.js CHANGED
@@ -22,17 +22,17 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- "use strict";var ta=Object.create;var Fe=Object.defineProperty;var na=Object.getOwnPropertyDescriptor;var ra=Object.getOwnPropertyNames;var oa=Object.getPrototypeOf,ia=Object.prototype.hasOwnProperty;var s=(t,e)=>Fe(t,"name",{value:e,configurable:!0});var $e=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),sa=(t,e)=>{for(var n in e)Fe(t,n,{get:e[n],enumerable:!0})},Qr=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ra(e))!ia.call(t,o)&&o!==n&&Fe(t,o,{get:()=>e[o],enumerable:!(r=na(e,o))||r.enumerable});return t};var Ie=(t,e,n)=>(n=t!=null?ta(oa(t)):{},Qr(e||!t||!t.__esModule?Fe(n,"default",{value:t,enumerable:!0}):n,t)),aa=t=>Qr(Fe({},"__esModule",{value:!0}),t);var wo=$e(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.generateColor=h.colorFunctions=h.stripColor=h.bgRgb24=h.rgb24=h.bgRgb8=h.rgb8=h.bgBrightWhite=h.bgBrightCyan=h.bgBrightMagenta=h.bgBrightBlue=h.bgBrightYellow=h.bgBrightGreen=h.bgBrightRed=h.bgBrightBlack=h.bgWhite=h.bgCyan=h.bgMagenta=h.bgBlue=h.bgYellow=h.bgGreen=h.bgRed=h.bgBlack=h.brightWhite=h.brightCyan=h.brightMagenta=h.brightBlue=h.brightYellow=h.brightGreen=h.brightRed=h.brightBlack=h.gray=h.white=h.cyan=h.magenta=h.blue=h.yellow=h.green=h.red=h.black=h.strikethrough=h.hidden=h.inverse=h.underline=h.italic=h.dim=h.bold=h.reset=h.getColorEnabled=h.setColorEnabled=void 0;var po=!0,Hn=!po;function ua(t){po||(Hn=t)}s(ua,"setColorEnabled");h.setColorEnabled=ua;function ca(){return Hn}s(ca,"getColorEnabled");h.getColorEnabled=ca;function x(t,e){return{open:`\x1B[${t.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}s(x,"code");function O(t,e){return Hn?`${e.open}${t.replace(e.regexp,e.open)}${e.close}`:t}s(O,"run");function la(t){return O(t,x([0],0))}s(la,"reset");h.reset=la;function da(t){return O(t,x([1],22))}s(da,"bold");h.bold=da;function pa(t){return O(t,x([2],22))}s(pa,"dim");h.dim=pa;function ma(t){return O(t,x([3],23))}s(ma,"italic");h.italic=ma;function ga(t){return O(t,x([4],24))}s(ga,"underline");h.underline=ga;function fa(t){return O(t,x([7],27))}s(fa,"inverse");h.inverse=fa;function ha(t){return O(t,x([8],28))}s(ha,"hidden");h.hidden=ha;function ya(t){return O(t,x([9],29))}s(ya,"strikethrough");h.strikethrough=ya;function ba(t){return O(t,x([30],39))}s(ba,"black");h.black=ba;function mo(t){return O(t,x([31],39))}s(mo,"red");h.red=mo;function go(t){return O(t,x([32],39))}s(go,"green");h.green=go;function fo(t){return O(t,x([33],39))}s(fo,"yellow");h.yellow=fo;function ho(t){return O(t,x([34],39))}s(ho,"blue");h.blue=ho;function yo(t){return O(t,x([35],39))}s(yo,"magenta");h.magenta=yo;function bo(t){return O(t,x([36],39))}s(bo,"cyan");h.cyan=bo;function Ra(t){return O(t,x([37],39))}s(Ra,"white");h.white=Ra;function wa(t){return Ro(t)}s(wa,"gray");h.gray=wa;function Ro(t){return O(t,x([90],39))}s(Ro,"brightBlack");h.brightBlack=Ro;function Pa(t){return O(t,x([91],39))}s(Pa,"brightRed");h.brightRed=Pa;function Ea(t){return O(t,x([92],39))}s(Ea,"brightGreen");h.brightGreen=Ea;function Ia(t){return O(t,x([93],39))}s(Ia,"brightYellow");h.brightYellow=Ia;function xa(t){return O(t,x([94],39))}s(xa,"brightBlue");h.brightBlue=xa;function Oa(t){return O(t,x([95],39))}s(Oa,"brightMagenta");h.brightMagenta=Oa;function va(t){return O(t,x([96],39))}s(va,"brightCyan");h.brightCyan=va;function Ta(t){return O(t,x([97],39))}s(Ta,"brightWhite");h.brightWhite=Ta;function Ca(t){return O(t,x([40],49))}s(Ca,"bgBlack");h.bgBlack=Ca;function Aa(t){return O(t,x([41],49))}s(Aa,"bgRed");h.bgRed=Aa;function Sa(t){return O(t,x([42],49))}s(Sa,"bgGreen");h.bgGreen=Sa;function La(t){return O(t,x([43],49))}s(La,"bgYellow");h.bgYellow=La;function _a(t){return O(t,x([44],49))}s(_a,"bgBlue");h.bgBlue=_a;function Da(t){return O(t,x([45],49))}s(Da,"bgMagenta");h.bgMagenta=Da;function ka(t){return O(t,x([46],49))}s(ka,"bgCyan");h.bgCyan=ka;function Ha(t){return O(t,x([47],49))}s(Ha,"bgWhite");h.bgWhite=Ha;function Ua(t){return O(t,x([100],49))}s(Ua,"bgBrightBlack");h.bgBrightBlack=Ua;function Na(t){return O(t,x([101],49))}s(Na,"bgBrightRed");h.bgBrightRed=Na;function Ma(t){return O(t,x([102],49))}s(Ma,"bgBrightGreen");h.bgBrightGreen=Ma;function Za(t){return O(t,x([103],49))}s(Za,"bgBrightYellow");h.bgBrightYellow=Za;function qa(t){return O(t,x([104],49))}s(qa,"bgBrightBlue");h.bgBrightBlue=qa;function Fa(t){return O(t,x([105],49))}s(Fa,"bgBrightMagenta");h.bgBrightMagenta=Fa;function $a(t){return O(t,x([106],49))}s($a,"bgBrightCyan");h.bgBrightCyan=$a;function za(t){return O(t,x([107],49))}s(za,"bgBrightWhite");h.bgBrightWhite=za;function ae(t,e=255,n=0){return Math.trunc(Math.max(Math.min(t,e),n))}s(ae,"clampAndTruncate");function Ga(t,e){return O(t,x([38,5,ae(e)],39))}s(Ga,"rgb8");h.rgb8=Ga;function Ba(t,e){return O(t,x([48,5,ae(e)],49))}s(Ba,"bgRgb8");h.bgRgb8=Ba;function Va(t,e){return typeof e=="number"?O(t,x([38,2,e>>16&255,e>>8&255,e&255],39)):O(t,x([38,2,ae(e.r),ae(e.g),ae(e.b)],39))}s(Va,"rgb24");h.rgb24=Va;function ja(t,e){return typeof e=="number"?O(t,x([48,2,e>>16&255,e>>8&255,e&255],49)):O(t,x([48,2,ae(e.r),ae(e.g),ae(e.b)],49))}s(ja,"bgRgb24");h.bgRgb24=ja;var Ja=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 Wa(t){return t.replace(Ja,"")}s(Wa,"stripColor");h.stripColor=Wa;h.colorFunctions=[mo,go,fo,ho,yo,bo];function Ka(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(Ka,"hashCode");function Ya(t){let e=Math.abs(Ka(t));return h.colorFunctions[e%h.colorFunctions.length]}s(Ya,"generateColor");h.generateColor=Ya});var Po=$e(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.format=void 0;function Qa(t,e,...n){let r=0,o=n.length,i=String(e).replace(/%[sdjoO%]/g,a=>{if(a==="%%")return"%";if(r>=o)return a;switch(a){case"%s":return String(n[r++]);case"%d":return Number(n[r++]).toString();case"%o":return t(n[r++]).split(`
26
- `).map(u=>u.trim()).join(" ");case"%O":return t(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch{return"[Circular]"}default:return a}});for(let a of n.splice(r))a===null||!(typeof a=="object"&&a!==null)?i+=" "+a:i+=" "+t(a);return i}s(Qa,"format");dt.format=Qa});var To=$e(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.inspect=void 0;function he(t,e,n,r){let o={seen:[],stylize:Xa,showHidden:e??!1,depth:n??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=tu),pt(o,t,o.depth)}s(he,"inspect");mt.inspect=he;he.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]};he.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function Xa(t,e){return t}s(Xa,"stylizeNoColor");function eu(t){return typeof t=="boolean"}s(eu,"isBoolean");function Io(t){return t===void 0}s(Io,"isUndefined");function tu(t,e){let n=he.styles[e];return n?"\x1B["+he.colors[n][0]+"m"+t+"\x1B["+he.colors[n][1]+"m":t}s(tu,"stylizeWithColor");function Un(t){return typeof t=="function"}s(Un,"isFunction");function xo(t){return typeof t=="string"}s(xo,"isString");function nu(t){return typeof t=="number"}s(nu,"isNumber");function Oo(t){return t===null}s(Oo,"isNull");function vo(t,e){return Object.prototype.hasOwnProperty.call(t,e)}s(vo,"hasOwn");function Nn(t){return Fn(t)&&$n(t)==="[object RegExp]"}s(Nn,"isRegExp");function Fn(t){return typeof t=="object"&&t!==null}s(Fn,"isObject");function Mn(t){return Fn(t)&&($n(t)==="[object Error]"||t instanceof Error)}s(Mn,"isError");function Eo(t){return Fn(t)&&$n(t)==="[object Date]"}s(Eo,"isDate");function $n(t){return Object.prototype.toString.call(t)}s($n,"objectToString");function ru(t){let e={};return t.forEach(function(n,r){e[n]=!0}),e}s(ru,"arrayToHash");function ou(t,e,n,r,o){let i=[];for(let a=0,u=e.length;a<u;++a)vo(e,String(a))?i.push(qn(t,e,n,r,String(a),!0)):i.push("");return o.forEach(function(a){a.match(/^\d+$/)||i.push(qn(t,e,n,r,a,!0))}),i}s(ou,"formatArray");function Zn(t){return"["+Error.prototype.toString.call(t)+"]"}s(Zn,"formatError");function pt(t,e,n){if(t.customInspect&&e&&Un(e.inspect)&&e.inspect!==he&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(n,t);return xo(d)||(d=pt(t,d,n)),d}let r=iu(t,e);if(r)return r;let o=Object.keys(e),i=ru(o);try{t.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(Mn(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return Zn(e);if(o.length===0){if(Un(e)){let d=e.name?": "+e.name:"";return t.stylize("[Function"+d+"]","special")}if(Nn(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(Eo(e))return t.stylize(Date.prototype.toString.call(e),"date");if(Mn(e))return Zn(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),Un(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),Nn(e)&&(a=" "+RegExp.prototype.toString.call(e)),Eo(e)&&(a=" "+Date.prototype.toUTCString.call(e)),Mn(e)&&(a=" "+Zn(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(n<0)return Nn(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special");t.seen.push(e);let l;return u?l=ou(t,e,n,i,o):l=o.map(function(d){return qn(t,e,n,i,d,u)}),t.seen.pop(),su(l,a,c)}s(pt,"formatValue");function qn(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")),vo(r,o)||(a="["+o+"]"),u||(t.seen.indexOf(c.value)<0?(Oo(n)?u=pt(t,c.value,null):u=pt(t,c.value,n-1),u.indexOf(`
25
+ "use strict";var ra=Object.create;var $e=Object.defineProperty;var oa=Object.getOwnPropertyDescriptor;var ia=Object.getOwnPropertyNames;var sa=Object.getPrototypeOf,aa=Object.prototype.hasOwnProperty;var s=(t,e)=>$e(t,"name",{value:e,configurable:!0});var je=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ua=(t,e)=>{for(var n in e)$e(t,n,{get:e[n],enumerable:!0})},Qr=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ia(e))!aa.call(t,o)&&o!==n&&$e(t,o,{get:()=>e[o],enumerable:!(r=oa(e,o))||r.enumerable});return t};var xe=(t,e,n)=>(n=t!=null?ra(sa(t)):{},Qr(e||!t||!t.__esModule?$e(n,"default",{value:t,enumerable:!0}):n,t)),ca=t=>Qr($e({},"__esModule",{value:!0}),t);var wo=je(b=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});b.generateColor=b.colorFunctions=b.stripColor=b.bgRgb24=b.rgb24=b.bgRgb8=b.rgb8=b.bgBrightWhite=b.bgBrightCyan=b.bgBrightMagenta=b.bgBrightBlue=b.bgBrightYellow=b.bgBrightGreen=b.bgBrightRed=b.bgBrightBlack=b.bgWhite=b.bgCyan=b.bgMagenta=b.bgBlue=b.bgYellow=b.bgGreen=b.bgRed=b.bgBlack=b.brightWhite=b.brightCyan=b.brightMagenta=b.brightBlue=b.brightYellow=b.brightGreen=b.brightRed=b.brightBlack=b.gray=b.white=b.cyan=b.magenta=b.blue=b.yellow=b.green=b.red=b.black=b.strikethrough=b.hidden=b.inverse=b.underline=b.italic=b.dim=b.bold=b.reset=b.getColorEnabled=b.setColorEnabled=void 0;var po=!0,Hn=!po;function la(t){po||(Hn=t)}s(la,"setColorEnabled");b.setColorEnabled=la;function da(){return Hn}s(da,"getColorEnabled");b.getColorEnabled=da;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 Hn?`${e.open}${t.replace(e.regexp,e.open)}${e.close}`:t}s(O,"run");function pa(t){return O(t,v([0],0))}s(pa,"reset");b.reset=pa;function ma(t){return O(t,v([1],22))}s(ma,"bold");b.bold=ma;function ga(t){return O(t,v([2],22))}s(ga,"dim");b.dim=ga;function fa(t){return O(t,v([3],23))}s(fa,"italic");b.italic=fa;function ha(t){return O(t,v([4],24))}s(ha,"underline");b.underline=ha;function ya(t){return O(t,v([7],27))}s(ya,"inverse");b.inverse=ya;function ba(t){return O(t,v([8],28))}s(ba,"hidden");b.hidden=ba;function Ra(t){return O(t,v([9],29))}s(Ra,"strikethrough");b.strikethrough=Ra;function wa(t){return O(t,v([30],39))}s(wa,"black");b.black=wa;function mo(t){return O(t,v([31],39))}s(mo,"red");b.red=mo;function go(t){return O(t,v([32],39))}s(go,"green");b.green=go;function fo(t){return O(t,v([33],39))}s(fo,"yellow");b.yellow=fo;function ho(t){return O(t,v([34],39))}s(ho,"blue");b.blue=ho;function yo(t){return O(t,v([35],39))}s(yo,"magenta");b.magenta=yo;function bo(t){return O(t,v([36],39))}s(bo,"cyan");b.cyan=bo;function Pa(t){return O(t,v([37],39))}s(Pa,"white");b.white=Pa;function Ea(t){return Ro(t)}s(Ea,"gray");b.gray=Ea;function Ro(t){return O(t,v([90],39))}s(Ro,"brightBlack");b.brightBlack=Ro;function Ia(t){return O(t,v([91],39))}s(Ia,"brightRed");b.brightRed=Ia;function xa(t){return O(t,v([92],39))}s(xa,"brightGreen");b.brightGreen=xa;function va(t){return O(t,v([93],39))}s(va,"brightYellow");b.brightYellow=va;function Oa(t){return O(t,v([94],39))}s(Oa,"brightBlue");b.brightBlue=Oa;function Ta(t){return O(t,v([95],39))}s(Ta,"brightMagenta");b.brightMagenta=Ta;function Sa(t){return O(t,v([96],39))}s(Sa,"brightCyan");b.brightCyan=Sa;function Ca(t){return O(t,v([97],39))}s(Ca,"brightWhite");b.brightWhite=Ca;function Aa(t){return O(t,v([40],49))}s(Aa,"bgBlack");b.bgBlack=Aa;function La(t){return O(t,v([41],49))}s(La,"bgRed");b.bgRed=La;function _a(t){return O(t,v([42],49))}s(_a,"bgGreen");b.bgGreen=_a;function ka(t){return O(t,v([43],49))}s(ka,"bgYellow");b.bgYellow=ka;function Da(t){return O(t,v([44],49))}s(Da,"bgBlue");b.bgBlue=Da;function Ha(t){return O(t,v([45],49))}s(Ha,"bgMagenta");b.bgMagenta=Ha;function Ua(t){return O(t,v([46],49))}s(Ua,"bgCyan");b.bgCyan=Ua;function Na(t){return O(t,v([47],49))}s(Na,"bgWhite");b.bgWhite=Na;function Ma(t){return O(t,v([100],49))}s(Ma,"bgBrightBlack");b.bgBrightBlack=Ma;function Za(t){return O(t,v([101],49))}s(Za,"bgBrightRed");b.bgBrightRed=Za;function qa(t){return O(t,v([102],49))}s(qa,"bgBrightGreen");b.bgBrightGreen=qa;function Fa(t){return O(t,v([103],49))}s(Fa,"bgBrightYellow");b.bgBrightYellow=Fa;function $a(t){return O(t,v([104],49))}s($a,"bgBrightBlue");b.bgBrightBlue=$a;function ja(t){return O(t,v([105],49))}s(ja,"bgBrightMagenta");b.bgBrightMagenta=ja;function za(t){return O(t,v([106],49))}s(za,"bgBrightCyan");b.bgBrightCyan=za;function Ba(t){return O(t,v([107],49))}s(Ba,"bgBrightWhite");b.bgBrightWhite=Ba;function ce(t,e=255,n=0){return Math.trunc(Math.max(Math.min(t,e),n))}s(ce,"clampAndTruncate");function Ga(t,e){return O(t,v([38,5,ce(e)],39))}s(Ga,"rgb8");b.rgb8=Ga;function Va(t,e){return O(t,v([48,5,ce(e)],49))}s(Va,"bgRgb8");b.bgRgb8=Va;function Wa(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,ce(e.r),ce(e.g),ce(e.b)],39))}s(Wa,"rgb24");b.rgb24=Wa;function Ja(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,ce(e.r),ce(e.g),ce(e.b)],49))}s(Ja,"bgRgb24");b.bgRgb24=Ja;var Ka=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 Ya(t){return t.replace(Ka,"")}s(Ya,"stripColor");b.stripColor=Ya;b.colorFunctions=[mo,go,fo,ho,yo,bo];function Qa(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(Qa,"hashCode");function Xa(t){let e=Math.abs(Qa(t));return b.colorFunctions[e%b.colorFunctions.length]}s(Xa,"generateColor");b.generateColor=Xa});var Po=je(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.format=void 0;function eu(t,e,...n){let r=0,o=n.length,i=String(e).replace(/%[sdjoO%]/g,a=>{if(a==="%%")return"%";if(r>=o)return a;switch(a){case"%s":return String(n[r++]);case"%d":return Number(n[r++]).toString();case"%o":return t(n[r++]).split(`
26
+ `).map(u=>u.trim()).join(" ");case"%O":return t(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch{return"[Circular]"}default:return a}});for(let a of n.splice(r))a===null||!(typeof a=="object"&&a!==null)?i+=" "+a:i+=" "+t(a);return i}s(eu,"format");pt.format=eu});var To=je(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.inspect=void 0;function ye(t,e,n,r){let o={seen:[],stylize:tu,showHidden:e??!1,depth:n??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=ru),mt(o,t,o.depth)}s(ye,"inspect");gt.inspect=ye;ye.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]};ye.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function tu(t,e){return t}s(tu,"stylizeNoColor");function nu(t){return typeof t=="boolean"}s(nu,"isBoolean");function Io(t){return t===void 0}s(Io,"isUndefined");function ru(t,e){let n=ye.styles[e];return n?"\x1B["+ye.colors[n][0]+"m"+t+"\x1B["+ye.colors[n][1]+"m":t}s(ru,"stylizeWithColor");function Un(t){return typeof t=="function"}s(Un,"isFunction");function xo(t){return typeof t=="string"}s(xo,"isString");function ou(t){return typeof t=="number"}s(ou,"isNumber");function vo(t){return t===null}s(vo,"isNull");function Oo(t,e){return Object.prototype.hasOwnProperty.call(t,e)}s(Oo,"hasOwn");function Nn(t){return Fn(t)&&$n(t)==="[object RegExp]"}s(Nn,"isRegExp");function Fn(t){return typeof t=="object"&&t!==null}s(Fn,"isObject");function Mn(t){return Fn(t)&&($n(t)==="[object Error]"||t instanceof Error)}s(Mn,"isError");function Eo(t){return Fn(t)&&$n(t)==="[object Date]"}s(Eo,"isDate");function $n(t){return Object.prototype.toString.call(t)}s($n,"objectToString");function iu(t){let e={};return t.forEach(function(n,r){e[n]=!0}),e}s(iu,"arrayToHash");function su(t,e,n,r,o){let i=[];for(let a=0,u=e.length;a<u;++a)Oo(e,String(a))?i.push(qn(t,e,n,r,String(a),!0)):i.push("");return o.forEach(function(a){a.match(/^\d+$/)||i.push(qn(t,e,n,r,a,!0))}),i}s(su,"formatArray");function Zn(t){return"["+Error.prototype.toString.call(t)+"]"}s(Zn,"formatError");function mt(t,e,n){if(t.customInspect&&e&&Un(e.inspect)&&e.inspect!==ye&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(n,t);return xo(d)||(d=mt(t,d,n)),d}let r=au(t,e);if(r)return r;let o=Object.keys(e),i=iu(o);try{t.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(Mn(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return Zn(e);if(o.length===0){if(Un(e)){let d=e.name?": "+e.name:"";return t.stylize("[Function"+d+"]","special")}if(Nn(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(Eo(e))return t.stylize(Date.prototype.toString.call(e),"date");if(Mn(e))return Zn(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),Un(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),Nn(e)&&(a=" "+RegExp.prototype.toString.call(e)),Eo(e)&&(a=" "+Date.prototype.toUTCString.call(e)),Mn(e)&&(a=" "+Zn(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(n<0)return Nn(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special");t.seen.push(e);let l;return u?l=su(t,e,n,i,o):l=o.map(function(d){return qn(t,e,n,i,d,u)}),t.seen.pop(),uu(l,a,c)}s(mt,"formatValue");function qn(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")),Oo(r,o)||(a="["+o+"]"),u||(t.seen.indexOf(c.value)<0?(vo(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(`
29
29
  `).substr(2):u=`
30
30
  `+u.split(`
31
31
  `).map(function(l){return" "+l}).join(`
32
- `))):u=t.stylize("[Circular]","special")),Io(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(qn,"formatProperty");function iu(t,e){if(Io(e))return t.stylize("undefined","undefined");if(xo(e)){let n="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(n,"string")}if(nu(e))return t.stylize(""+e,"number");if(eu(e))return t.stylize(""+e,"boolean");if(Oo(e))return t.stylize("null","null")}s(iu,"formatPrimitive");function su(t,e,n){let r=0;return t.reduce(function(i,a){return r++,a.indexOf(`
32
+ `))):u=t.stylize("[Circular]","special")),Io(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(qn,"formatProperty");function au(t,e){if(Io(e))return t.stylize("undefined","undefined");if(xo(e)){let n="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(n,"string")}if(ou(e))return t.stylize(""+e,"number");if(nu(e))return t.stylize(""+e,"boolean");if(vo(e))return t.stylize("null","null")}s(au,"formatPrimitive");function uu(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(su,"reduceToSingleString")});var Co=$e(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.format=void 0;var au=Po(),uu=To(),cu=s((t,...e)=>(0,au.format)(uu.inspect,t,e),"format");gt.format=cu});var ye=$e(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.debug=ue.withoutEnv=ue.Debugger=void 0;var lu=wo(),du=Co(),ft=class{static{s(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,n){this.manager=e,this.ns=n,this.color=(0,lu.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,du.format)(n,...e);let i=`${this.color(this.ns)} ${n} ${this.color(`+${o}ms`)}`;console.log(i),this.last=Date.now()}};ue.Debugger=ft;var ht=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 Ge;function pu(t){t||(t=[]),typeof t=="string"&&(t=Ao(t)),Ge=new ht(t)}s(pu,"withoutEnv");ue.withoutEnv=pu;function mu(t){let e=globalThis.DEBUG;Ge||(Ge=new ht(Ao(e)));let n=new ft(Ge,t);return Ge.debuggers.set(t,n),Object.assign(n.log.bind(n),{self:n})}s(mu,"debug");ue.debug=mu});var pl={};sa(pl,{API_KEY:()=>ni,AWSLoggingPlugin:()=>Kt,AmberfloMeteringInboundPolicy:()=>Gi,AmberfloMeteringPolicy:()=>rn,ApiAuthKeyInboundPolicy:()=>ji,ApiKeyInboundPolicy:()=>sn,AuditLogDataStaxProvider:()=>Xt,AuditLogPlugin:()=>en,Auth0JwtInboundPolicy:()=>Ji,AwsLambdaHandlerExtensions:()=>Si,BasicAuthInboundPolicy:()=>Wi,BasicRateLimitInboundPolicy:()=>$r,CachingInboundPolicy:()=>Ki,ChangeMethodInboundPolicy:()=>Yi,ClearHeadersInboundPolicy:()=>Qi,ClearHeadersOutboundPolicy:()=>Xi,ClerkJwtInboundPolicy:()=>es,CognitoJwtInboundPolicy:()=>ts,CompositeInboundPolicy:()=>ns,ConfigurationError:()=>f,ContentTypes:()=>Rt,ContextData:()=>zt,CreditsMeteringInboundPolicy:()=>rs,CryptoBeta:()=>hn,CurityPhantomTokenInboundPolicy:()=>os,DataDogLoggingPlugin:()=>Ht,DataDogMetricsPlugin:()=>Yt,DynaTraceLoggingPlugin:()=>Vt,DynatraceMetricsPlugin:()=>Qt,FirebaseJwtInboundPolicy:()=>is,FormDataToJsonInboundPolicy:()=>ss,GeoFilterInboundPolicy:()=>as,GoogleCloudLoggingPlugin:()=>_t,Handler:()=>Gt,HttpProblems:()=>w,HttpStatusCode:()=>Et,JWTScopeValidationInboundPolicy:()=>us,KeyValueStore:()=>bn,LokiLoggingPlugin:()=>jt,LookupResult:()=>Se,MemoryZoneReadThroughCache:()=>N,MockApiInboundPolicy:()=>ls,MoesifInboundPolicy:()=>hs,OktaJwtInboundPolicy:()=>ys,OpenIdJwtInboundPolicy:()=>q,ProblemResponseFormatter:()=>ce,PropelAuthJwtInboundPolicy:()=>Rs,RateLimitInboundPolicy:()=>$r,ReadmeMetricsInboundPolicy:()=>xs,RemoveHeadersInboundPolicy:()=>Os,RemoveHeadersOutboundPolicy:()=>vs,RemoveQueryParamsInboundPolicy:()=>Ts,ReplaceStringOutboundPolicy:()=>Cs,RequestSizeLimitInboundPolicy:()=>Ss,RequestValidationInboundPolicy:()=>Br,RequireOriginInboundPolicy:()=>Ms,ResponseSendingEvent:()=>ve,ResponseSentEvent:()=>Te,Router:()=>Le,SYSTEM_LOGGER:()=>Ye,SchemaBasedRequestValidation:()=>Ns,ServiceProviderImpl:()=>gn,SetBodyInboundPolicy:()=>Zs,SetHeadersInboundPolicy:()=>qs,SetHeadersOutboundPolicy:()=>Fs,SetQueryParamsInboundPolicy:()=>$s,SetStatusOutboundPolicy:()=>zs,SleepInboundPolicy:()=>Gs,StripeMeteringPlugin:()=>kr,StripeWebhookInboundPolicy:()=>tn,SumoLogicLoggingPlugin:()=>Jt,SupabaseJwtInboundPolicy:()=>Bs,SystemLogMap:()=>A,SystemRouteName:()=>ee,UpstreamAzureAdServiceAuthInboundPolicy:()=>Vs,UpstreamFirebaseAdminAuthInboundPolicy:()=>Js,UpstreamFirebaseUserAuthInboundPolicy:()=>Ws,UpstreamGcpJwtInboundPolicy:()=>Ks,UpstreamGcpServiceAuthInboundPolicy:()=>Qs,VMWareLogInsightLoggingPlugin:()=>Wt,ValidateJsonSchemaInbound:()=>Xs,ZoneCache:()=>se,ZuploRequest:()=>S,awsLambdaHandler:()=>Li,environment:()=>ot,getIdForParameterSchema:()=>pn,getIdForRefSchema:()=>_s,getIdForRequestBodySchema:()=>mn,getRawOperationDataIdentifierName:()=>Ls,httpStatuses:()=>It,isRestrictedEnvVariableName:()=>lr,isZuploReadableEnvVariableName:()=>dr,openApiSpecHandler:()=>_i,originalFetch:()=>_e,purgeGatewayCache:()=>Ri,redirectHandler:()=>Di,sanitizedIdentifierName:()=>fe,serialize:()=>wt,setMoesifContext:()=>fs,urlForwardHandler:()=>ki,urlRewriteHandler:()=>Hi,webSocketHandler:()=>Ui,webSocketPipelineHandler:()=>Zi});module.exports=aa(pl);var _=class extends Error{static{s(this,"SystemError")}constructor(e,n){super(e,n),this.name="InternalError"}},I=class extends Error{static{s(this,"RuntimeError")}extensionMembers;constructor(e,n){typeof e=="string"?super(e,n):(super(e.message,n),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},f=class extends I{static{s(this,"ConfigurationError")}constructor(e,n){super(e,n),this.name="ConfigurationError"}},ct=class extends I{static{s(this,"FeatureNotEnabledError")}constructor(e,n){super(e,n),this.name="FeatureNotEnabledError"}};var y=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 _("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.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_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 lt=globalThis,Xr=lt.caches;if(Xr){let t=Xr.open;lt.caches.open=function(e){let n=y.instance.deploymentName??y.instance.build.BUILD_ID;return t.call(this,`${n}-${e}`)},delete lt.caches.default,Object.freeze(lt.caches)}var eo=new Map,wn=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)})}},xe=class{static{s(this,"MemoryCache")}constructor(e,n={maxSize:1e3}){this.name=e;let r=eo.get(e);r||(r=new wn(n),eo.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 Pn="__zuplo-expiry-header",se=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(Pn);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(Pn,`${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(Pn,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),i=new Response("",{headers:n});await r.put(o,i)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var N=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,n){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new xe(r),this.#n=new se(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 to="zuplo-request-id",ze="zp-rid",no="zp-body-removed",Oe="cf-ray",En="cf-ipcity",In="cf-ipcontinent",xn="cf-ipcountry",On="cf-iplongitude",vn="cf-iplatitude",ro="zp-ipcity",oo="zp-ipcontinent",io="zp-ipcountry",so="zp-iplongitude",ao="zp-iplatitude",uo="true-client-ip",Tn="zp-asn",Cn="zp-asorg",An="zp-colo",Sn="zp-postalcode",Ln="zp-metrocode",_n="zp-region",Dn="zp-regioncode",kn="zp-timezone",co=[En,In,xn,On,vn,Tn,Cn,An,Sn,Ln,_n,Dn,kn],lo=["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=Ie(ye());var Be=class t{static{s(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let n=e.problem,r=JSON.stringify(n,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(t.problemResponseFormat=(n,r,o)=>{try{return e(n,r,o)}catch(i){throw new I("Error in custom 'problemResponseFormat'",{cause:i})}})}},ce=class{static{s(this,"ProblemResponseFormatter")}static async format(e,n,r){return await Be.problemResponseFormat(e,n,r)}};function yt(t){for(let e in t){let n=t[e];n&&typeof n=="object"&&yt(n)}return Object.freeze(t)}s(yt,"deepFreeze");var S=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 yt(this.#e)}get params(){return yt(this.#t)}user};var be=class{static{s(this,"RuntimePlugin")}},oe=class extends be{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,n){}},Ve={},le=[],So=[],Lo=[],_o=[];var bt={addPlugin(t){le.push(t)},addRequestHook(t){So.push(t)},addResponseSendingHook(t){Lo.push(t)},addResponseSendingFinalHook(t){_o.push(t)}},Do=s(async(t,e)=>{let n=t;for(let r of So){let o=await r(n,e);if(o instanceof S)n=o;else{if(o instanceof Response)return o;throw new f(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof n}.`)}}return n},"invokeOnRequestExtensions"),ko=s(async(t,e,n)=>{let r=t;for(let o of Lo){let i=await o(t,e,n);if(i instanceof Response)r=i;else throw new f(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof r}.`)}return r},"invokeOnResponseSendingExtensions"),Ho=s(async(t,e,n)=>{for(let r of _o)await r(t,e,n)},"invokeOnResponseSendingFinalExtensions");async function Uo(t=()=>Promise.resolve()){await t(bt),Ve.value=bt;for(let e of le)e instanceof oe&&await e.initialize(bt);Be.setProblemResponseFormat(bt.problemResponseFormat)}s(Uo,"initializeRuntime");var Rt={Json:"application/json",Form:"application/x-www-form-urlencoded"};function wt(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(wt,"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 b=>{let E=a.pop();return E?E(o,i,n,u):await this.#e(async v=>{let C=await r(v,i);return gu(C)},n)(b,i)},"nextPipe"),l=await u(o),d=new ve(o,l);i.dispatchEvent(d);let p=F.getContextExtensions(i),R=p.latestRequest,g;try{g=await d.mutableResponse}catch(b){return i.log.error(b),n.errorHandler(o,i,b)}try{g=await p.onResponseSending(g,R,i)}catch(b){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),n.errorHandler(o,i,b)}try{g=await ko(g,R,i)}catch(b){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),n.errorHandler(o,i,b)}i.dispatchEvent(new Te(o,g));try{await p.onResponseSendingFinal(l,R,i)}catch(b){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}try{await Ho(l,R,i)}catch(b){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}return g}};function gu(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response(wt(t),{headers:{"content-type":"application/json"}})}s(gu,"resultToResponse");var de=class extends be{static{s(this,"MetricsPlugin")}};var A=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 _(r)}return n}static addLogger(e,n){t.#e.set(e,n)}};var T=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 Pt=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=y.instance.loggingId,this.#e=e,this.#t=new T("ellie-metrics-transport",10,this.dispatchFunction,A.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}=y.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":y.instance.deploymentName??"unknown","user-agent":y.instance.systemUserAgent}});if(!u.ok){let c=await u.text();A.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=je.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},je={name:"__system-no-version",pathPrefix:""};var $=s(async(t,e,n,r)=>{let o=new Date,i=Date.now(),a=await r(t),u=t.headers.get(Oe)??void 0,c=t.headers.get(uo)??void 0,l=e.incomingRequestProperties,d;e.route instanceof D&&(d=e.route.systemRouteName);let p=F.getContextExtensions(e).latestRequest,R={timestamp:o,statusCode:a.status,durationMs:Date.now()-i,requestContentLength:t.headers.get("content-length")?Number(t.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:t.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:n.instanceId,userSub:p.user?.sub,clientIp:c},g=[];return g.push(new Pt(e)),le.forEach(b=>{if(b instanceof de){let E=b.getTransport();g.push(E)}}),g.forEach(b=>{b.pushMetrics(R,e)}),a},"metricsProcessor");var ee=(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))(ee||{});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 w.notFound(i,a);let l=y.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"&&A.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:[$],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 Et=(m=>(m[m.CONTINUE=100]="CONTINUE",m[m.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",m[m.PROCESSING=102]="PROCESSING",m[m.EARLY_HINTS=103]="EARLY_HINTS",m[m.OK=200]="OK",m[m.CREATED=201]="CREATED",m[m.ACCEPTED=202]="ACCEPTED",m[m.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",m[m.NO_CONTENT=204]="NO_CONTENT",m[m.RESET_CONTENT=205]="RESET_CONTENT",m[m.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",m[m.MULTI_STATUS=207]="MULTI_STATUS",m[m.ALREADY_REPORTED=208]="ALREADY_REPORTED",m[m.IM_USED=226]="IM_USED",m[m.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",m[m.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",m[m.FOUND=302]="FOUND",m[m.SEE_OTHER=303]="SEE_OTHER",m[m.NOT_MODIFIED=304]="NOT_MODIFIED",m[m.USE_PROXY=305]="USE_PROXY",m[m.SWITCH_PROXY=306]="SWITCH_PROXY",m[m.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",m[m.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",m[m.BAD_REQUEST=400]="BAD_REQUEST",m[m.UNAUTHORIZED=401]="UNAUTHORIZED",m[m.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",m[m.FORBIDDEN=403]="FORBIDDEN",m[m.NOT_FOUND=404]="NOT_FOUND",m[m.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",m[m.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",m[m.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",m[m.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",m[m.CONFLICT=409]="CONFLICT",m[m.GONE=410]="GONE",m[m.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",m[m.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",m[m.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",m[m.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",m[m.URI_TOO_LONG=414]="URI_TOO_LONG",m[m.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",m[m.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",m[m.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",m[m.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",m[m.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",m[m.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",m[m.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",m[m.LOCKED=423]="LOCKED",m[m.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",m[m.TOO_EARLY=425]="TOO_EARLY",m[m.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",m[m.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",m[m.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",m[m.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",m[m.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",m[m.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",m[m.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",m[m.BAD_GATEWAY=502]="BAD_GATEWAY",m[m.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",m[m.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",m[m.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",m[m.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",m[m.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",m[m.LOOP_DETECTED=508]="LOOP_DETECTED",m[m.NOT_EXTENDED=510]="NOT_EXTENDED",m[m.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",m))(Et||{}),No={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Content Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Content",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};var fu={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"},It=fu;function hu(t){return`${new URL(t.url).pathname}`}s(hu,"instance");function yu(t,e){let n={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:y.instance.build.BUILD_ID},r=t.headers.get(Oe);return r&&(n.rayId=r),n}s(yu,"trace");var bu=s((t,e,n,r,o)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:hu(e),trace:yu(e,n),...r},additionalHeaders:o,statusText:It[t.status]}),"merge"),Gn=class{static{s(this,"HttpProblemsBase")}static format=(e,n,r)=>"problem"in e?ce.format(e,n,r):ce.format({problem:e},n,r);static getProblemFromStatus(e,n){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:No[e],...n}}},w=class extends Gn{static{s(this,"HttpProblems")}static#e(e,n,r,o,i){let a=bu(this.getProblemFromStatus(e),n,r,o,i);return ce.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:Ru}=Object.prototype,{propertyIsEnumerable:wu}=Object.prototype;function Bn(t){return Ru.call(t)}s(Bn,"toString");function pe(t){return typeof t=="string"}s(pe,"isString");function Mo(t){return pe(t)&&t!==""}s(Mo,"isNonEmptyString");function Zo(t){return Bn(t)==="[object RegExp]"}s(Zo,"isRegexp");function qo(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>wu.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 Vn(t){return typeof t=="number"&&!isNaN(t)}s(Vn,"isNumber");function jn(t){return t===!0||t===!1}s(jn,"isBoolean");function Fo(t){return typeof t>"u"}s(Fo,"isUndefined");function $o(t){return Fo(t)||t===null}s($o,"isUndefinedOrNull");function We(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}s(We,"isErrorLike");var zo=new Map;function Go(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=zo.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 zo.set(t,r),r}s(Go,"statusCodesStringToNumberArray");function Re(t,e,n){if(!e.startsWith("."))throw new f(`Invalid ${n} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=t;return r.forEach(i=>{if(o===void 0)throw new I(`Error applying ${n} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(Re,"getValueFromRequestUser");function Jn(t){if(Array.isArray(t)){if(t.includes(n=>typeof n!="string"))throw new f("Received an array that contains non-string values.");return t}if(pe(t))return t.includes(",")?t.split(",").map(n=>n.trim()).filter(n=>n!==","&&n!==""):[t];throw new f(`Expected type of string, received type '${typeof t}'`)}s(Jn,"parseValueToStringArray");function Bo(t){if(t==null)return[];if(!Array.isArray(t))throw new f(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof t}'`);return t.map(n=>{if(!Je(n))throw new f(`Invalid custom cors policy is set. Expected an object, received '${typeof n}'`);if(!Mo(n.name))throw new f("Value of 'name' on custom cors policies must be a non-empty string.");if(n.maxAge!==void 0&&!Vn(n.maxAge))throw new f(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof n.maxAge}'`);if(n.allowCredentials!==void 0&&!jn(n.allowCredentials))throw new f("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let r=Wn(n,"allowedHeaders"),o=Wn(n,"allowedMethods"),i=Wn(n,"exposeHeaders"),a;try{a=Jn(n.allowedOrigins)}catch(c){throw new f(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name: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(Bo,"parseCorsPolicies");function Wn(t,e){let n;if(t[e]!==void 0)try{n=Jn(t[e])}catch(r){throw new f(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return n}s(Wn,"parseOptionalProperty");var xt=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"),Ot=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 Kn=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 w.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let R=t.lookup(l,c);if(!R)return w.notFound(a,u);let g=R.routeConfiguration,b=Pu(l,d,p,g,n);return b.isValid?new Response(void 0,{status:200,statusText:"OK",headers:b.headers}):(b.error&&u.log.warn(b.error),w.notFound(a,u))},"optionsHandler"),o=new H({processors:[$],handler:r,gateway:e}),i=new D({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});t.addRoute(i,o.execute)},"registerCorsRoute"),Pu=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 f(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=xt(a.allowedOrigins,n);return u?{isValid:!0,headers:Ot(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:[$],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 Yn=new D({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),jo=s((t,e)=>{let n=s(async(o,i)=>{let a=Ve.value?.notFoundHandler;if(a){let u=F.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return w.notFound(o,i)},"notFoundHandler"),r=new H({processors:[$],handler:n,gateway:e});t.addRoute(Yn,r.execute)},"registerNotMatchedHandler");var Eu=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Jo=s(t=>{Eu.forEach(e=>t.delete(e))},"stripCorsHeaders"),vt=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 Jo(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 _(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=Iu(o,n.routeData.corsPolicies),u=xu(t,a),c=new Headers(i.headers);return Jo(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"),Iu=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 f(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return n},"getCorsPolicy"),xu=s((t,e)=>{let n=xt(e.allowedOrigins,t.headers.get("origin"));return n?Ot(e,n):{}},"getCorsHeaders");var Qn=s((t,e)=>{let n=s(async()=>new Response(null,{status:200}),"pingRouteHandler"),r=new H({processors:[vt],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 Ke(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 f(`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 f(`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(Ke,"getInboundPolicyHandlerAndOptions");function Ou(t,e){return(t.policies?.outbound??[]).map(o=>{let i=e?.find(u=>u.name===o);if(!i)throw new f(`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 f(`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(Ou,"getOutboundPolicyHandlerAndOptions");var Xn=s(t=>async(e,n)=>{let r=F.getContextExtensions(n),o=[...t],i=e;for(;o.length>0;){let a=o.shift();if(!a)return i;let u=await a.handler(i,n,a.options,a.policyName);if(u instanceof S)i=u;else if(u instanceof Request)i=new S(u);else{if(u instanceof Response)return u;throw new f(`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"),vu=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 f(`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"),Tt=s(async(t,e,n,r)=>{let o=Ke(e.route,n.routeData.policies),i=Ou(e.route,n.routeData.policies);return Ko({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)=>Ko({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 Ko({request:t,context:e,inboundPolicies:n,outboundPolicies:r,gateway:o,next:i}){let a=Xn(n);try{let u=await a(t,e);if(u instanceof Response)return u;let c=await i(u),l=vu(r),d;return y.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(Ko,"executePolicyProcessor");function Yo(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");let n={},o=(e||{}).decode||Tu,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]=Cu(l,o)}i=u+1}return n}s(Yo,"parse");function Tu(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}s(Tu,"decode");function Cu(t,e){try{return e(t)}catch{return t}}s(Cu,"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",Au="dev-portal-id",Su="dev-portal-host",Lu="zp-account",_u="zp-project",Du="dev-portal-build",ku=`
35
+ `)+" "+n[1]:n[0]+e+" "+t.join(", ")+" "+n[1]}s(uu,"reduceToSingleString")});var So=je(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.format=void 0;var cu=Po(),lu=To(),du=s((t,...e)=>(0,cu.format)(lu.inspect,t,e),"format");ft.format=du});var be=je(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.debug=le.withoutEnv=le.Debugger=void 0;var pu=wo(),mu=So(),ht=class{static{s(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,n){this.manager=e,this.ns=n,this.color=(0,pu.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,mu.format)(n,...e);let i=`${this.color(this.ns)} ${n} ${this.color(`+${o}ms`)}`;console.log(i),this.last=Date.now()}};le.Debugger=ht;var yt=class{static{s(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function Co(t){return!t||t.length===0?[]:(t=t.replace(/\s/g,"").replace(/\*/g,".+"),t.split(",").map(e=>new RegExp(`^${e}$`)))}s(Co,"extract");var Be;function gu(t){t||(t=[]),typeof t=="string"&&(t=Co(t)),Be=new yt(t)}s(gu,"withoutEnv");le.withoutEnv=gu;function fu(t){let e=globalThis.DEBUG;Be||(Be=new yt(Co(e)));let n=new ht(Be,t);return Be.debuggers.set(t,n),Object.assign(n.log.bind(n),{self:n})}s(fu,"debug");le.debug=fu});var hl={};ua(hl,{API_KEY:()=>ni,AWSLoggingPlugin:()=>Kt,AmberfloMeteringInboundPolicy:()=>zi,AmberfloMeteringPolicy:()=>rn,ApiAuthKeyInboundPolicy:()=>Vi,ApiKeyInboundPolicy:()=>sn,AuditLogDataStaxProvider:()=>Xt,AuditLogPlugin:()=>en,Auth0JwtInboundPolicy:()=>Wi,AwsLambdaHandlerExtensions:()=>Ai,BasicAuthInboundPolicy:()=>Ji,BasicRateLimitInboundPolicy:()=>$r,CachingInboundPolicy:()=>Ki,ChangeMethodInboundPolicy:()=>Yi,ClearHeadersInboundPolicy:()=>Qi,ClearHeadersOutboundPolicy:()=>Xi,ClerkJwtInboundPolicy:()=>es,CognitoJwtInboundPolicy:()=>ts,CompositeInboundPolicy:()=>ns,ConfigurationError:()=>f,ContentTypes:()=>wt,ContextData:()=>ae,CreditsMeteringInboundPolicy:()=>rs,CryptoBeta:()=>hn,CurityPhantomTokenInboundPolicy:()=>os,DataDogLoggingPlugin:()=>Ut,DataDogMetricsPlugin:()=>Yt,DynaTraceLoggingPlugin:()=>Gt,DynatraceMetricsPlugin:()=>Qt,FirebaseJwtInboundPolicy:()=>is,FormDataToJsonInboundPolicy:()=>ss,GeoFilterInboundPolicy:()=>as,GoogleCloudLoggingPlugin:()=>kt,Handler:()=>zt,HttpProblems:()=>w,HttpStatusCode:()=>It,JWTScopeValidationInboundPolicy:()=>us,KeyValueStore:()=>bn,LoadSubscriptionInboundPolicy:()=>ta,LokiLoggingPlugin:()=>Vt,LookupResult:()=>Le,MemoryZoneReadThroughCache:()=>N,MeteringInboundPolicy:()=>ea,MockApiInboundPolicy:()=>ls,MoesifInboundPolicy:()=>hs,OktaJwtInboundPolicy:()=>ys,OpenIdJwtInboundPolicy:()=>q,ProblemResponseFormatter:()=>de,PropelAuthJwtInboundPolicy:()=>Rs,RateLimitInboundPolicy:()=>$r,ReadmeMetricsInboundPolicy:()=>xs,RemoveHeadersInboundPolicy:()=>vs,RemoveHeadersOutboundPolicy:()=>Os,RemoveQueryParamsInboundPolicy:()=>Ts,ReplaceStringOutboundPolicy:()=>Ss,RequestSizeLimitInboundPolicy:()=>As,RequestValidationInboundPolicy:()=>Br,RequireOriginInboundPolicy:()=>Ms,ResponseSendingEvent:()=>Te,ResponseSentEvent:()=>Se,Router:()=>_e,SYSTEM_LOGGER:()=>Qe,SchemaBasedRequestValidation:()=>Ns,ServiceProviderImpl:()=>gn,SetBodyInboundPolicy:()=>Zs,SetHeadersInboundPolicy:()=>qs,SetHeadersOutboundPolicy:()=>Fs,SetQueryParamsInboundPolicy:()=>$s,SetStatusOutboundPolicy:()=>js,SleepInboundPolicy:()=>zs,StripeMeteringPlugin:()=>Dr,StripeWebhookInboundPolicy:()=>tn,SumoLogicLoggingPlugin:()=>Wt,SupabaseJwtInboundPolicy:()=>Bs,SystemLogMap:()=>S,SystemRouteName:()=>te,UpstreamAzureAdServiceAuthInboundPolicy:()=>Gs,UpstreamFirebaseAdminAuthInboundPolicy:()=>Ws,UpstreamFirebaseUserAuthInboundPolicy:()=>Js,UpstreamGcpJwtInboundPolicy:()=>Ks,UpstreamGcpServiceAuthInboundPolicy:()=>Qs,VMWareLogInsightLoggingPlugin:()=>Jt,ValidateJsonSchemaInbound:()=>Xs,ZoneCache:()=>ue,ZuploRequest:()=>L,awsLambdaHandler:()=>Li,environment:()=>it,getIdForParameterSchema:()=>pn,getIdForRefSchema:()=>_s,getIdForRequestBodySchema:()=>mn,getRawOperationDataIdentifierName:()=>Ls,httpStatuses:()=>xt,isRestrictedEnvVariableName:()=>lr,isZuploReadableEnvVariableName:()=>dr,openApiSpecHandler:()=>_i,originalFetch:()=>ke,purgeGatewayCache:()=>Ri,redirectHandler:()=>ki,sanitizedIdentifierName:()=>he,serialize:()=>Pt,setMoesifContext:()=>fs,urlForwardHandler:()=>Di,urlRewriteHandler:()=>Hi,webSocketHandler:()=>Ui,webSocketPipelineHandler:()=>Zi});module.exports=ca(hl);var _=class extends Error{static{s(this,"SystemError")}constructor(e,n){super(e,n),this.name="InternalError"}},I=class extends Error{static{s(this,"RuntimeError")}extensionMembers;constructor(e,n){typeof e=="string"?super(e,n):(super(e.message,n),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},f=class extends I{static{s(this,"ConfigurationError")}constructor(e,n){super(e,n),this.name="ConfigurationError"}},lt=class extends I{static{s(this,"FeatureNotEnabledError")}constructor(e,n){super(e,n),this.name="FeatureNotEnabledError"}};var y=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 _("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.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_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,Xr=dt.caches;if(Xr){let t=Xr.open;dt.caches.open=function(e){let n=y.instance.deploymentName??y.instance.build.BUILD_ID;return t.call(this,`${n}-${e}`)},delete dt.caches.default,Object.freeze(dt.caches)}var eo=new Map,wn=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)})}},ve=class{static{s(this,"MemoryCache")}constructor(e,n={maxSize:1e3}){this.name=e;let r=eo.get(e);r||(r=new wn(n),eo.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 Pn="__zuplo-expiry-header",ue=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(Pn);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(Pn,`${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(Pn,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),i=new Response("",{headers:n});await r.put(o,i)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var N=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,n){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new ve(r),this.#n=new ue(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 to="zuplo-request-id",ze="zp-rid",no="zp-body-removed",Oe="cf-ray",En="cf-ipcity",In="cf-ipcontinent",xn="cf-ipcountry",vn="cf-iplongitude",On="cf-iplatitude",ro="zp-ipcity",oo="zp-ipcontinent",io="zp-ipcountry",so="zp-iplongitude",ao="zp-iplatitude",uo="true-client-ip",Tn="zp-asn",Sn="zp-asorg",Cn="zp-colo",An="zp-postalcode",Ln="zp-metrocode",_n="zp-region",kn="zp-regioncode",Dn="zp-timezone",co=[En,In,xn,vn,On,Tn,Sn,Cn,An,Ln,_n,kn,Dn],lo=["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=xe(be());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 I("Error in custom 'problemResponseFormat'",{cause:i})}})}},de=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 L=class t extends Request{static{s(this,"ZuploRequest")}#e=void 0;#t;constructor(e,n){super(e,n);let r=n?.params;r?this.#t=r:e instanceof t?this.#t=e.#t:this.#t={};let o=n?.user;o?this.user=o:e instanceof t&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},n=new URL(this.url).searchParams;for(let[r,o]of n.entries())e[r]=o;this.#e=e}return bt(this.#e)}get params(){return bt(this.#t)}user};var Re=class{static{s(this,"RuntimePlugin")}},ie=class extends Re{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,n){}},Ve={},pe=[],Ao=[],Lo=[],_o=[];var Rt={addPlugin(t){pe.push(t)},addRequestHook(t){Ao.push(t)},addResponseSendingHook(t){Lo.push(t)},addResponseSendingFinalHook(t){_o.push(t)}},ko=s(async(t,e)=>{let n=t;for(let r of Ao){let o=await r(n,e);if(o instanceof L)n=o;else{if(o instanceof Response)return o;throw new f(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof n}.`)}}return n},"invokeOnRequestExtensions"),Do=s(async(t,e,n)=>{let r=t;for(let o of Lo){let i=await o(t,e,n);if(i instanceof Response)r=i;else throw new f(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof r}.`)}return r},"invokeOnResponseSendingExtensions"),Ho=s(async(t,e,n)=>{for(let r of _o)await r(t,e,n)},"invokeOnResponseSendingFinalExtensions");async function Uo(t=()=>Promise.resolve()){await t(Rt),Ve.value=Rt;for(let e of pe)e instanceof ie&&await e.initialize(Rt);Ge.setProblemResponseFormat(Rt.problemResponseFormat)}s(Uo,"initializeRuntime");var wt={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(wt.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(wt.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 h=>{let E=a.pop();return E?E(o,i,n,u):await this.#e(async x=>{let T=await r(x,i);return hu(T)},n)(h,i)},"nextPipe"),l=await u(o),d=new Te(o,l);i.dispatchEvent(d);let p=F.getContextExtensions(i),R=p.latestRequest,g;try{g=await d.mutableResponse}catch(h){return i.log.error(h),n.errorHandler(o,i,h)}try{g=await p.onResponseSending(g,R,i)}catch(h){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${h.message}'`,h),n.errorHandler(o,i,h)}try{g=await Do(g,R,i)}catch(h){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${h.message}'`,h),n.errorHandler(o,i,h)}i.dispatchEvent(new Se(o,g));try{await p.onResponseSendingFinal(l,R,i)}catch(h){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${h.message}'`,h),h}try{await Ho(l,R,i)}catch(h){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${h.message}'`,h),h}return g}};function hu(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response(Pt(t),{headers:{"content-type":"application/json"}})}s(hu,"resultToResponse");var me=class extends Re{static{s(this,"MetricsPlugin")}};var S=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 _(r)}return n}static addLogger(e,n){t.#e.set(e,n)}};var C=class{static{s(this,"BatchDispatch")}constructor(e,n,r,o){this.#t=e,this.#i=n,this.#r=r,this.#n=o}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=e=>{this.#o.push(e),this.#e||(this.#e=new Promise(n=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n&&this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{n()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var Et=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=y.instance.loggingId,this.#e=e,this.#t=new C("ellie-metrics-transport",10,this.dispatchFunction,S.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}=y.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":y.instance.deploymentName??"unknown","user-agent":y.instance.systemUserAgent}});if(!u.ok){let c=await u.text();S.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 $=s(async(t,e,n,r)=>{let o=new Date,i=Date.now(),a=await r(t),u=t.headers.get(Oe)??void 0,c=t.headers.get(uo)??void 0,l=e.incomingRequestProperties,d;e.route instanceof D&&(d=e.route.systemRouteName);let p=F.getContextExtensions(e).latestRequest,R={timestamp:o,statusCode:a.status,durationMs:Date.now()-i,requestContentLength:t.headers.get("content-length")?Number(t.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:t.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:n.instanceId,userSub:p.user?.sub,clientIp:c},g=[];return g.push(new Et(e)),pe.forEach(h=>{if(h instanceof me){let E=h.getTransport();g.push(E)}}),g.forEach(h=>{h.pushMetrics(R,e)}),a},"metricsProcessor");var te=(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))(te||{});var jn=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 w.notFound(i,a);let l=y.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"&&S.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:[$],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=(m=>(m[m.CONTINUE=100]="CONTINUE",m[m.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",m[m.PROCESSING=102]="PROCESSING",m[m.EARLY_HINTS=103]="EARLY_HINTS",m[m.OK=200]="OK",m[m.CREATED=201]="CREATED",m[m.ACCEPTED=202]="ACCEPTED",m[m.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",m[m.NO_CONTENT=204]="NO_CONTENT",m[m.RESET_CONTENT=205]="RESET_CONTENT",m[m.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",m[m.MULTI_STATUS=207]="MULTI_STATUS",m[m.ALREADY_REPORTED=208]="ALREADY_REPORTED",m[m.IM_USED=226]="IM_USED",m[m.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",m[m.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",m[m.FOUND=302]="FOUND",m[m.SEE_OTHER=303]="SEE_OTHER",m[m.NOT_MODIFIED=304]="NOT_MODIFIED",m[m.USE_PROXY=305]="USE_PROXY",m[m.SWITCH_PROXY=306]="SWITCH_PROXY",m[m.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",m[m.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",m[m.BAD_REQUEST=400]="BAD_REQUEST",m[m.UNAUTHORIZED=401]="UNAUTHORIZED",m[m.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",m[m.FORBIDDEN=403]="FORBIDDEN",m[m.NOT_FOUND=404]="NOT_FOUND",m[m.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",m[m.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",m[m.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",m[m.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",m[m.CONFLICT=409]="CONFLICT",m[m.GONE=410]="GONE",m[m.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",m[m.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",m[m.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",m[m.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",m[m.URI_TOO_LONG=414]="URI_TOO_LONG",m[m.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",m[m.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",m[m.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",m[m.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",m[m.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",m[m.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",m[m.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",m[m.LOCKED=423]="LOCKED",m[m.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",m[m.TOO_EARLY=425]="TOO_EARLY",m[m.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",m[m.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",m[m.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",m[m.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",m[m.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",m[m.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",m[m.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",m[m.BAD_GATEWAY=502]="BAD_GATEWAY",m[m.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",m[m.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",m[m.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",m[m.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",m[m.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",m[m.LOOP_DETECTED=508]="LOOP_DETECTED",m[m.NOT_EXTENDED=510]="NOT_EXTENDED",m[m.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",m))(It||{}),No={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 yu={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=yu;function bu(t){return`${new URL(t.url).pathname}`}s(bu,"instance");function Ru(t,e){let n={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:y.instance.build.BUILD_ID},r=t.headers.get(Oe);return r&&(n.rayId=r),n}s(Ru,"trace");var wu=s((t,e,n,r,o)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:bu(e),trace:Ru(e,n),...r},additionalHeaders:o,statusText:xt[t.status]}),"merge"),zn=class{static{s(this,"HttpProblemsBase")}static format=(e,n,r)=>"problem"in e?de.format(e,n,r):de.format({problem:e},n,r);static getProblemFromStatus(e,n){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:No[e],...n}}},w=class extends zn{static{s(this,"HttpProblems")}static#e(e,n,r,o,i){let a=wu(this.getProblemFromStatus(e),n,r,o,i);return de.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:Pu}=Object.prototype,{propertyIsEnumerable:Eu}=Object.prototype;function Bn(t){return Pu.call(t)}s(Bn,"toString");function K(t){return typeof t=="string"}s(K,"isString");function Mo(t){return K(t)&&t!==""}s(Mo,"isNonEmptyString");function Zo(t){return Bn(t)==="[object RegExp]"}s(Zo,"isRegexp");function qo(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>Eu.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 Vn(t){return t===!0||t===!1}s(Vn,"isBoolean");function Fo(t){return typeof t>"u"}s(Fo,"isUndefined");function $o(t){return Fo(t)||t===null}s($o,"isUndefinedOrNull");function Ke(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}s(Ke,"isErrorLike");var jo=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=jo.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 jo.set(t,r),r}s(zo,"statusCodesStringToNumberArray");function we(t,e,n){if(!e.startsWith("."))throw new f(`Invalid ${n} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=t;return r.forEach(i=>{if(o===void 0)throw new I(`Error applying ${n} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(we,"getValueFromRequestUser");function Wn(t){if(Array.isArray(t)){if(t.includes(n=>typeof n!="string"))throw new f("Received an array that contains non-string values.");return t}if(K(t))return t.includes(",")?t.split(",").map(n=>n.trim()).filter(n=>n!==","&&n!==""):[t];throw new f(`Expected type of string, received type '${typeof t}'`)}s(Wn,"parseValueToStringArray");function Bo(t){if(t==null)return[];if(!Array.isArray(t))throw new f(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof t}'`);return t.map(n=>{if(!Je(n))throw new f(`Invalid custom cors policy is set. Expected an object, received '${typeof n}'`);if(!Mo(n.name))throw new f("Value of 'name' on custom cors policies must be a non-empty string.");if(n.maxAge!==void 0&&!Gn(n.maxAge))throw new f(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof n.maxAge}'`);if(n.allowCredentials!==void 0&&!Vn(n.allowCredentials))throw new f("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let r=Jn(n,"allowedHeaders"),o=Jn(n,"allowedMethods"),i=Jn(n,"exposeHeaders"),a;try{a=Wn(n.allowedOrigins)}catch(c){throw new f(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name: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(Bo,"parseCorsPolicies");function Jn(t,e){let n;if(t[e]!==void 0)try{n=Wn(t[e])}catch(r){throw new f(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return n}s(Jn,"parseOptionalProperty");var vt=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"),Ot=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 Kn=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 w.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let R=t.lookup(l,c);if(!R)return w.notFound(a,u);let g=R.routeConfiguration,h=Iu(l,d,p,g,n);return h.isValid?new Response(void 0,{status:200,statusText:"OK",headers:h.headers}):(h.error&&u.log.warn(h.error),w.notFound(a,u))},"optionsHandler"),o=new H({processors:[$],handler:r,gateway:e}),i=new D({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});t.addRoute(i,o.execute)},"registerCorsRoute"),Iu=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 f(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=vt(a.allowedOrigins,n);return u?{isValid:!0,headers:Ot(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${n}'`}},"validateAndBuildResponseHeaders");var Go=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:[$],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 Yn=new D({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Vo=s((t,e)=>{let n=s(async(o,i)=>{let a=Ve.value?.notFoundHandler;if(a){let u=F.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return w.notFound(o,i)},"notFoundHandler"),r=new H({processors:[$],handler:n,gateway:e});t.addRoute(Yn,r.execute)},"registerNotMatchedHandler");var xu=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Wo=s(t=>{xu.forEach(e=>t.delete(e))},"stripCorsHeaders"),Tt=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 Wo(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 _(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=vu(o,n.routeData.corsPolicies),u=Ou(t,a),c=new Headers(i.headers);return Wo(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"),vu=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 f(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return n},"getCorsPolicy"),Ou=s((t,e)=>{let n=vt(e.allowedOrigins,t.headers.get("origin"));return n?Ot(e,n):{}},"getCorsHeaders");var Qn=s((t,e)=>{let n=s(async()=>new Response(null,{status:200}),"pingRouteHandler"),r=new H({processors:[Tt],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 Ye(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 f(`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 f(`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(Ye,"getInboundPolicyHandlerAndOptions");function Tu(t,e){return(t.policies?.outbound??[]).map(o=>{let i=e?.find(u=>u.name===o);if(!i)throw new f(`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 f(`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(Tu,"getOutboundPolicyHandlerAndOptions");var Xn=s(t=>async(e,n)=>{let r=F.getContextExtensions(n),o=[...t],i=e;for(;o.length>0;){let a=o.shift();if(!a)return i;let u=await a.handler(i,n,a.options,a.policyName);if(u instanceof L)i=u;else if(u instanceof Request)i=new L(u);else{if(u instanceof Response)return u;throw new f(`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"),Su=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 f(`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"),St=s(async(t,e,n,r)=>{let o=Ye(e.route,n.routeData.policies),i=Tu(e.route,n.routeData.policies);return Ko({request:t,context:e,inboundPolicies:o,outboundPolicies:i,gateway:n,next:r})},"policyProcessor");function Jo({inboundPolicies:t=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>Ko({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(Jo,"createInternalPolicyProcessor");async function Ko({request:t,context:e,inboundPolicies:n,outboundPolicies:r,gateway:o,next:i}){let a=Xn(n);try{let u=await a(t,e);if(u instanceof Response)return u;let c=await i(u),l=Su(r),d;return y.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(Ko,"executePolicyProcessor");function Yo(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");let n={},o=(e||{}).decode||Cu,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]=Au(l,o)}i=u+1}return n}s(Yo,"parse");function Cu(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}s(Cu,"decode");function Au(t,e){try{return e(t)}catch{return t}}s(Au,"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",Lu="dev-portal-id",_u="dev-portal-host",ku="zp-account",Du="zp-project",Hu="dev-portal-build",Uu=`
36
36
  <!DOCTYPE html>
37
37
  <html lang="en">
38
38
  <head>
@@ -46,27 +46,27 @@
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=y.instance.deploymentName,o=y.instance.devPortalBaseUrl,i=s(async(c,l)=>{if(y.instance.isLocalDevelopment)return new Response(ku,{headers:{"content-type":"text/html"}});if(!r)return w.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),R=new URL(`${d.pathname}${d.search}`,p),{headers:g,method:b,body:E}=c;return y.instance.build.ACCOUNT_NAME&&g.set(Lu,y.instance.build.ACCOUNT_NAME),y.instance.build.PROJECT_NAME&&g.set(_u,y.instance.build.PROJECT_NAME),g.set(Au,r),g.set(Su,d.host),g.set(Du,y.instance.build.BUILD_ID),await fetch(R.toString(),{headers:g,method:b,body:E,redirect:"manual"})},"devPortalRoute"),a=new H({processors:[$,Tt],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:[$],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=Ie(ye());var Ye="system-logger",ni="api-key";var er=0,Qe=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){er>=Number.MAX_SAFE_INTEGER&&(er=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:er++};this.#t[e](u,a)}};var U=class extends be{static{s(this,"LogPlugin")}};var Ct=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 Xe=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 Hu=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(t=>[t.name,t]),Uu=new Map(Hu);var Nu=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],tr=Symbol(".toJSON was called"),Mu=s(t=>{t[tr]=!0;let e=t.toJSON();return delete t[tr],e},"toJSON"),Zu=s(t=>Uu.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&&We(t)){let l=Zu(t.name);n=new l}else n={};if(e.push(t),i>=o)return n;if(a&&typeof t.toJSON=="function"&&t[tr]!==!0)return Mu(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 Nu)typeof t[l]<"u"&&t[l]!==null&&Object.defineProperty(n,l,{value:We(t[l])?c(t[l]):t[l],enumerable:r?!0:d,configurable:!0,writable:!0});return n},"destroyCircular");function z(t,e){let n=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof t=="object"&&t!==null?ri({from:t,seen:[],forceEnumerable:!0,maxDepth:n,depth:0,useToJSON:r,serialize:!0}):typeof t=="function"?`[Function: ${t.name??"anonymous"}]`:t}s(z,"serializeError");var qu=/file:\/\/\/(.*?)\/dist\//g,Fu=/\(https:\/\/raw\.githubusercontent\.com\/.*?\)/g,$u="at async Event.respondWith";function oi(t){return typeof t!="string"?t:t.split(`
50
- `).filter(e=>!e.trim().startsWith("at async file")).map((e,n)=>{let r=e.replaceAll(qu,"").replaceAll(Fu,"").replaceAll($u,"").trim();return n===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
49
+ `,ei=s((t,e)=>{let{sitePathname:n}=e.runtimeSettings.developerPortal,r=y.instance.deploymentName,o=y.instance.devPortalBaseUrl,i=s(async(c,l)=>{if(y.instance.isLocalDevelopment)return new Response(Uu,{headers:{"content-type":"text/html"}});if(!r)return w.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),R=new URL(`${d.pathname}${d.search}`,p),{headers:g,method:h,body:E}=c;return y.instance.build.ACCOUNT_NAME&&g.set(ku,y.instance.build.ACCOUNT_NAME),y.instance.build.PROJECT_NAME&&g.set(Du,y.instance.build.PROJECT_NAME),g.set(Lu,r),g.set(_u,d.host),g.set(Hu,y.instance.build.BUILD_ID),await fetch(R.toString(),{headers:g,method:h,body:E,redirect:"manual"})},"devPortalRoute"),a=new H({processors:[$,St],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:[$],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=xe(be());var Qe="system-logger",ni="api-key";var er=0,Xe=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){er>=Number.MAX_SAFE_INTEGER&&(er=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:er++};this.#t[e](u,a)}};var U=class extends Re{static{s(this,"LogPlugin")}};var Ct=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 et=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 Nu=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(t=>[t.name,t]),Mu=new Map(Nu);var Zu=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],tr=Symbol(".toJSON was called"),qu=s(t=>{t[tr]=!0;let e=t.toJSON();return delete t[tr],e},"toJSON"),Fu=s(t=>Mu.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&&Ke(t)){let l=Fu(t.name);n=new l}else n={};if(e.push(t),i>=o)return n;if(a&&typeof t.toJSON=="function"&&t[tr]!==!0)return qu(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 Zu)typeof t[l]<"u"&&t[l]!==null&&Object.defineProperty(n,l,{value:Ke(t[l])?c(t[l]):t[l],enumerable:r?!0:d,configurable:!0,writable:!0});return n},"destroyCircular");function z(t,e){let n=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof t=="object"&&t!==null?ri({from:t,seen:[],forceEnumerable:!0,maxDepth:n,depth:0,useToJSON:r,serialize:!0}):typeof t=="function"?`[Function: ${t.name??"anonymous"}]`:t}s(z,"serializeError");var $u=/file:\/\/\/(.*?)\/dist\//g,ju=/\(https:\/\/raw\.githubusercontent\.com\/.*?\)/g,zu="at async Event.respondWith";function oi(t){return typeof t!="string"?t:t.split(`
50
+ `).filter(e=>!e.trim().startsWith("at async file")).map((e,n)=>{let r=e.replaceAll($u,"").replaceAll(ju,"").replaceAll(zu,"").trim();return n===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
51
51
  `)}s(oi,"cleanStack");function At(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 R=s(g=>{if(u.inlineCharacterLimit===void 0)return g;let b=g.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return b.length<=u.inlineCharacterLimit?b:g.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
54
- `).replace(new RegExp(p.pad,"g"),c).replace(new RegExp(p.indent,"g"),c+d)},"expandWhiteSpace");if(r.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||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 g="["+p.newline+a.map((b,E)=>{let P=a.length-1===E?p.newline:","+p.newlineOrSpace,v=i(b,u,c+d,l+1);return u.transform&&(v=u.transform(a,E,v)),p.indent+v+P}).join("")+p.pad+"]";return r.pop(),R(g)}if(Je(a)){let g=qo(a);if(u.filter&&(g=g.filter(E=>u.filter?.(a,E))),g.length===0)return"{}";r.push(a);let b="{"+p.newline+g.map((E,P)=>{let v=g.length-1===P?p.newline:","+p.newlineOrSpace,C=typeof E=="symbol",k=!C&&/^[a-z$_][$\w]*$/i.test(E),L=C||k?E:i(E,u,"",l+1),G=i(a[E],u,c+d,l+1);return u.transform&&(G=u.transform(a,E,G)),p.indent+String(L)+": "+G+v}).join("")+p.pad+"}";return r.pop(),R(b)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,g=>g===`
55
- `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(t,e,n,0)}s(At,"stringifyObject");function me(t){return t.map(e=>z(e))}s(me,"makeErrorsSerializable");function Ce(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:ie(z(e))}s(Ce,"extractBestMessage");function ii(t){let e=[];return t.forEach(n=>{if(typeof n=="string")e.push(n);else if(We(n))if(n.stack)e.push(n.stack);else{let r=At(z(n));e.push(r)}else if(typeof n=="object"){let r=At(n);e.push(r)}else{let r=nr(n);e.push(r)}}),e.join(`
56
- `)}s(ii,"messagesToMultilineText");function ie(t){return typeof t=="string"?t:JSON.stringify(t)}s(ie,"stringifyNonString");function nr(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"?Bn(t):"unknown"}s(nr,"stringifyNonStringToText");var St=require("jose");async function Ae(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 f("An unknown error occurred, ensure retries is not negative")}s(Ae,"fetchRetry");async function te({serviceAccount:t,audience:e,expirationTime:n="1h",payload:r={}}){let{clientEmail:o,privateKeyId:i,privateKey:a}=t;return await new St.SignJWT(r).setProtectedHeader({alg:"RS256",kid:i}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(n).sign(a)}s(te,"getTokenFromGcpServiceAccount");async function si(t,e,n){return ai(t,{token:e,returnSecureToken:!0},n)}s(si,"exchangeFirebaseJwtForIdToken");async function Lt(t,e,n){return ai(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},n)}s(Lt,"exchangeGgpJwtForIdToken");async function ai(t,e,n){let r=await Ae(n,t,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let i;try{let a=await r.text(),u=JSON.parse(a);i={cause:u.error??u}}catch{}throw new I({message:"Could not get token from Google Identity",extensionMembers:i})}return await r.json()}s(ai,"fetchToken");var B=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,St.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 _t=class extends U{constructor(n){super();this.options=n}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new et(this.options)}},zu="https://logging.googleapis.com/v2/entries:write?alt=json",rr={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},et=class{static{s(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=y.instance.loggingEnvironmentType,this.#i=y.instance.loggingEnvironmentStage,this.#r=y.instance.deploymentName}#e;#t;#n;#r;#o;#i;async log(e,n){if(e.messages.length===0)return;let r={allMessages:me(e.messages)};this.#t||(this.#t=await B.init(this.#e));let o=this.#t.projectId??"zuplo-production",i={logName:this.#n,resource:{type:"global"},severity:rr[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=Ce(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 B.init(this.#e));let n=await te({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await fetch(zu,{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 T("google-log-transport",1,this.dispatchFunction)};var Dt="gcp";function kt(t){let e={allMessages:me(t.messages)},n="zuplo-production",r=Ce(e.allMessages),o={logName:`projects/${n}/logs/runtime-user`,message:r,severity:rr[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(kt,"gcpLogFormat");var tt=class{static{s(this,"ConsoleTransport")}constructor(e,n){this.#e=e??console,this.#t=n}#e;#t;async log(e){if(this.#t===Dt){if(e.messages.length===0)return;this.#e[e.level].apply(null,[kt(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 Ht=class extends U{constructor(n){super();this.options=n}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new nt(this.options)}},or="__ddtags",ir="__ddattr",sr=s(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),Gu=s(t=>{let e=Object.keys(t),n=[];return e.forEach(r=>{let o=t[r];o==null?n.push(sr(r)):n.push(`${sr(r)}:${sr(o.toString())}`)}),n.join(",")},"formatTags"),nt=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=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName}#e;#t;#n;#r;#o;async log(e,n){let r={},o=n.custom[or];o&&typeof o=="object"&&Object.assign(r,o);let i=[...e.messages],a=e.messages.findIndex(g=>g[or]!==void 0);a>-1&&(Object.assign(r,i[a][or]),i.splice(a,1));let u={},c=n.custom[ir];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(g=>g[ir]!==void 0);l>-1&&(Object.assign(u,i[l][ir]),i.splice(l,1));let d=me(i),R={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(n.originalRequest.url).hostname,msg:Ce(d),service:e.loggingId,ddtags:Gu(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(R,u),this.batcher.enqueue(R),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 T("data-dog-transport",10,this.dispatchFunction)};var rt=class{static{s(this,"ProcessTransport")}constructor(e,n){this.#e=e,this.#t=n}#e;#t;async log(e){if(this.#t===Dt){if(e.messages.length===0)return;this.#e[e.level].apply(null,[kt(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 Bu=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:me(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":y.instance.systemUserAgent,"zp-dn":y.instance.deploymentName??"unknown"}}).catch(a=>{console.error(a)})},"dispatchFunction"),Ut,Nt=class{static{s(this,"RemoteLogTransport")}constructor(e){Ut||(Ut=new T("remote-log-transport",1,Bu(e)))}async log(e,n){Ut.enqueue(e),n.waitUntil(Ut.waitUntilFlushed())}};var Vu={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:Vu[n.level],body:n.messages,attributes:r}},"unifiedFormatter");var ju=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":y.instance.systemUserAgent,"zp-dn":y.instance.deploymentName??"unknown"}}).catch(a=>{console.error(a)})},"dispatchFunction"),Mt,Zt=class{static{s(this,"UnifiedLogTransport")}constructor(e){Mt||(Mt=new T("unified-log-transport",1,ju(e)))}async log(e,n){Mt.enqueue(e),n.waitUntil(Mt.waitUntilFlushed())}};var ar=(0,ci.debug)("zuplo:logging"),qt=class{constructor(e){this.serviceProvider=e;this.systemCoreLogger=this.setupSystemCoreLogger(y.instance),this.userCoreLogger=this.setupUserCoreLogger(y.instance)}static{s(this,"LogInitializer")}systemCoreLogger;userCoreLogger;setupSystemCoreLogger(e){let{build:n}=e;ar("Gateway.setupSystemCoreLogger");let r=[],o=this.serviceProvider.getService(Ye);return o?r.push(new rt(o.logger,e.logFormat)):e.isDeno&&r.push(new tt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new Zt({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),new Qe(e.systemLogLevel,"system",e.loggingId,n.BUILD_ID,r)}setupUserCoreLogger(e){ar("Gateway.setupUserCoreLogger");let n=[],{runtime:r,build:o}=e,i=this.serviceProvider.getService(Ye);if(i&&i.captureUserLogs===!0?n.push(new rt(i.logger,e.logFormat)):e.isDeno&&n.push(new tt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&n.push(new Nt({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 et({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 nt({apiKey:r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:a}))}return le.forEach(a=>{a instanceof U&&n.push(a.getTransport())}),new Qe(e.userLogLevel,"user",e.loggingId,o.BUILD_ID,n)}createRequestLoggers(e,n,r,o,i){ar("Gateway.createRequestLoggers");let a=new Ct(r,o,i),u=new Xe(e,n,this.systemCoreLogger,a);return{userRequestLogger:new Xe(e,n,this.userCoreLogger,a),systemRequestLogger:u}}};var we=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 ur=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},Se=class{static{s(this,"LookupResult")}constructor(e,n,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=n}executableHandler;routeConfiguration;params},cr=class extends Error{static{s(this,"RouterError")}constructor(e,n){super(e,n)}},Le=class{static{s(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,n){if(!(e instanceof we||e instanceof D))throw new _("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 ur(o,i,e,n);Object.freeze(a.config),this.routeEntries.push(a)}catch(i){throw new cr(`addRoute-error: Invalid path '${o}'. '${i.message}'`,{cause:i})}}lookup(e,n){if(typeof e>"u")throw new f(`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 Se(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 Se(o.config,o.executableHandler,a.pathname.groups);n.push(u)}}return n}};var Ju=["/__zuplo/ping","/__zuplo/open-api","/__zuplo/docs","/__zuplo/consumers","/__zuplo/external-users","/__zuplo/assets","/__zuplo/config","/__zuplo/build","/favicon.ico"],ne=(0,li.debug)("zuplo:runtime"),Wu=s(t=>{let e=t.findIndex(n=>n.name===je.name);return e>-1?[...t.splice(e),je]:[...t,je]},"setupSystemNoVersion"),V=class t{constructor(e,n,r,o){this.routeData=e;this.runtimeSettings=n;this.schemaValidator=o;ne("Gateway.constructor"),this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=new qt(r)}static{s(this,"Gateway")}static#e;static async initialize(e,n,r,o,i){if(ne("Gateway.initialize"),!t.#e){await Uo(i);let a={...e,corsPolicies:Bo(e.corsPolicies)},u=new t(a,n,r,o);t.#e=u}return t.#e}static purgeGatewayCache(){ne("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new _("Gateway cannot be used before it is initialized");return t.#e}instanceId=crypto.randomUUID();#t;#n;#r=[Tt,vt,$];#o;setupRoutes=()=>{ne("Gateway.setupRoutes");let e=this.routeData,n=Wu(e.versions),r=new Le(n);if(e.routes.length===0)return zn(r,this),Qn(r,this),Kn(r,this),Vo(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(ti(r,this),ei(r,this)),zn(r,this),Qn(r,this),Kn(r,this);for(let i of le)i instanceof oe&&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 f(`Invalid state - No handler on route for path '${i.path}'`);let u=new H({processors:this.#r,handler:a,gateway:this}),c=new we(i);r.addRoute(c,u.execute)}),jo(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 f("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 ne("An error occurred in the user's errorHandler",o),this.#i(e,n,o)}}#i(e,n,r){ne("Gateway.internalErrorResponse");let o={};if(y.instance.isDeno){if(r instanceof I&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let i=z(r.cause);"stack"in i&&(i.stack=oi(i.stack)),o={cause:i}}}return w.internalServerError(e,n,{detail:r.message,...o})}#s(e){let n=new Headers(e.headers);return co.forEach(r=>{n.delete(r)}),y.instance.isDeno&&lo.forEach(r=>{n.delete(r)}),new Request(e,{headers:n})}async handleRequest(e,n){let r=e.headers.get(ze)??e.headers.get(to),o=e.headers.get(Oe);if(!r){r=crypto.randomUUID();let P=new Headers(e.headers);P.set(ze,r),e=new Request(e,{headers:P})}if(["GET","HEAD"].includes(e.method)&&e.body){let P=new Headers(e.headers);P.set(no,"true"),e=new Request(e,{headers:P,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 _(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let p=new Ft(e.headers),R=this.#s(e),g=new S(R,{params:d.params}),b=new $t({logger:a,route:d.routeConfiguration,requestId:r,fetchEvent:n,custom:i,incomingRequestProperties:p}),E=F.initialize(b,g);if(d.routeConfiguration===Yn&&Ve.value?.notFoundHandler!==void 0){let P=this.#n.lookupByPathOnly(l);E.pathOnlyMatches=P.map(v=>v.routeConfiguration).filter(v=>v instanceof we)}try{if(A.addLogger(b,u),!c.pathname.startsWith("/__zuplo")){let k=await Do(g,b);if(k instanceof Response)return k;{let L=F.getContextExtensions(b);g=k,L.latestRequest=g}}[...Ju,...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 v=d.executableHandler;Ku(v,d,e),ne("Gateway.handleRequest - call user handler");let C=await v(g,b);if(ne("Gateway.handleRequest - user handler"),!(C instanceof Response))throw new I(`Invalid Response type from the request handler: ${typeof C}`);if(C.bodyUsed)throw new I("The response object has already been used. Return a new response instead.");if(C.headers.get(ze)===null&&!C.webSocket){let k=new Headers(C.headers);return k.set(ze,r),new Response(C.body,{status:C.status,statusText:C.statusText,headers:k,cf:C.cf})}else return C}catch(P){return ne("Gateway - error executing handler",P),P instanceof I?(a.error(P),u.warn(P)):u.error(P),await this.#i(g,b,P)}}};function Ku(t,e,n){if(ne("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new f(`Invalid state - no routeConfiguration for '${n.method}:${n.url}`):new f(`Invalid state. No handler for request '${n.method}':'${e.routeConfiguration.path}'`)}s(Ku,"checkHandler");var di=s(async(t,e,n)=>{let r=V.instance.routeData.policies,o=Ke([t],r);if(o.length===0)throw new I(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);let i=o[0];return i.handler(e,n,i.options,t)},"invokeInboundPolicy");var Ft=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Tn);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Cn)??void 0}get city(){return this.#e.get(En)??this.#e.get(ro)??void 0}get continent(){return this.#e.get(In)??this.#e.get(oo)??void 0}get country(){return this.#e.get(xn)??this.#e.get(io)??void 0}get latitude(){return this.#e.get(vn)??this.#e.get(ao)??void 0}get longitude(){return this.#e.get(On)??this.#e.get(so)??void 0}get colo(){return this.#e.get(An)??void 0}get postalCode(){return this.#e.get(Sn)??void 0}get metroCode(){return this.#e.get(Ln)??void 0}get region(){return this.#e.get(_n)??void 0}get regionCode(){return this.#e.get(Dn)??void 0}get timezone(){return this.#e.get(kn)??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}}},ve=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},Te=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,n){super("responseSent"),this.request=e,this.response=n}request;response},F=class t{static{s(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,n){if(!t.#e.has(e)){let r=new t(n);return t.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let n=t.#e.get(e);if(!n)throw new I(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return n}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,n,r)=>{for(let o of this.#t)await o(e,n,r)};onResponseSending=async(e,n,r)=>{let o=e;for(let i of this.#n)o=await i(e,n,r);return o}},$t=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=>{F.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{F.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,n,r){let o=s(i=>{try{typeof n=="function"?n(i):n.handleEvent(i)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var zt=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 Yu=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function lr(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!Yu.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}s(lr,"isRestrictedEnvVariableName");function dr(t){return!!t.startsWith("ZUPLO_")}s(dr,"isZuploReadableEnvVariableName");var ot=new Proxy({},{get(t,e){if(lr(String(e))&&!dr(String(e)))return;let n=globalThis,r;return n.process?r=n.process.env[e]:r=n[e],r}});var mi=Ie(ye());var K=(0,mi.debug)("zuplo:runtime:external-service");function gi(){let t,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=y.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 K("There is no external service auth configured for this zup."),new I("There are no external services configured for this zup.");if(typeof t!="string")throw K("Cannot call external service with Request object"),new I("Currently, we only support fetch(<some_string>, ...).");let r=new URL(t).hostname,o={};o["CF-Access-Client-Id"]=e.clientId,o["CF-Access-Client-Secret"]=e.clientSecret;let i;if(e.customServiceMapping&&e.customServiceMapping[r])i=`https://${e.customServiceMapping[r]}`;else if(y.instance.useSha256ServiceRouting){K("Using sha256 service routing");let a=y.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 K("Cannot use sha256 service routing, missing build variables"),new I("Failed to generate fully qualified tunnel url.")}else i=`https://${r}.zuptunnel.com`;return{serviceBaseUrl:i,tunnelHeaders:o}}s(fi,"externalServiceTunnelConfig");async function hi(t,e){let n=gi();if(n)if(K(`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(y.instance.useSha256ServiceRouting){K("Using sha256 service routing");let d=y.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 K("Cannot use sha256 service routing, missing build variables"),new I("Failed to generate fully qualified tunnel url.")}else u=`https://${o}.zuptunnel.com`;let c=new URL(`${u}${r.pathname}${r.search}`);K(`Calling external service: ${c.toString()}`);let l=await _e(c.toString(),i);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:n.clientId,tunnelHost:u}),new I("Could not connect to secure tunnel.");return l}else throw K("Cannot call external service with Request object"),new I("Currently, we only support fetch(<some_string>, ...).");else throw K("There is no external service auth configured for this zup."),new I("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=Qu(r);K(`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 Qu(t){let e=t.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}s(Qu,"sanitizeEnvironmentType");var bi=new Map;bi.set("service:",hi);var _e=globalThis.fetch;globalThis.fetch=function(t,e){let n=Xu(e);if(typeof t=="string"){let r=new URL(t),o=bi.get(r.protocol);return o?o(t,n):_e(t,n)}else return _e(t,n)};var Xu=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 Ri=s(()=>{V.purgeGatewayCache()},"purgeGatewayCache"),Gt=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)=>{y.initialize(this.buildEnvironment,this.runtimeEnvironment);let r;try{r=await V.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 f&&(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:y.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 Ci=Ie(ye());function ec(t){for(var e=[],n=0;n<t.length;){var r=t[n];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:n,value:t[n++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:n++,value:t[n++]});continue}if(r==="{"){e.push({type:"OPEN",index:n,value:t[n++]});continue}if(r==="}"){e.push({type:"CLOSE",index:n,value:t[n++]});continue}if(r===":"){for(var o="",i=n+1;i<t.length;){var a=t.charCodeAt(i);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=t[i++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(n));e.push({type:"NAME",index:n,value:o}),n=i;continue}if(r==="("){var u=1,c="",i=n+1;if(t[i]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(i));for(;i<t.length;){if(t[i]==="\\"){c+=t[i++]+t[i++];continue}if(t[i]===")"){if(u--,u===0){i++;break}}else if(t[i]==="("&&(u++,t[i+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(i));c+=t[i++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(n));if(!c)throw new TypeError("Missing pattern at ".concat(n));e.push({type:"PATTERN",index:n,value:c}),n=i;continue}e.push({type:"CHAR",index:n,value:t[n++]})}return e.push({type:"END",index:n,value:""}),e}s(ec,"lexer");function pr(t,e){e===void 0&&(e={});for(var n=ec(t),r=e.prefixes,o=r===void 0?"./":r,i="[^".concat(nc(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=s(function(J){if(c<n.length&&n[c].type===J)return n[c++].value},"tryConsume"),p=s(function(J){var W=d(J);if(W!==void 0)return W;var Pe=n[c],Ee=Pe.type,Rn=Pe.index;throw new TypeError("Unexpected ".concat(Ee," at ").concat(Rn,", expected ").concat(J))},"mustConsume"),R=s(function(){for(var J="",W;W=d("CHAR")||d("ESCAPED_CHAR");)J+=W;return J},"consumeText");c<n.length;){var g=d("CHAR"),b=d("NAME"),E=d("PATTERN");if(b||E){var P=g||"";o.indexOf(P)===-1&&(l+=P,P=""),l&&(a.push(l),l=""),a.push({name:b||u++,prefix:P,suffix:"",pattern:E||i,modifier:d("MODIFIER")||""});continue}var v=g||d("ESCAPED_CHAR");if(v){l+=v;continue}l&&(a.push(l),l="");var C=d("OPEN");if(C){var P=R(),k=d("NAME")||"",L=d("PATTERN")||"",G=R();p("CLOSE"),a.push({name:k||(L?u++:""),pattern:k&&!L?i:L,prefix:P,suffix:G,modifier:d("MODIFIER")||""});continue}p("END")}return a}s(pr,"parse");function wi(t,e){return tc(pr(t,e),e)}s(wi,"compile");function tc(t,e){e===void 0&&(e={});var n=rc(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 R=c?c[p.name]:void 0,g=p.modifier==="?"||p.modifier==="*",b=p.modifier==="*"||p.modifier==="+";if(Array.isArray(R)){if(!b)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(R.length===0){if(g)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var E=0;E<R.length;E++){var P=o(R[E],p);if(a&&!u[d].test(P))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(P,'"'));l+=p.prefix+P+p.suffix}continue}if(typeof R=="string"||typeof R=="number"){var P=o(String(R),p);if(a&&!u[d].test(P))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(P,'"'));l+=p.prefix+P+p.suffix;continue}if(!g){var v=b?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(v))}}return l}}s(tc,"tokensToFunction");function nc(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(nc,"escapeString");function rc(t){return t&&t.sensitive?"":"i"}s(rc,"flags");var xi=Ie(ye());var oc=(0,xi.debug)("zuplo:runtime"),gr=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"},ic=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],De=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 fr(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){oc("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 f("An unknown error occurred, ensure retries is not negative")}},fr=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:R,appendSessionToken:g,allHeaders:b,singleEncode:E}){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 P,v;(!c||!l)&&([P,v]=sc(this.url,this.headers)),this.service=c||P||"",this.region=l||v||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=R,this.appendSessionToken=g||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(L=>b||!ic.includes(L)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(L=>L+":"+(L==="host"?this.url.host:(this.headers.get(L)||"").replace(/\s+/g," "))).join(`
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,"/");E||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=Ii(this.encodedPath);let k=new Set;this.encodedSearch=[...this.url.searchParams].filter(([L])=>{if(!L)return!1;if(this.service==="s3"){if(k.has(L))return!1;k.add(L)}return!0}).map(L=>L.map(G=>Ii(encodeURIComponent(G)))).sort(([L,G],[J,W])=>L<J?-1:L>J?1:G<W?-1:G>W?1:0).map(L=>L.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 it("AWS4"+this.secretAccessKey,e),i=await it(o,this.region),a=await it(i,this.service);r=await it(a,"aws4_request"),this.cache.set(n,r)}return mr(await it(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,mr(await Ei(await this.canonicalString()))].join(`
53
+ `,pad:c,indent:c+d}:p={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let R=s(g=>{if(u.inlineCharacterLimit===void 0)return g;let h=g.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return h.length<=u.inlineCharacterLimit?h:g.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
54
+ `).replace(new RegExp(p.pad,"g"),c).replace(new RegExp(p.indent,"g"),c+d)},"expandWhiteSpace");if(r.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||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 g="["+p.newline+a.map((h,E)=>{let P=a.length-1===E?p.newline:","+p.newlineOrSpace,x=i(h,u,c+d,l+1);return u.transform&&(x=u.transform(a,E,x)),p.indent+x+P}).join("")+p.pad+"]";return r.pop(),R(g)}if(Je(a)){let g=qo(a);if(u.filter&&(g=g.filter(E=>u.filter?.(a,E))),g.length===0)return"{}";r.push(a);let h="{"+p.newline+g.map((E,P)=>{let x=g.length-1===P?p.newline:","+p.newlineOrSpace,T=typeof E=="symbol",k=!T&&/^[a-z$_][$\w]*$/i.test(E),A=T||k?E:i(E,u,"",l+1),j=i(a[E],u,c+d,l+1);return u.transform&&(j=u.transform(a,E,j)),p.indent+String(A)+": "+j+x}).join("")+p.pad+"}";return r.pop(),R(h)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,g=>g===`
55
+ `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(t,e,n,0)}s(At,"stringifyObject");function ge(t){return t.map(e=>z(e))}s(ge,"makeErrorsSerializable");function Ce(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:se(z(e))}s(Ce,"extractBestMessage");function ii(t){let e=[];return t.forEach(n=>{if(typeof n=="string")e.push(n);else if(Ke(n))if(n.stack)e.push(n.stack);else{let r=At(z(n));e.push(r)}else if(typeof n=="object"){let r=At(n);e.push(r)}else{let r=nr(n);e.push(r)}}),e.join(`
56
+ `)}s(ii,"messagesToMultilineText");function se(t){return typeof t=="string"?t:JSON.stringify(t)}s(se,"stringifyNonString");function nr(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"?Bn(t):"unknown"}s(nr,"stringifyNonStringToText");var Lt=require("jose");async function Ae(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 f("An unknown error occurred, ensure retries is not negative")}s(Ae,"fetchRetry");async function ne({serviceAccount:t,audience:e,expirationTime:n="1h",payload:r={}}){let{clientEmail:o,privateKeyId:i,privateKey:a}=t;return await new Lt.SignJWT(r).setProtectedHeader({alg:"RS256",kid:i}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(n).sign(a)}s(ne,"getTokenFromGcpServiceAccount");async function si(t,e,n){return ai(t,{token:e,returnSecureToken:!0},n)}s(si,"exchangeFirebaseJwtForIdToken");async function _t(t,e,n){return ai(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},n)}s(_t,"exchangeGgpJwtForIdToken");async function ai(t,e,n){let r=await Ae(n,t,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let i;try{let a=await r.text(),u=JSON.parse(a);i={cause:u.error??u}}catch{}throw new I({message:"Could not get token from Google Identity",extensionMembers:i})}return await r.json()}s(ai,"fetchToken");var B=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,Lt.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 kt=class extends U{constructor(n){super();this.options=n}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new tt(this.options)}},Bu="https://logging.googleapis.com/v2/entries:write?alt=json",rr={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},tt=class{static{s(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=y.instance.loggingEnvironmentType,this.#i=y.instance.loggingEnvironmentStage,this.#r=y.instance.deploymentName}#e;#t;#n;#r;#o;#i;async log(e,n){if(e.messages.length===0)return;let r={allMessages:ge(e.messages)};this.#t||(this.#t=await B.init(this.#e));let o=this.#t.projectId??"zuplo-production",i={logName:this.#n,resource:{type:"global"},severity:rr[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=Ce(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 B.init(this.#e));let n=await ne({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await fetch(Bu,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${n}`,"content-type":"application/json;charset=UTF-8"}});r.ok||console.error(r.status,r.statusText,await r.text())};batcher=new C("google-log-transport",1,this.dispatchFunction)};var Dt="gcp";function Ht(t){let e={allMessages:ge(t.messages)},n="zuplo-production",r=Ce(e.allMessages),o={logName:`projects/${n}/logs/runtime-user`,message:r,severity:rr[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(Ht,"gcpLogFormat");var nt=class{static{s(this,"ConsoleTransport")}constructor(e,n){this.#e=e??console,this.#t=n}#e;#t;async log(e){if(this.#t===Dt){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Ht(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 Ut=class extends U{constructor(n){super();this.options=n}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new rt(this.options)}},or="__ddtags",ir="__ddattr",sr=s(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),Gu=s(t=>{let e=Object.keys(t),n=[];return e.forEach(r=>{let o=t[r];o==null?n.push(sr(r)):n.push(`${sr(r)}:${sr(o.toString())}`)}),n.join(",")},"formatTags"),rt=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=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName}#e;#t;#n;#r;#o;async log(e,n){let r={},o=n.custom[or];o&&typeof o=="object"&&Object.assign(r,o);let i=[...e.messages],a=e.messages.findIndex(g=>g[or]!==void 0);a>-1&&(Object.assign(r,i[a][or]),i.splice(a,1));let u={},c=n.custom[ir];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(g=>g[ir]!==void 0);l>-1&&(Object.assign(u,i[l][ir]),i.splice(l,1));let d=ge(i),R={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(n.originalRequest.url).hostname,msg:Ce(d),service:e.loggingId,ddtags:Gu(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(R,u),this.batcher.enqueue(R),n.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new C("data-dog-transport",10,this.dispatchFunction)};var ot=class{static{s(this,"ProcessTransport")}constructor(e,n){this.#e=e,this.#t=n}#e;#t;async log(e){if(this.#t===Dt){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Ht(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 Vu=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:ge(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":y.instance.systemUserAgent,"zp-dn":y.instance.deploymentName??"unknown"}}).catch(a=>{console.error(a)})},"dispatchFunction"),Nt,Mt=class{static{s(this,"RemoteLogTransport")}constructor(e){Nt||(Nt=new C("remote-log-transport",1,Vu(e)))}async log(e,n){Nt.enqueue(e),n.waitUntil(Nt.waitUntilFlushed())}};var Wu={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:Wu[n.level],body:n.messages,attributes:r}},"unifiedFormatter");var Ju=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":y.instance.systemUserAgent,"zp-dn":y.instance.deploymentName??"unknown"}}).catch(a=>{console.error(a)})},"dispatchFunction"),Zt,qt=class{static{s(this,"UnifiedLogTransport")}constructor(e){Zt||(Zt=new C("unified-log-transport",1,Ju(e)))}async log(e,n){Zt.enqueue(e),n.waitUntil(Zt.waitUntilFlushed())}};var ar=(0,ci.debug)("zuplo:logging"),Ft=class{constructor(e){this.serviceProvider=e;this.systemCoreLogger=this.setupSystemCoreLogger(y.instance),this.userCoreLogger=this.setupUserCoreLogger(y.instance)}static{s(this,"LogInitializer")}systemCoreLogger;userCoreLogger;setupSystemCoreLogger(e){let{build:n}=e;ar("Gateway.setupSystemCoreLogger");let r=[],o=this.serviceProvider.getService(Qe);return o?r.push(new ot(o.logger,e.logFormat)):e.isDeno&&r.push(new nt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new qt({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),new Xe(e.systemLogLevel,"system",e.loggingId,n.BUILD_ID,r)}setupUserCoreLogger(e){ar("Gateway.setupUserCoreLogger");let n=[],{runtime:r,build:o}=e,i=this.serviceProvider.getService(Qe);if(i&&i.captureUserLogs===!0?n.push(new ot(i.logger,e.logFormat)):e.isDeno&&n.push(new nt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&n.push(new Mt({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 tt({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 rt({apiKey:r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:a}))}return pe.forEach(a=>{a instanceof U&&n.push(a.getTransport())}),new Xe(e.userLogLevel,"user",e.loggingId,o.BUILD_ID,n)}createRequestLoggers(e,n,r,o,i){ar("Gateway.createRequestLoggers");let a=new Ct(r,o,i),u=new et(e,n,this.systemCoreLogger,a);return{userRequestLogger:new et(e,n,this.userCoreLogger,a),systemRequestLogger:u}}};var Pe=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 ur=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},Le=class{static{s(this,"LookupResult")}constructor(e,n,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=n}executableHandler;routeConfiguration;params},cr=class extends Error{static{s(this,"RouterError")}constructor(e,n){super(e,n)}},_e=class{static{s(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,n){if(!(e instanceof Pe||e instanceof D))throw new _("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 ur(o,i,e,n);Object.freeze(a.config),this.routeEntries.push(a)}catch(i){throw new cr(`addRoute-error: Invalid path '${o}'. '${i.message}'`,{cause:i})}}lookup(e,n){if(typeof e>"u")throw new f(`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 Le(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 Le(o.config,o.executableHandler,a.pathname.groups);n.push(u)}}return n}};var Ku=["/__zuplo/ping","/__zuplo/open-api","/__zuplo/docs","/__zuplo/consumers","/__zuplo/external-users","/__zuplo/assets","/__zuplo/config","/__zuplo/build","/favicon.ico"],re=(0,li.debug)("zuplo:runtime"),Yu=s(t=>{let e=t.findIndex(n=>n.name===We.name);return e>-1?[...t.splice(e),We]:[...t,We]},"setupSystemNoVersion"),G=class t{constructor(e,n,r,o){this.routeData=e;this.runtimeSettings=n;this.schemaValidator=o;re("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(re("Gateway.initialize"),!t.#e){await Uo(i);let a={...e,corsPolicies:Bo(e.corsPolicies)},u=new t(a,n,r,o);t.#e=u}return t.#e}static purgeGatewayCache(){re("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new _("Gateway cannot be used before it is initialized");return t.#e}instanceId=crypto.randomUUID();#t;#n;#r=[St,Tt,$];#o;setupRoutes=()=>{re("Gateway.setupRoutes");let e=this.routeData,n=Yu(e.versions),r=new _e(n);if(e.routes.length===0)return jn(r,this),Qn(r,this),Kn(r,this),Go(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(ti(r,this),ei(r,this)),jn(r,this),Qn(r,this),Kn(r,this);for(let i of pe)i instanceof ie&&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 f(`Invalid state - No handler on route for path '${i.path}'`);let u=new H({processors:this.#r,handler:a,gateway:this}),c=new Pe(i);r.addRoute(c,u.execute)}),Vo(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 f("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 re("An error occurred in the user's errorHandler",o),this.#i(e,n,o)}}#i(e,n,r){re("Gateway.internalErrorResponse");let o={};if(y.instance.isDeno){if(r instanceof I&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let i=z(r.cause);"stack"in i&&(i.stack=oi(i.stack)),o={cause:i}}}return w.internalServerError(e,n,{detail:r.message,...o})}#s(e){let n=new Headers(e.headers);return co.forEach(r=>{n.delete(r)}),y.instance.isDeno&&lo.forEach(r=>{n.delete(r)}),new Request(e,{headers:n})}async handleRequest(e,n){let r=e.headers.get(ze)??e.headers.get(to),o=e.headers.get(Oe);if(!r){r=crypto.randomUUID();let P=new Headers(e.headers);P.set(ze,r),e=new Request(e,{headers:P})}if(["GET","HEAD"].includes(e.method)&&e.body){let P=new Headers(e.headers);P.set(no,"true"),e=new Request(e,{headers:P,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 _(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let p=new $t(e.headers),R=this.#s(e),g=new L(R,{params:d.params}),h=new jt({logger:a,route:d.routeConfiguration,requestId:r,fetchEvent:n,custom:i,incomingRequestProperties:p}),E=F.initialize(h,g);if(d.routeConfiguration===Yn&&Ve.value?.notFoundHandler!==void 0){let P=this.#n.lookupByPathOnly(l);E.pathOnlyMatches=P.map(x=>x.routeConfiguration).filter(x=>x instanceof Pe)}try{if(S.addLogger(h,u),!c.pathname.startsWith("/__zuplo")){let k=await ko(g,h);if(k instanceof Response)return k;{let A=F.getContextExtensions(h);g=k,A.latestRequest=g}}[...Ku,...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;Qu(x,d,e),re("Gateway.handleRequest - call user handler");let T=await x(g,h);if(re("Gateway.handleRequest - user handler"),!(T instanceof Response))throw new I(`Invalid Response type from the request handler: ${typeof T}`);if(T.bodyUsed)throw new I("The response object has already been used. Return a new response instead.");if(T.headers.get(ze)===null&&!T.webSocket){let k=new Headers(T.headers);return k.set(ze,r),new Response(T.body,{status:T.status,statusText:T.statusText,headers:k,cf:T.cf})}else return T}catch(P){return re("Gateway - error executing handler",P),P instanceof I?(a.error(P),u.warn(P)):u.error(P),await this.#i(g,h,P)}}};function Qu(t,e,n){if(re("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new f(`Invalid state - no routeConfiguration for '${n.method}:${n.url}`):new f(`Invalid state. No handler for request '${n.method}':'${e.routeConfiguration.path}'`)}s(Qu,"checkHandler");var di=s(async(t,e,n)=>{let r=G.instance.routeData.policies,o=Ye([t],r);if(o.length===0)throw new I(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);let i=o[0];return i.handler(e,n,i.options,t)},"invokeInboundPolicy");var $t=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Tn);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Sn)??void 0}get city(){return this.#e.get(En)??this.#e.get(ro)??void 0}get continent(){return this.#e.get(In)??this.#e.get(oo)??void 0}get country(){return this.#e.get(xn)??this.#e.get(io)??void 0}get latitude(){return this.#e.get(On)??this.#e.get(ao)??void 0}get longitude(){return this.#e.get(vn)??this.#e.get(so)??void 0}get colo(){return this.#e.get(Cn)??void 0}get postalCode(){return this.#e.get(An)??void 0}get metroCode(){return this.#e.get(Ln)??void 0}get region(){return this.#e.get(_n)??void 0}get regionCode(){return this.#e.get(kn)??void 0}get timezone(){return this.#e.get(Dn)??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}}},Te=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},Se=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,n){super("responseSent"),this.request=e,this.response=n}request;response},F=class t{static{s(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,n){if(!t.#e.has(e)){let r=new t(n);return t.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let n=t.#e.get(e);if(!n)throw new I(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return n}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,n,r)=>{for(let o of this.#t)await o(e,n,r)};onResponseSending=async(e,n,r)=>{let o=e;for(let i of this.#n)o=await i(e,n,r);return o}},jt=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=>{F.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{F.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,n,r){let o=s(i=>{try{typeof n=="function"?n(i):n.handleEvent(i)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var ae=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 Xu=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function lr(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!Xu.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}s(lr,"isRestrictedEnvVariableName");function dr(t){return!!t.startsWith("ZUPLO_")}s(dr,"isZuploReadableEnvVariableName");var it=new Proxy({},{get(t,e){if(lr(String(e))&&!dr(String(e)))return;let n=globalThis,r;return n.process?r=n.process.env[e]:r=n[e],r}});var mi=xe(be());var Y=(0,mi.debug)("zuplo:runtime:external-service");function gi(){let t,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=y.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 Y("There is no external service auth configured for this zup."),new I("There are no external services configured for this zup.");if(typeof t!="string")throw Y("Cannot call external service with Request object"),new I("Currently, we only support fetch(<some_string>, ...).");let r=new URL(t).hostname,o={};o["CF-Access-Client-Id"]=e.clientId,o["CF-Access-Client-Secret"]=e.clientSecret;let i;if(e.customServiceMapping&&e.customServiceMapping[r])i=`https://${e.customServiceMapping[r]}`;else if(y.instance.useSha256ServiceRouting){Y("Using sha256 service routing");let a=y.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 Y("Cannot use sha256 service routing, missing build variables"),new I("Failed to generate fully qualified tunnel url.")}else i=`https://${r}.zuptunnel.com`;return{serviceBaseUrl:i,tunnelHeaders:o}}s(fi,"externalServiceTunnelConfig");async function hi(t,e){let n=gi();if(n)if(Y(`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(y.instance.useSha256ServiceRouting){Y("Using sha256 service routing");let d=y.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 Y("Cannot use sha256 service routing, missing build variables"),new I("Failed to generate fully qualified tunnel url.")}else u=`https://${o}.zuptunnel.com`;let c=new URL(`${u}${r.pathname}${r.search}`);Y(`Calling external service: ${c.toString()}`);let l=await ke(c.toString(),i);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:n.clientId,tunnelHost:u}),new I("Could not connect to secure tunnel.");return l}else throw Y("Cannot call external service with Request object"),new I("Currently, we only support fetch(<some_string>, ...).");else throw Y("There is no external service auth configured for this zup."),new I("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=ec(r);Y(`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 ec(t){let e=t.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}s(ec,"sanitizeEnvironmentType");var bi=new Map;bi.set("service:",hi);var ke=globalThis.fetch;globalThis.fetch=function(t,e){let n=tc(e);if(typeof t=="string"){let r=new URL(t),o=bi.get(r.protocol);return o?o(t,n):ke(t,n)}else return ke(t,n)};var tc=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 Ri=s(()=>{G.purgeGatewayCache()},"purgeGatewayCache"),zt=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)=>{y.initialize(this.buildEnvironment,this.runtimeEnvironment);let r;try{r=await G.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 f&&(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:y.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=xe(be());function nc(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(nc,"lexer");function pr(t,e){e===void 0&&(e={});for(var n=nc(t),r=e.prefixes,o=r===void 0?"./":r,i="[^".concat(oc(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=s(function(W){if(c<n.length&&n[c].type===W)return n[c++].value},"tryConsume"),p=s(function(W){var J=d(W);if(J!==void 0)return J;var Ee=n[c],Ie=Ee.type,Rn=Ee.index;throw new TypeError("Unexpected ".concat(Ie," at ").concat(Rn,", expected ").concat(W))},"mustConsume"),R=s(function(){for(var W="",J;J=d("CHAR")||d("ESCAPED_CHAR");)W+=J;return W},"consumeText");c<n.length;){var g=d("CHAR"),h=d("NAME"),E=d("PATTERN");if(h||E){var P=g||"";o.indexOf(P)===-1&&(l+=P,P=""),l&&(a.push(l),l=""),a.push({name:h||u++,prefix:P,suffix:"",pattern:E||i,modifier:d("MODIFIER")||""});continue}var x=g||d("ESCAPED_CHAR");if(x){l+=x;continue}l&&(a.push(l),l="");var T=d("OPEN");if(T){var P=R(),k=d("NAME")||"",A=d("PATTERN")||"",j=R();p("CLOSE"),a.push({name:k||(A?u++:""),pattern:k&&!A?i:A,prefix:P,suffix:j,modifier:d("MODIFIER")||""});continue}p("END")}return a}s(pr,"parse");function wi(t,e){return rc(pr(t,e),e)}s(wi,"compile");function rc(t,e){e===void 0&&(e={});var n=ic(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 R=c?c[p.name]:void 0,g=p.modifier==="?"||p.modifier==="*",h=p.modifier==="*"||p.modifier==="+";if(Array.isArray(R)){if(!h)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(R.length===0){if(g)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var E=0;E<R.length;E++){var P=o(R[E],p);if(a&&!u[d].test(P))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(P,'"'));l+=p.prefix+P+p.suffix}continue}if(typeof R=="string"||typeof R=="number"){var P=o(String(R),p);if(a&&!u[d].test(P))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(P,'"'));l+=p.prefix+P+p.suffix;continue}if(!g){var x=h?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(x))}}return l}}s(rc,"tokensToFunction");function oc(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(oc,"escapeString");function ic(t){return t&&t.sensitive?"":"i"}s(ic,"flags");var xi=xe(be());var sc=(0,xi.debug)("zuplo:runtime"),gr=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"},ac=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],De=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 fr(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){sc("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 f("An unknown error occurred, ensure retries is not negative")}},fr=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:R,appendSessionToken:g,allHeaders:h,singleEncode:E}){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 P,x;(!c||!l)&&([P,x]=uc(this.url,this.headers)),this.service=c||P||"",this.region=l||x||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=R,this.appendSessionToken=g||this.service==="iotdevicegateway",this.headers.delete("Host");let T=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"),T.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&T.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(A=>h||!ac.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
+ `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!T.has("X-Amz-Expires")&&T.set("X-Amz-Expires","86400"),T.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),T.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),T.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,"/");E||(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(j=>Ii(encodeURIComponent(j)))).sort(([A,j],[W,J])=>A<W?-1:A>W?1:j<J?-1:j>J?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 mr(await st(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,mr(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 I("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=mr(await Ei(this.body||""))}return e}};async function it(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?gr.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",n,gr.encode(e))}s(it,"hmac");async function Ei(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?gr.encode(t):t)}s(Ei,"hash");function mr(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}s(mr,"buf2hex");function Ii(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}s(Ii,"encodeRfc3986");function sc(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(sc,"guessServiceRegion");function ac(t){return t>64&&t<91?t-65:t>96&&t<123?t-71:t>47&&t<58?t+4:t===43?62:t===47?63:0}s(ac,"b64ToUint6");function Oi(t,e){let n=t.replace(/[^A-Za-z0-9+/]/g,""),r=n.length,o=e?Math.ceil((r*3+1>>2)/e)*e:r*3+1>>2,i=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=ac(n.charCodeAt(d))<<6*(3-u),u===3||r-d===1){for(a=0;a<3&&l<o;)i[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return i}s(Oi,"base64Decode");function Bt(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}s(Bt,"uint6ToB64");function vi(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(Bt(o>>>18&63),Bt(o>>>12&63),Bt(o>>>6&63),Bt(o&63)),o=0);return n.substring(0,n.length-2+e)+(e===2?"":e===1?"=":"==")}s(vi,"base64Encode");function ke(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}s(ke,"numberToString");function uc(t){let e=t.getTimezoneOffset(),n=Math.abs(e),r=e>0?"-":"+",o=ke(Math.floor(n/60)),i=ke(n%60);return`${r}${o}${i}`}s(uc,"getCLFOffset");function hr(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=ke(t.getDate()),r=e[t.getMonth()],o=t.getFullYear(),i=ke(t.getHours()),a=ke(t.getMinutes()),u=ke(t.getSeconds()),c=uc(t);return`${n}/${r}/${o}:${i}:${a}:${u} ${c}`}s(hr,"toCLFDate");var Ti=(0,Ci.debug)("zuplo:runtime"),cc="X-Amzn-Trace-Id",lc="x-amzn-errortype",Ai=[],dc=s(async(t,e,n)=>{let r=n;for await(let o of Ai)r=await o(t,e,n);return r},"onSendingAwsLambdaEvent"),j=class extends I{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,n){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=n.get(cc)??void 0,this.errorType=n.get(lc)??void 0}},Si={addSendingAwsLambdaEventHook:t=>{Ai.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 f("awsAccessKeyId is not set in the handler options");if(!r)throw new f("secretAccessKey is not set in the handler options");if(!o)throw new f("region is not set in the handler options");if(!i)throw new f("functionName is not set in the handler options");let l=new De({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,R]=await fc(t,{binaryMediaTypes:c}),{options:g}=e.route.handler,b;g&&typeof g=="object"&&"payloadFormatVersion"in g&&g.payloadFormatVersion==="2.0"?b=gc(t,e):b=await mc(t,e,{useAwsResourcePathStyle:u}),Ti("Calling onSendingAwsLambdaEvent hook");let E=await dc(t,e,b);E.body=p,E.isBase64Encoded=R;let P=await l.fetch(d,{body:JSON.stringify(E)});try{return pc(P)}catch(v){if(v instanceof j){let C=g&&typeof g=="object"&&"returnAmazonTraceIdHeader"in g&&g.returnAmazonTraceIdHeader&&v.traceId?{AMZN_TRACE_ID_HEADER:v.traceId}:void 0;return w.internalServerError(t,e,void 0,C)}throw v}}s(Li,"awsLambdaHandler");async function pc(t){let e;try{e=await t.json()}catch{throw new j("Lambda response did not contain valid JSON",t.headers)}if(t.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new j(e.message,t.headers):new j(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new j(e.errorMessage,t.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:t.status,headers:{"content-type":"application/json"}});let n=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new j(`Response headers must be an object. Received ${typeof e.headers}`,t.headers);for(let[o,i]of Object.entries(e.headers))n.set(o,i)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new j(`Response cookies must be an array. Received ${typeof e.cookies}`,t.headers);n.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new j(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,t.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new j("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new j("Response was set to base64 encoded but body was not a string",t.headers);r=Oi(e.body)}else"body"in e&&typeof e.body=="string"?r=e.statusCode===204&&e.body===""?null:e.body:"body"in e&&e.body!==null&&e.body!==void 0?r=JSON.stringify(e.body):r=null;if(r!==null&&"bodyEncoding"in e){if(typeof e.bodyEncoding!="string"||!(e.bodyEncoding==="gzip"||e.bodyEncoding==="deflate"))throw new j(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,t.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:n,status:e.statusCode})}s(pc,"getResponse");async function mc(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:hr(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:yc(e.route.path,n),stage:null},pathParameters:t.params,stageVariables:null}}s(mc,"buildEventVersion1");function gc(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:hr(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}s(gc,"buildEventVersion2");async function fc(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&&hc(e,o)){let i=await t.arrayBuffer();n=vi(new Uint8Array(i)),r=!0}else n=await t.clone().text();return[n,r]}s(fc,"getBodyResult");function hc(t,e){let n=e.split(";")[0].trim().toLowerCase();return t.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===n)>-1}s(hc,"matchesContentType");function yc(t,e=!1){if(!e)return t;let n=pr(t),r=wi(t),o={};return n.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),r(o)}s(yc,"getResourcePath");var bc=[502,503,504];async function He(t,e){if(bc.includes(t.status)){let n=A.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(He,"logBadGatewayResponses");var yr;function ge(t){if(yr===void 0){let n=y.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(n??"")||(n="debug"),yr=n}return t.log[yr]}s(ge,"getHandlerUserLogFunction");async function _i(t,e){let n=y.instance.build.BUILD_ID,{buildAssetsUrl:r}=y.instance,o=e.route.handler.options,{openApiFilePath:i}=o;if(!i)throw new f("Open API Spec Handler must have 'openApiFilePath' specified");let a=Rc(i);if(!a.isValid)throw new f(a.error);let u;y.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 w.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 He(l,e),l}s(_i,"openApiSpecHandler");var Rc=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 Di(t,e){let n=e.route.handler.options;if(!n.location)throw new f("Redirect Handler must have 'location' specified");let r=n.status??302;return new Response(null,{status:r,headers:{location:n.location}})}s(Di,"redirectHandler");function wc(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(wc,"join");async function ki(t,e){let n=ge(e),r=e.route.handler.options,o=r.forwardSearch!==!1;if(!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new f("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(t.url),u=r.__rewriteFunction(t,i),c=wc(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}),R=Date.now()-d;return n(`URL Forward received response ${p.status} - ${p.statusText} in ${R}ms`),He(p,e),p}s(ki,"urlForwardHandler");var Pc=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=ge(e),r=e.route.handler.options,o=r.forwardSearch!==!1,i=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new f("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=o?Pc(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`),He(d,e),d}s(Hi,"urlRewriteHandler");async function Ui(t,e){let n=y.instance,r=e.route.handler.options,o=ge(e);if(!r||!r.rewritePattern)throw new f("WebSocket Handler must have option 'rewritePattern' specified");let i=t.headers.get("Upgrade");if(!i||i!=="websocket")return w.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new f("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno){let p=new Headers(t.headers);if(u.startsWith("service:")){let g=await fi(u),b=new URL(u);u=new URL(`${g.serviceBaseUrl}${b.pathname}${b.search}`).toString();for(let P in g.tunnelHeaders)p.set(P,g.tunnelHeaders[P])}u=u.replace(/^(http)/,"ws");try{if(p.get("Authorization")){let g=p.get("Authorization")?.replace("Bearer ","");u+=`?apiKey=${g}`}}catch{}let R=JSON.stringify({url:u});return new Response(R,{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(),R=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${p}'`;throw new Error(R)}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 br=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 f(`${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=y.instance,r=e.route.handler.options,o=ge(e);if(!r||!r.rewritePattern)throw new f("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let i=t.headers.get("Upgrade");if(!i||i!=="websocket")return w.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new f("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno)throw new f("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 v=await l.text(),C=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${v}'`;throw new Error(C)}let d=new WebSocketPair,[p,R]=Object.values(d),g=Date.now()-c;o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${g}ms`);let b=l.webSocket;b.accept(),R.accept();let E=r.policies&&r.policies.inbound?br(r.policies.inbound,"inbound"):[],P=r.policies&&r.policies.outbound?br(r.policies.outbound,"outbound"):[];return Mi(R,b,t,e,E),Mi(b,R,t,e,P),new Response(null,{status:101,webSocket:p})}s(Zi,"webSocketPipelineHandler");var Vt=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=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName}#e;#t;#n;#r;#o;async log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:ie(z(r)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{e.length!==0&&await fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new T("dyna-trace-log-transport",10,this.#i)};var jt=class extends U{constructor(n){super();this.options=n}static{s(this,"LokiLoggingPlugin")}getTransport(){return new Pr(this.options)}},wr=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 Ec(t,e){return btoa(`${t}:${e}`)}s(Ec,"createBasicDigest");var Pr=class{static{s(this,"LokiTransport")}constructor(e){this.#e=e.url,this.#t=Ec(e.username,e.password),this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName}#e;#t;#n;#r;#o;async log(e,n){let r=new wr(e.level,this.#n,this.#r,this.#o,e.requestId);e.messages.forEach(o=>{let i={stream:r,message:ie(z(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(i)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=e=>{let n={streams:[]};return e.forEach(r=>{let o=n.streams.find(i=>i.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},n.streams.push(o)),o.values.push([r.nanoSecondEpoch,r.message])}),n};#s=async e=>{if(e.length===0)return;let n=this.#i(e);await fetch(this.#e,{method:"POST",body:JSON.stringify(n),headers:{"content-type":"application/json",authorization:`Basic ${this.#t}`}})};batcher=new T("loki-log-transport",10,this.#s)};var Jt=class extends U{constructor(n){super();this.options=n}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new Er(this.options)}},Er=class{static{s(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=y.instance.loggingEnvironmentType,this.#r=y.instance.loggingEnvironmentStage,this.#t=y.instance.deploymentName}#e;#t;#n;#r;#o;#i;async log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:ie(z(r)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let n=e.map(o=>JSON.stringify(o)).join(`
61
- `),r=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&r.set("X-Sumo-Name",this.#i),this.#o&&r.set("X-Sumo-Category",this.#o),await fetch(this.#e,{method:"POST",body:n,headers:r})};batcher=new T("sumo-logic-log-transport",10,this.#s)};var Ic="d3a5b78f-8236-48f5-b1df-4fe269d41172",Wt=class extends U{constructor(n){super();this.options=n}static{s(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new Ir(this.options)}},Ir=class{static{s(this,"VMWareLogInsightTransport")}constructor(e){let n;try{n=new URL(e.url)}catch{throw new f(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=n.origin,this.#n=y.instance.loggingEnvironmentType,this.#r=y.instance.loggingEnvironmentStage,this.#t=y.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=nr(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/${Ic}`,{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 T("vmware-log-insights-log-transport",10,this.#s)};var Kt=class extends U{constructor(n){super();this.options=n}static{s(this,"AWSLoggingPlugin")}getTransport(){return new xr(this.options)}},xr=class{static{s(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new T("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 De({accessKeyId:e,secretAccessKey:o,service:"logs",region:i}),this.logGroupName=r,this.logStreamName=n,this.region=i,this.environmentType=y.instance.loggingEnvironmentType,this.environment=y.instance.deploymentName}async log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:ie(z(r)),severity:e.level,source:e.logSource,environment:this.environment,requestId:e.requestId,environmentType:this.environmentType,rayId:e.rayId===null?void 0:e.rayId})};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}};var Or=new WeakMap,xc={tags:[]},Yt=class extends de{constructor(n){super();this.options=n}static{s(this,"DataDogMetricsPlugin")}getTransport(){return new vr(this.options)}static setContext(n,r){let o=Or.get(n);o||(o=xc);let i=Object.assign({...o},r);Or.set(n,i)}},vr=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 T("data-dog-metrics-transport",10,this.dispatchFunction,A.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 Tr(await r.text())}},Tr=class t extends Error{static{s(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var Cr=new WeakMap,Oc={dimensions:[]},Qt=class extends de{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=Oc);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 T("dynatrace-metrics-transport",10,this.dispatchFunction,A.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 Sr(await r.text())}},Sr=class t extends Error{static{s(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var Xt=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 en=class extends oe{static{s(this,"AuditLogPlugin")}constructor(e,n){super(),this.#e=e,this.#t=n}#e;#t;async initialize(e){new Lr(e,this.#e,this.#t)}},qi=s(t=>{let e={};return t.forEach((n,r)=>{e[r]=n}),e},"serializableHeaders"),vc={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},Lr=class{static{s(this,"AuditPluginImpl")}constructor(e,n,r){this.#t=n;let o={...vc};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 T("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(R=>{n.log.error(R)});n.waitUntil(p)}),e}catch(r){return n.log.error(r),e}}};var _r=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}},re=class extends _r{static{s(this,"StripeSignatureVerificationError")}header;payload;constructor(e,n,r={}){super(r),this.header=e,this.payload=n}};var Tc="v1",Cc=300;async function Fi(t,e,n,r=Cc,o){return await Sc(t,e,n,r,o),t instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(t)):JSON.parse(t)}s(Fi,"constructEventAsync");function Ac(t,e){return`${e.timestamp}.${t}`}s(Ac,"makeHMACContent");async function Sc(t,e,n,r,o){let{decodedHeader:i,decodedPayload:a,details:u,suspectPayloadType:c}=Lc(t,e,Tc),l=/\s/.test(n),d=await Hc(Ac(a,u),n);return _c(a,i,u,d,r,c,l,o)}s(Sc,"verifyHeaderAsync");function Lc(t,e,n){if(!t)throw new re(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 re(e,t,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=Dc(a,n);if(!u||u.timestamp===-1)throw new re(a,i,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new re(a,i,{message:"No signatures found with expected scheme"});return{decodedPayload:i,decodedHeader:a,details:u,suspectPayloadType:r}}s(Lc,"parseEventDetails");function _c(t,e,n,r,o,i,a,u){let c=!!n.signatures.filter(R=>kc(R,r)).length,l=`
60
+ `)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new I("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=mr(await Ei(this.body||""))}return e}};async function st(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?gr.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",n,gr.encode(e))}s(st,"hmac");async function Ei(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?gr.encode(t):t)}s(Ei,"hash");function mr(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}s(mr,"buf2hex");function Ii(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}s(Ii,"encodeRfc3986");function uc(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(uc,"guessServiceRegion");function cc(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(cc,"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|=cc(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 Bt(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}s(Bt,"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(Bt(o>>>18&63),Bt(o>>>12&63),Bt(o>>>6&63),Bt(o&63)),o=0);return n.substring(0,n.length-2+e)+(e===2?"":e===1?"=":"==")}s(Oi,"base64Encode");function He(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}s(He,"numberToString");function lc(t){let e=t.getTimezoneOffset(),n=Math.abs(e),r=e>0?"-":"+",o=He(Math.floor(n/60)),i=He(n%60);return`${r}${o}${i}`}s(lc,"getCLFOffset");function hr(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=He(t.getDate()),r=e[t.getMonth()],o=t.getFullYear(),i=He(t.getHours()),a=He(t.getMinutes()),u=He(t.getSeconds()),c=lc(t);return`${n}/${r}/${o}:${i}:${a}:${u} ${c}`}s(hr,"toCLFDate");var Ti=(0,Si.debug)("zuplo:runtime"),dc="X-Amzn-Trace-Id",pc="x-amzn-errortype",Ci=[],mc=s(async(t,e,n)=>{let r=n;for await(let o of Ci)r=await o(t,e,n);return r},"onSendingAwsLambdaEvent"),V=class extends I{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,n){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=n.get(dc)??void 0,this.errorType=n.get(pc)??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 f("awsAccessKeyId is not set in the handler options");if(!r)throw new f("secretAccessKey is not set in the handler options");if(!o)throw new f("region is not set in the handler options");if(!i)throw new f("functionName is not set in the handler options");let l=new De({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,R]=await yc(t,{binaryMediaTypes:c}),{options:g}=e.route.handler,h;g&&typeof g=="object"&&"payloadFormatVersion"in g&&g.payloadFormatVersion==="2.0"?h=hc(t,e):h=await fc(t,e,{useAwsResourcePathStyle:u}),Ti("Calling onSendingAwsLambdaEvent hook");let E=await mc(t,e,h);E.body=p,E.isBase64Encoded=R;let P=await l.fetch(d,{body:JSON.stringify(E)});try{return gc(P)}catch(x){if(x instanceof V){let T=g&&typeof g=="object"&&"returnAmazonTraceIdHeader"in g&&g.returnAmazonTraceIdHeader&&x.traceId?{AMZN_TRACE_ID_HEADER:x.traceId}:void 0;return w.internalServerError(t,e,void 0,T)}throw x}}s(Li,"awsLambdaHandler");async function gc(t){let e;try{e=await t.json()}catch{throw new V("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 V(e.message,t.headers):new V(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new V(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 V(`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 V(`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 V(`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 V("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new V("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 V(`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(gc,"getResponse");async function fc(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:hr(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Rc(e.route.path,n),stage:null},pathParameters:t.params,stageVariables:null}}s(fc,"buildEventVersion1");function hc(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:hr(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}s(hc,"buildEventVersion2");async function yc(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&&bc(e,o)){let i=await t.arrayBuffer();n=Oi(new Uint8Array(i)),r=!0}else n=await t.clone().text();return[n,r]}s(yc,"getBodyResult");function bc(t,e){let n=e.split(";")[0].trim().toLowerCase();return t.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===n)>-1}s(bc,"matchesContentType");function Rc(t,e=!1){if(!e)return t;let n=pr(t),r=wi(t),o={};return n.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),r(o)}s(Rc,"getResourcePath");var wc=[502,503,504];async function Ue(t,e){if(wc.includes(t.status)){let n=S.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(Ue,"logBadGatewayResponses");var yr;function fe(t){if(yr===void 0){let n=y.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(n??"")||(n="debug"),yr=n}return t.log[yr]}s(fe,"getHandlerUserLogFunction");async function _i(t,e){let n=y.instance.build.BUILD_ID,{buildAssetsUrl:r}=y.instance,o=e.route.handler.options,{openApiFilePath:i}=o;if(!i)throw new f("Open API Spec Handler must have 'openApiFilePath' specified");let a=Pc(i);if(!a.isValid)throw new f(a.error);let u;y.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 w.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 Ue(l,e),l}s(_i,"openApiSpecHandler");var Pc=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 f("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 Ec(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(Ec,"join");async function Di(t,e){let n=fe(e),r=e.route.handler.options,o=r.forwardSearch!==!1;if(!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new f("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(t.url),u=r.__rewriteFunction(t,i),c=Ec(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}),R=Date.now()-d;return n(`URL Forward received response ${p.status} - ${p.statusText} in ${R}ms`),Ue(p,e),p}s(Di,"urlForwardHandler");var Ic=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=fe(e),r=e.route.handler.options,o=r.forwardSearch!==!1,i=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new f("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=o?Ic(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`),Ue(d,e),d}s(Hi,"urlRewriteHandler");async function Ui(t,e){let n=y.instance,r=e.route.handler.options,o=fe(e);if(!r||!r.rewritePattern)throw new f("WebSocket Handler must have option 'rewritePattern' specified");let i=t.headers.get("Upgrade");if(!i||i!=="websocket")return w.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new f("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno){let p=new Headers(t.headers);if(u.startsWith("service:")){let g=await fi(u),h=new URL(u);u=new URL(`${g.serviceBaseUrl}${h.pathname}${h.search}`).toString();for(let P in g.tunnelHeaders)p.set(P,g.tunnelHeaders[P])}u=u.replace(/^(http)/,"ws");try{if(p.get("Authorization")){let g=p.get("Authorization")?.replace("Bearer ","");u+=`?apiKey=${g}`}}catch{}let R=JSON.stringify({url:u});return new Response(R,{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(),R=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${p}'`;throw new Error(R)}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 br=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 f(`${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=y.instance,r=e.route.handler.options,o=fe(e);if(!r||!r.rewritePattern)throw new f("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let i=t.headers.get("Upgrade");if(!i||i!=="websocket")return w.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new f("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(t,a),c=Date.now();if(o(`Attempting WebSocket connection to '${u}'`),n.isDeno)throw new f("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(),T=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${x}'`;throw new Error(T)}let d=new WebSocketPair,[p,R]=Object.values(d),g=Date.now()-c;o(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${g}ms`);let h=l.webSocket;h.accept(),R.accept();let E=r.policies&&r.policies.inbound?br(r.policies.inbound,"inbound"):[],P=r.policies&&r.policies.outbound?br(r.policies.outbound,"outbound"):[];return Mi(R,h,t,e,E),Mi(h,R,t,e,P),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=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName}#e;#t;#n;#r;#o;async log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:se(z(r)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{e.length!==0&&await fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new C("dyna-trace-log-transport",10,this.#i)};var Vt=class extends U{constructor(n){super();this.options=n}static{s(this,"LokiLoggingPlugin")}getTransport(){return new Pr(this.options)}},wr=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 xc(t,e){return btoa(`${t}:${e}`)}s(xc,"createBasicDigest");var Pr=class{static{s(this,"LokiTransport")}constructor(e){this.#e=e.url,this.#t=xc(e.username,e.password),this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName}#e;#t;#n;#r;#o;async log(e,n){let r=new wr(e.level,this.#n,this.#r,this.#o,e.requestId);e.messages.forEach(o=>{let i={stream:r,message:se(z(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(i)}),n.waitUntil(this.batcher.waitUntilFlushed())}#i=e=>{let n={streams:[]};return e.forEach(r=>{let o=n.streams.find(i=>i.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},n.streams.push(o)),o.values.push([r.nanoSecondEpoch,r.message])}),n};#s=async e=>{if(e.length===0)return;let n=this.#i(e);await fetch(this.#e,{method:"POST",body:JSON.stringify(n),headers:{"content-type":"application/json",authorization:`Basic ${this.#t}`}})};batcher=new C("loki-log-transport",10,this.#s)};var Wt=class extends U{constructor(n){super();this.options=n}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new Er(this.options)}},Er=class{static{s(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=y.instance.loggingEnvironmentType,this.#r=y.instance.loggingEnvironmentStage,this.#t=y.instance.deploymentName}#e;#t;#n;#r;#o;#i;async log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:se(z(r)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let n=e.map(o=>JSON.stringify(o)).join(`
61
+ `),r=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&r.set("X-Sumo-Name",this.#i),this.#o&&r.set("X-Sumo-Category",this.#o),await fetch(this.#e,{method:"POST",body:n,headers:r})};batcher=new C("sumo-logic-log-transport",10,this.#s)};var vc="d3a5b78f-8236-48f5-b1df-4fe269d41172",Jt=class extends U{constructor(n){super();this.options=n}static{s(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new Ir(this.options)}},Ir=class{static{s(this,"VMWareLogInsightTransport")}constructor(e){let n;try{n=new URL(e.url)}catch{throw new f(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=n.origin,this.#n=y.instance.loggingEnvironmentType,this.#r=y.instance.loggingEnvironmentStage,this.#t=y.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=nr(a);u&&o.fields.push({name:i,content:u})}),this.#o&&(o=this.#o(o)),o}#s=async e=>{if(e.length===0)return;let n=await fetch(`${this.#e}/api/v1/events/ingest/${vc}`,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8"}});if(n.status!==200)try{let r=await n.text();console.error("Error logging to Log Insight",r)}catch(r){console.error(r)}};batcher=new C("vmware-log-insights-log-transport",10,this.#s)};var Kt=class extends U{constructor(n){super();this.options=n}static{s(this,"AWSLoggingPlugin")}getTransport(){return new xr(this.options)}},xr=class{static{s(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new C("aws-log-transport",10,async e=>{if(e.length===0)return;let n=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:n,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}})});constructor({accessKeyId:e,logStreamName:n,logGroupName:r,secretAccessKey:o,region:i}){this.awsClient=new De({accessKeyId:e,secretAccessKey:o,service:"logs",region:i}),this.logGroupName=r,this.logStreamName=n,this.region=i,this.environmentType=y.instance.loggingEnvironmentType,this.environment=y.instance.deploymentName}async log(e,n){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:se(z(r)),severity:e.level,source:e.logSource,environment:this.environment,requestId:e.requestId,environmentType:this.environmentType,rayId:e.rayId===null?void 0:e.rayId})};this.batcher.enqueue(o)}),n.waitUntil(this.batcher.waitUntilFlushed())}};var vr=new WeakMap,Oc={tags:[]},Yt=class extends me{constructor(n){super();this.options=n}static{s(this,"DataDogMetricsPlugin")}getTransport(){return new Or(this.options)}static setContext(n,r){let o=vr.get(n);o||(o=Oc);let i=Object.assign({...o},r);vr.set(n,i)}},Or=class{static{s(this,"DataDogMetricsTransport")}#e;#t;#n;#r;#o;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://api.datadoghq.com/api/v2/series",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.#r=e.tags??[]}pushMetrics(e,n){this.#i===void 0&&(this.#i=new C("data-dog-metrics-transport",10,this.dispatchFunction,S.getLogger(n)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(vr.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 Tr(await r.text())}},Tr=class t extends Error{static{s(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var Sr=new WeakMap,Tc={dimensions:[]},Qt=class extends me{constructor(n){super();this.options=n}static{s(this,"DynatraceMetricsPlugin")}getTransport(){return new Cr(this.options)}static setContext(n,r){let o=Sr.get(n);o||(o=Tc);let i=Object.assign({...o},r);Sr.set(n,i)}},Cr=class{static{s(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#n;#r=void 0;constructor(e){this.apiToken=e.apiToken,this.#e=e.url,this.#t=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#n=e.include??{},this.dimensions=e.dimensions??[]}pushMetrics(e,n){this.#r===void 0&&(this.#r=new C("dynatrace-metrics-transport",10,this.dispatchFunction,S.getLogger(n)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(Sr.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 Ar(await r.text())}},Ar=class t extends Error{static{s(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};var Xt=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 en=class extends ie{static{s(this,"AuditLogPlugin")}constructor(e,n){super(),this.#e=e,this.#t=n}#e;#t;async initialize(e){new Lr(e,this.#e,this.#t)}},qi=s(t=>{let e={};return t.forEach((n,r)=>{e[r]=n}),e},"serializableHeaders"),Sc={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},Lr=class{static{s(this,"AuditPluginImpl")}constructor(e,n,r){this.#t=n;let o={...Sc};r?.requestFilter&&(o.requestFilter=r.requestFilter),r?.include?.request&&Object.assign(o,r.include.request),r?.include?.response&&Object.assign(o,r.include.response),this.#e=o,e.addRequestHook(this.#i),this.#n=new C("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,n,r,o,i,a)=>{try{let u={timestamp:o,durationMs:i,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:n.url,method:n.method,headers:this.#e.include?.request?.headers?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(R=>{n.log.error(R)});n.waitUntil(p)}),e}catch(r){return n.log.error(r),e}}};var _r=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}},oe=class extends _r{static{s(this,"StripeSignatureVerificationError")}header;payload;constructor(e,n,r={}){super(r),this.header=e,this.payload=n}};var Cc="v1",Ac=300;async function Fi(t,e,n,r=Ac,o){return await _c(t,e,n,r,o),t instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(t)):JSON.parse(t)}s(Fi,"constructEventAsync");function Lc(t,e){return`${e.timestamp}.${t}`}s(Lc,"makeHMACContent");async function _c(t,e,n,r,o){let{decodedHeader:i,decodedPayload:a,details:u,suspectPayloadType:c}=kc(t,e,Cc),l=/\s/.test(n),d=await Nc(Lc(a,u),n);return Dc(a,i,u,d,r,c,l,o)}s(_c,"verifyHeaderAsync");function kc(t,e,n){if(!t)throw new oe(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 oe(e,t,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=Hc(a,n);if(!u||u.timestamp===-1)throw new oe(a,i,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new oe(a,i,{message:"No signatures found with expected scheme"});return{decodedPayload:i,decodedHeader:a,details:u,suspectPayloadType:r}}s(kc,"parseEventDetails");function Dc(t,e,n,r,o,i,a,u){let c=!!n.signatures.filter(R=>Uc(R,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
- Note: The provided signing secret contains whitespace. This often indicates an extra newline or space is in the value`:"";if(!c)throw i?new re(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.
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 oe(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.
66
66
  Signature verification is impossible without access to the original signed material.
67
67
  `+l+`
68
- `+d}):new re(e,t,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
68
+ `+d}):new oe(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 re(e,t,{message:"Timestamp outside the tolerance zone"});return!0}s(_c,"validateComputedSignature");function Dc(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(Dc,"parseHeader");function kc(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(kc,"secureCompare");async function Hc(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(Hc,"computeHMACSignatureAsync");var Dr=new Array(256);for(let t=0;t<Dr.length;t++)Dr[t]=t.toString(16).padStart(2,"0");function M(t,e){let n=s((i,a,u)=>{let c=t[i];if(!(u&&c===void 0)){if(c===void 0)throw new f(`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 f(`Value of '${String(i)}' on policy '${e}' must be an array. Received type ${typeof c}.`);if(typeof c!==a)throw new f(`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 f(`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 f(`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(M,"optionValidator");var tn=s(async(t,e,n,r)=>{M(n,r).required("signingSecret","string").optional("tolerance","number");let o=t.headers.get("stripe-signature");try{let i=await t.clone().text();await Fi(i,o,n.signingSecret)}catch(i){return e.log.error("Error validating stripe webhook",i),w.badRequest(t,e,{title:"Webhook Error",detail:i.message})}return t},"StripeWebhookInboundPolicy");var nn=class extends oe{static{s(this,"MeteringPlugin")}};var kr=class extends nn{constructor(n){super();this.options=n}static{s(this,"StripeMeteringPlugin")}registerRoutes(n,r){let o=s(async(c,l)=>this.options.testMode?"success":w.ok(c,l),"stripeWebhookHandler"),i=Wo({inboundPolicies:[{handler:tn,options:{signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance}}]}),a=new H({processors:[$,i],handler:o,gateway:r}),u=new D({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["POST"],path:"/__zuplo/stripe-webhooks",systemRouteName:"stripe-plugin"});n.addRoute(u,a.execute)}};var zi=new WeakMap,$i={},rn=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){zi.set(e,n)}};async function Gi(t,e,n,r){if(!n.statusCodes)throw new f(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Array.isArray(n.statusCodes)?n.statusCodes:Go(n.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=zi.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new I(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=Re(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)},R=$i[n.apiKey];if(!R){let g=n.apiKey,b=t.headers.get("zm-test-id")??"";R=new T("amberflo-ingest-meter",10,async E=>{try{let P=n.url??"https://app.amberflo.io/ingest",v=await fetch(P,{method:"POST",body:JSON.stringify(E),headers:{"content-type":"application/json","x-api-key":g,"zm-test-id":b}});v.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${v.status}: ${await v.text()}`)}catch(P){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${P.message}`),P}}),$i[g]=R}R.enqueue(p),e.waitUntil(R.waitUntilFlushed())}}),t}s(Gi,"AmberfloMeteringInboundPolicy");async function on(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(on,"sha256");var Bi=new Map;async function Z(t,e){let n,r=Bi.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await on(JSON.stringify({policyName:t,options:e}))}`,Bi.set(t,n)),n}s(Z,"getPolicyCacheName");var Vi="key-metadata-cache-type";function Uc(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}s(Uc,"getKeyValue");async function sn(t,e,n,r){if(!n.bucketName)if(ot.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=ot.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new f(`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 f(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(P=>o.allowUnauthenticatedRequests?t:w.unauthorized(t,e,{detail:P}),"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=Uc(a,o);if(!u||u==="")return i("No key present");let c=await Nc(u),l=await Z(r,o),d=new N(l,{logger:A.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!==Vi&&A.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let R={key:u},g=await Ae({retryDelayMs:5,retries:2,logger:A.getLogger(e)},`${y.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":y.instance.deploymentName??"unknown","User-Agent":y.instance.systemUserAgent},body:JSON.stringify(R)});if(g.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(g.status!==200){try{let P=await g.text(),v=JSON.parse(P);e.log.error("Unexpected response from key service",v)}catch{e.log.error("Invalid response from key service")}throw new I(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${g.status}`)}let b=await g.json(),E={isValid:!0,typeId:Vi,user:{sub:b.name,data:b.metadata}};return t.user=E.user,d.put(c,E,o.cacheTtlSeconds),t}s(sn,"ApiKeyInboundPolicy");async function Nc(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(Nc,"hashValue");var ji=sn;var st=require("jose");var Hr={},Mc=s(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new f("Invalid State - jwkUrl not set");Hr[e.jwkUrl]||(Hr[e.jwkUrl]=(0,st.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,st.jwtVerify)(t,Hr[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),Zc=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,st.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),q=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),i="bearer ",a=s(R=>w.unauthorized(t,e,{detail:R}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?Mc:Zc,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 R=o.substring(i.length);if(!R||R.length===0)return a("No bearer token on authorization header");try{return await u(R,n)}catch(g){let b=new URL(t.url);return"code"in g&&g.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${b.pathname} `,g):e.log.warn(`Invalid token on: ${t.method} ${b.pathname}`,g),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return n.allowUnauthenticatedRequests===!0?t:l;let d=n.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var Ji=s(async(t,e,n,r)=>q(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var Wi=s(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",i=s(l=>w.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 R=d.substring(0,p),g=d.substring(p+1),b=n.accounts.find(E=>E.username===R&&E.password===g);return b||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 qc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Fc(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(Fc,"digestMessage");var $c=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 Fc(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 Ki(t,e,n,r){let o=await Z(r,n),i=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await $c(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 R=n?.expirationSecondsTtl??60,g=new Response(p.body,p);qc.forEach(b=>g.headers.delete(b)),g.headers.set("cache-control",`s-maxage=${R}`),e.waitUntil(i.put(u,g))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}s(Ki,"CachingInboundPolicy");var Yi=s(async(t,e,n,r)=>{if(!n.method)throw new f(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new S(t,{method:n.method})},"ChangeMethodInboundPolicy");var Qi=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 S(t,{headers:o})},"ClearHeadersInboundPolicy");var Xi=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 es=s(async(t,e,n,r)=>{let o=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",q(t,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var ts=s(async(t,e,n,r)=>{if(!n.userPoolId)throw new f("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new f("region must be set in the options for CognitoJwtInboundPolicy");return q(t,e,{issuer:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}`,jwkUrl:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var ns=s(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new f(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=V.instance,i=Ke(n.policies,o?.routeData.policies);return Xn(i)(t,e)},"CompositeInboundPolicy");var rs=s(async(t,e,n)=>{let r=t.user;if(!r)return w.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 w.unauthorized(t,e,{title:"Metering bucket not configured",detail:"Specify one using the bucketId option on the policy"});let i=n.bucketId,a=await zc(i,o,e);if(!a)return w.unauthorized(t,e,{title:"No valid, active subscription found"});if(!a.quotas)return w.forbidden(t,e,{title:"Insufficient credits"});for(let u of Object.keys(a.quotas))if(a.quotas[u]<=0)return w.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 Gc(i,a.id,c,e)}),t},"CreditsMeteringInboundPolicy");async function zc(t,e,n){let{authApiJWT:r,meteringServiceUrl:o}=y.instance,i=new URL(`${o}/internal/v1/metering/${t}/subscriptions`);i.search=new URLSearchParams({customerRef:e,status:"active"}).toString();let a=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${r}`}});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(zc,"getSubscription");async function Gc(t,e,n,r){let{authApiJWT:o,meteringServiceUrl:i}=y.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}`}});u.ok||r.log.error(`Error consuming subscription quotas for credits metering ': ${u.status} - ${await u.text()}`)}s(Gc,"consumeSubscription");var os=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization");if(!o)return w.unauthorized(t,e,{detail:"No authorization header"});let i=Bc(o);if(!i)return w.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await Z(r,n),u=new N(a,e),c=await u.get(i);if(!c){let l=await fetch(n.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${n.clientId}:${n.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+i+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(i,c,n.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),w.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):w.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${c}`),t},"CurityPhantomTokenInboundPolicy");function Bc(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}s(Bc,"getToken");var is=s(async(t,e,n,r)=>(M(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),q(t,e,{issuer:`https://securetoken.google.com/${n.projectId}`,audience:n.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var ss=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 S(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var Ue="__unknown__",as=s(async(t,e,n,r)=>{let o={allow:{countries:Me(n.allow?.countries,"allow.countries",r),regionCodes:Me(n.allow?.regionCodes,"allow.regionCode",r),asns:Me(n.allow?.asns,"allow.asOrganization",r)},block:{countries:Me(n.block?.countries,"block.countries",r),regionCodes:Me(n.block?.regionCodes,"block.regionCode",r),asns:Me(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??Ue,a=e.incomingRequestProperties.regionCode?.toLowerCase()??Ue,u=e.incomingRequestProperties.asn?.toString()??Ue,c=o.ignoreUnknown&&i===Ue,l=o.ignoreUnknown&&a===Ue,d=o.ignoreUnknown&&u===Ue,p=o.allow.countries,R=o.allow.regionCodes,g=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||R.length>0&&!R.includes(a)&&!l||g.length>0&&!g.includes(u)&&!d)return Ne(t,e,r,i,a,u);let b=o.block.countries,E=o.block.regionCodes,P=o.block.asns;return b.length>0&&b.includes(i)&&!c||E.length>0&&E.includes(a)&&!l||P.length>0&&P.includes(u)&&!d?Ne(t,e,r,i,a,u):t},"GeoFilterInboundPolicy");function Ne(t,e,n,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),w.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(Ne,"blockedResponse");function Me(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 f(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}s(Me,"toLowerStringArray");var us=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 ls=s(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return Ur(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 Ur(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(R=>{a.push({responseName:u,contentName:l,exampleName:R,exampleValue:d[R]})})})}),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 cs(a[u])}else return a.length>0?cs(a[0]):Ur(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 cs(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(cs,"generateResponse");var Ur=s((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return w.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var Vc="Incoming",jc={logRequestBody:!0,logResponseBody:!0};function ds(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}s(ds,"headersToObject");function ps(){return new Date().toISOString()}s(ps,"timestamp");var Nr=new WeakMap,Jc={};function fs(t,e){let n=Nr.get(t);n||(n=Jc);let r=Object.assign({...n},e);Nr.set(t,r)}s(fs,"setMoesifContext");async function ms(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(ms,"readBody");var Wc={},Mr;function gs(){if(!Mr)throw new I("Invalid State - no _lastLogger");return Mr}s(gs,"getLastLogger");function Kc(t){let e=Wc[t];return e||(e=new T("moesif-inbound",100,async n=>{let r=JSON.stringify(n);gs().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||gs().error({status:o.status,body:await o.text()})})),e}s(Kc,"getDispatcher");async function hs(t,e,n,r){Mr=e.log;let o=ps(),i=Object.assign(jc,n);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await ms(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Kc(i.applicationId),d=t.headers.get("true-client-ip"),p=Nr.get(e)??{},R={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:ds(t.headers)},g=i.logResponseBody?await ms(u,e):void 0,b={time:ps(),status:u.status,headers:ds(u.headers),body:g},E={request:R,response:b,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Vc};l.enqueue(E),e.waitUntil(l.waitUntilFlushed())}),t}s(hs,"MoesifInboundPolicy");var ys=s(async(t,e,n,r)=>q(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var bs=require("jose");var Zr,Rs=s(async(t,e,n,r)=>{if(!Zr)try{Zr=await(0,bs.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return q(t,e,{issuer:n.authUrl,secret:Zr,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Ps=Ie(ye());var an=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},qr=class extends an{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Fr=class extends an{static{s(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function Yc(t,e){if($o(t))throw new qr(e)}s(Yc,"throwIfUndefinedOrNull");function at(t,e){if(Yc(t,e),!pe(t))throw new Fr(e,"string")}s(at,"throwIfNotString");var un=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 at(e,"redisClientUrl"),at(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}){at(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 _("Redis client failed with 401: Unauthorized"):new _(`Redis client failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},cn=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(at(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 _("The in-memory redis client only supports /rate-limit calls")}};var ln=(0,Ps.debug)("zuplo:policies:RateLimitInboundPolicy"),Qc="strict",Xc=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"),el=s(async t=>({key:`ip-${Xc(t)}`}),"getIP"),tl=s(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),nl=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),dn;function rl(t,e){let n;if(dn)return dn;if(y.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new cn,dn=n,n;let{authApiJWT:r,redisURL:o}=y.instance;if(!pe(o))throw new _(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!pe(r))throw new _(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=un.initialize(o,r,y.instance.deploymentName??"unknown",y.instance.systemUserAgent)),!n||!n.isEnabled())throw new _(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return dn=n,n}s(rl,"getRedisClient");async function ws(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(ws,"getCountAndUpdateExpiry");function ol(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new f(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new f(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new f(`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 f(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return s(async(o,i,a)=>{let u=await n(o,i,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw i.log.error(c),new I(c)}return u},"outerFunction")}s(ol,"wrapUserFunction");var il="Retry-After",$r=s(async(t,e,n,r)=>{let o=Date.now(),i=A.getLogger(e),a=s((c,l)=>{if(n.throwOnFailure)throw new _(c,{cause:l});i.error(c,l)},"throwOrLog"),u=s((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[il]=l.toString()),w.tooManyRequests(t,e,void 0,d)},"rateLimited");try{let l={function:ol(n,r),user:tl,ip:el,all:nl}[n.rateLimitBy],d=await l(t,e,r),p=d.key,R=d.requestsAllowed??n.requestsAllowed,g=d.timeWindowMinutes??n.timeWindowMinutes,b=n.headerMode??"retry-after",E=rl(r,i),v=`bucket/${y.instance.build.BUILD_ID}/${r}/${p}`;if((n.mode??Qc)==="async"){let L=await Z(r,n),G=new se(L,{logger:A.getLogger(e)}),J=ws(v,g,E,i,e.requestId),W=await G.get(v);if(W!==void 0&&W<=Date.now()){ln(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${v}' (async mode)`);let Pe=Math.round((W-Date.now())/1e3);return u(b,Pe)}return e.addEventListener("responseSending",Pe=>{try{let Ee=Pe,Rn=Ee.mutableResponse;Ee.mutableResponse=(async()=>{let ut=await J;if(ut.count>R){let ea=Date.now()+ut.ttlSeconds*1e3;return G.put(v,ea,ut.ttlSeconds).catch(Yr=>{throw i.error(Yr),Yr}),ln(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${v}' (async mode)`),u(b,ut.ttlSeconds)}return Rn})()}catch(Ee){i.error(`RateLimitInboundPolicy '${r}' -error in responseSending`,Ee)}}),t}let k=await ws(v,g,E,i,e.requestId);return k.count>R?(ln(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${v}' (strict mode)`),u(b,k.ttlSeconds)):t}catch(c){return a(c.message,c),t}finally{let c=Date.now()-o;ln(`RateLimitInboundPolicy '${r}' - latency ${c}ms`)}},"RateLimitInboundPolicy");var zr;function Es(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}s(Es,"headersToNameValuePairs");function sl(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}s(sl,"queryToNameValueParis");function al(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}s(al,"parseIntOrUndefined");var Is={};async function xs(t,e,n,r){let o=new Date,i=Date.now();return zr||(zr={name:"zuplo",version:y.instance.build.ZUPLO_VERSION,comment:`zuplo/${y.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?Re(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?Re(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:y.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:Es(t.headers),queryString:sl(t.query)},response:{status:a.status,statusText:a.statusText,headers:Es(a.headers),content:{size:al(t.headers.get("content-length"))}}}]}}},d=Is[n.apiKey];if(!d){let p=n.apiKey;d=new T("readme-metering-inbound-policy",10,async R=>{try{let g=n.url??"https://metrics.readme.io/request",b=await fetch(g,{method:"POST",body:JSON.stringify(R),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});b.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${b.status}: '${await b.text()}'`)}catch(g){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${g.message}'`),g}}),Is[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}s(xs,"ReadmeMetricsInboundPolicy");var Os=s(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new f(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(t.headers);return o.forEach(u=>{i.delete(u)}),new S(t,{headers:i})},"RemoveHeadersInboundPolicy");var vs=s(async(t,e,n,r,o)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new f(`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 Ts=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new f(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(t.url);return o.forEach(u=>{i.searchParams.delete(u)}),new S(i.toString(),t)},"RemoveQueryParamsInboundPolicy");var Cs=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 As=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Ss=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?As():i&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?As():t},"RequestSizeLimitInboundPolicy");function Ls(t,e,n){return`_${fe(t+"_"+e+"_"+n)}`}s(Ls,"getRawOperationDataIdentifierName");function pn(t,e,n,r){return`_${fe(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}s(pn,"getIdForParameterSchema");function mn(t,e,n){return`_${fe(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${fe(n.toLowerCase())}`}s(mn,"getIdForRequestBodySchema");function _s(t,e){return`_${fe(t)}__${fe(e)}`}s(_s,"getIdForRefSchema");function fe(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(fe,"sanitizedIdentifierName");var Ze=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"),qe=s((t,e,n,r,o)=>{let i=[],a=!0,u=[];return t.forEach(c=>{if(c.required&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else{let l=pn(n,r,o,c.name),d=V.instance.schemaValidator[l],p=d(e[c.name]),R=Gr(d.errors);p||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${R.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),Y=s((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),Q=s(t=>t==="log-only"||t==="reject-and-log","shouldLog"),X=s(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),Gr=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 Ds(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(g){let b=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,E=w.badRequest(e,t,{detail:`${b}, see errors property for more details`,errors:`${g}`});if(Q(n.validateBody)&&Y(t,n.logLevel??"info",b,[r],g),X(n.validateBody))return E}if(!e.headers.get("Content-Type")){let g=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,b=w.badRequest(e,t,{detail:g});return Q(n.validateBody)&&Y(t,n.logLevel??"info",g,[r],[g]),X(n.validateBody)?b:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=mn(t.route.path,e.method,o),u=V.instance.schemaValidator[a];if(!u){let g=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,b=w.badRequest(e,t,{detail:g});return Q(n.validateBody)&&Y(t,n.logLevel??"info",g,[r],[g]),X(n.validateBody)?b:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Gr(l),R=w.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(Q(n.validateBody)&&Y(t,n.logLevel??"info",d,[r],p),X(n.validateBody))return R}s(Ds,"handleBodyValidation");function ks(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Ze(t),i=qe(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=w.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:i.errors});if(Q(n.validateHeaders)&&Y(t,n.logLevel??"info",a,i.invalidValues,i.errors),X(n.validateHeaders))return u}}s(ks,"handleHeadersValidation");function Hs(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=Ze(t),o=qe(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=w.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Q(n.validatePathParameters)&&Y(t,n.logLevel??"info",i,o.invalidValues,o.errors),X(n.validatePathParameters))return a}}s(Hs,"handlePathParameterValidation");function Us(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=Ze(t),o=qe(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=w.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Q(n.validateQueryParameters)&&Y(t,n.logLevel??"info",i,o.invalidValues,o.errors),X(n.validateQueryParameters))return a}}s(Us,"handleQueryParameterValidation");var Br=s(async(t,e,n)=>{let r=Us(e,t,n);if(r!==void 0||(r=Hs(e,t,n),r!==void 0)||(r=ks(e,t,n),r!==void 0))return r;let o=await Ds(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),Ns=Br;var Ms=s(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new f(`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 w.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var Zs=s(async(t,e,n)=>new S(t,{body:n.body}),"SetBodyInboundPolicy");var qs=s(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new f(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new f(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new S(t,{headers:i})},"SetHeadersInboundPolicy");var Fs=s(async(t,e,n,r,o)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new f(`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 f(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");var $s=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new f(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new f(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new S(i.toString(),t)},"SetQueryParamsInboundPolicy");var zs=s(async(t,e,n,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(t.body,{headers:t.headers,status:r.status,statusText:r.statusText??t.statusText})},"SetStatusOutboundPolicy");var ul=s(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),Gs=s(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new f(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await ul(n.sleepInMs),t},"SleepInboundPolicy");var Bs=s(async(t,e,n,r)=>{M(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},i=await q(t,e,o,r);if(i instanceof Response)return i;if(!(i instanceof S))throw new _("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=n.requiredClaims;if(!a)return i;let u=t.user?.data.app_metadata;if(!u)throw new I(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?w.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var Vs=s(async(t,e,n,r)=>{M(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await Z(r,n),i=new N(o,{logger:A.getLogger(e)}),a=await i.get(r);if(!a){let u=await cl(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 cl(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await Ae({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:n});if(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new I("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new I("Response returned from Azure AD is not in the expected format.")}s(cl,"getAccessToken");var js="https://accounts.google.com/o/oauth2/token",Vr,Js=s(async(t,e,n,r)=>{M(n,r).required("serviceAccountJson","string"),Vr||(Vr=await B.init(n.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},i=await Z(r,n),a=new N(i,{logger:A.getLogger(e)}),u=await a.get(r);if(!u){let c=await te({serviceAccount:Vr,audience:js,payload:o}),l=await Lt(js,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new I("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");var ll="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",dl=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],jr,Ws=s(async(t,e,n,r)=>{if(M(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new f(`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(dl.indexOf(p)!==-1)throw new f(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}jr||(jr=await B.init(n.serviceAccountJson));let i=n.userId;if(!i&&!n.userIdPropertyPath){if(!t.user)throw new I("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");i=t.user?.sub}else if(n.userIdPropertyPath){if(!t.user)throw new I(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=Re(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new I(`Unable to determine user from for the policy ${r}`);let a=await Z(r,n),u=new N(a,{logger:A.getLogger(e)}),c={uid:i,claims:o},l=await on(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await te({serviceAccount:jr,audience:ll,payload:c}),R=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,g=await si(R,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!g.idToken)throw new I("Invalid token response from Firebase");d=g.idToken,u.put(l,d,(g.expiresIn?parseInt(g.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var Jr,Ks=s(async(t,e,n,r)=>{M(n,r).required("audience","string").required("serviceAccountJson","string"),Jr||(Jr=await B.init(n.serviceAccountJson));let o=await te({serviceAccount:Jr,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var Ys="https://www.googleapis.com/oauth2/v4/token",Wr,Qs=s(async(t,e,n,r)=>{M(n,r).required("audience","string").required("serviceAccountJson","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Wr||(Wr=await B.init(n.serviceAccountJson));let o=await Z(r,n),i;n.useMemoryCacheOnly?i=new xe(o):i=new N(o,e);let a=await i.get(r);if(!a){let u=await te({serviceAccount:Wr,audience:Ys,payload:{target_audience:`${n.audience}`}}),{id_token:c}=await Lt(Ys,u,{retries:n.tokenRetries??3,retryDelayMs:10});if(!c)throw new I("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 Xs=s(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return w.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 _("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 w.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var gn=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 _(`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 Kr=["sha-1","sha-256","sha-384","sha-512"],fn=class{static{s(this,"BaseCryptoBeta")}};var hn=class extends fn{static{s(this,"WorkerCryptoBeta")}async digest(e,n){if(!Kr.includes(e.toLowerCase()))throw new I(`Algorithm ${e} is not supported. Try using ${Kr.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 yn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var bn=class extends yn{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=globalThis.ZUPLO_KV;if(!r)throw new ct("The Key Value Store feature is not enabled for this project.");this.#e=r}put(e,n,r){if(typeof e!="string")throw new f("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 oe(e,t,{message:"Timestamp outside the tolerance zone"});return!0}s(Dc,"validateComputedSignature");function Hc(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(Hc,"parseHeader");function Uc(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(Uc,"secureCompare");async function Nc(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]=kr[i[u]];return a.join("")}s(Nc,"computeHMACSignatureAsync");var kr=new Array(256);for(let t=0;t<kr.length;t++)kr[t]=t.toString(16).padStart(2,"0");function M(t,e){let n=s((i,a,u)=>{let c=t[i];if(!(u&&c===void 0)){if(c===void 0)throw new f(`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 f(`Value of '${String(i)}' on policy '${e}' must be an array. Received type ${typeof c}.`);if(typeof c!==a)throw new f(`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 f(`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 f(`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(M,"optionValidator");var tn=s(async(t,e,n,r)=>{M(n,r).required("signingSecret","string").optional("tolerance","number");let o=t.headers.get("stripe-signature");try{let i=await t.clone().text();await Fi(i,o,n.signingSecret)}catch(i){return e.log.error("Error validating stripe webhook",i),w.badRequest(t,e,{title:"Webhook Error",detail:i.message})}return t},"StripeWebhookInboundPolicy");var nn=class extends ie{static{s(this,"MeteringPlugin")}};var Mc=["customer.subscription.created","customer.subscription.deleted","customer.subscription.paused","customer.subscription.resumed","customer.subscription.updated"],Dr=class extends nn{constructor(n){super();this.options=n}static{s(this,"StripeMeteringPlugin")}registerRoutes(n,r){let o=s(async(c,l)=>{if(this.options.testMode)return"success";let{bucketId:d}=this.options;if(!d)throw new f("StripeMeteringPlugin - No bucketName property provided");let{authApiJWT:p,meteringServiceUrl:R}=y.instance,g=await c.json();try{Zc(g)}catch{return w.badRequest(c,l,{detail:"The received body was not in the expected format."})}if(!Mc.includes(g.type))return w.ok(c,l,{detail:"Event was ignored by Stripe metering plugin webhook."});let h=g.data?.object?.id;if(!h)return w.badRequest(c,l,{detail:"Invalid Stripe Webhook event. Expected '.data.object.id' to be the subscription ID."});let E=g.data?.object?.items?.data.find(k=>k.object==="subscription_item");if(!E||!E.id)return w.badRequest(c,l,{detail:"Invalid Stripe Webhook event. Expected '.data.object.items.data[]' to contain a subscription_item."});let P=E.plan;if(!P||!P.product)return w.badRequest(c,l,{detail:"Invalid Stripe Webhook event. Expected '.data.object.items.data[].plan'."});let x={status:"active",type:"periodic",renewalStrategy:"monthly",customerKey:"luis-tester",productKey:"routes.oas.json",planProviderKey:P.product,subscriptionProviderKey:h,region:this.options.bucketRegion??"us-central1"},T=await fetch(`${R}/internal/v1/metering/${d}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json"},method:"POST",body:JSON.stringify(x)});if(T.status!==200){let k="Unknown error creating subscription",A;try{A=await T.json(),k=A.detail??A.title??k}catch{}return l.log.error(k,A),w.internalServerError(c,l,{detail:k})}return w.ok(c,l)},"stripeWebhookHandler"),i=Jo({inboundPolicies:[{handler:tn,options:{signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance}}]}),a=new H({processors:[$,i],handler:o,gateway:r}),u=new D({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__zuplo/stripe-webhooks",systemRouteName:"stripe-plugin"});n.addRoute(u,a.execute)}};function Zc(t){if(!(t!==null&&typeof t=="object"&&"id"in t&&K(t.id)&&"type"in t&&K(t.type)))throw new Error("Object is not a stripe webhook event")}s(Zc,"assertsStripeWebhookEvent");var ji=new WeakMap,$i={},rn=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){ji.set(e,n)}};async function zi(t,e,n,r){if(!n.statusCodes)throw new f(`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 I(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=we(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)},R=$i[n.apiKey];if(!R){let g=n.apiKey,h=t.headers.get("zm-test-id")??"";R=new C("amberflo-ingest-meter",10,async E=>{try{let P=n.url??"https://app.amberflo.io/ingest",x=await fetch(P,{method:"POST",body:JSON.stringify(E),headers:{"content-type":"application/json","x-api-key":g,"zm-test-id":h}});x.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${x.status}: ${await x.text()}`)}catch(P){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${P.message}`),P}}),$i[g]=R}R.enqueue(p),e.waitUntil(R.waitUntilFlushed())}}),t}s(zi,"AmberfloMeteringInboundPolicy");async function on(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(on,"sha256");var Bi=new Map;async function Z(t,e){let n,r=Bi.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await on(JSON.stringify({policyName:t,options:e}))}`,Bi.set(t,n)),n}s(Z,"getPolicyCacheName");var Gi="key-metadata-cache-type";function qc(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}s(qc,"getKeyValue");async function sn(t,e,n,r){if(!n.bucketName)if(it.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=it.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new f(`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 f(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(P=>o.allowUnauthenticatedRequests?t:w.unauthorized(t,e,{detail:P}),"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=qc(a,o);if(!u||u==="")return i("No key present");let c=await Fc(u),l=await Z(r,o),d=new N(l,{logger:S.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!==Gi&&S.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let R={key:u},g=await Ae({retryDelayMs:5,retries:2,logger:S.getLogger(e)},`${y.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":y.instance.deploymentName??"unknown","User-Agent":y.instance.systemUserAgent},body:JSON.stringify(R)});if(g.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(g.status!==200){try{let P=await g.text(),x=JSON.parse(P);e.log.error("Unexpected response from key service",x)}catch{e.log.error("Invalid response from key service")}throw new I(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${g.status}`)}let h=await g.json(),E={isValid:!0,typeId:Gi,user:{sub:h.name,data:h.metadata}};return t.user=E.user,d.put(c,E,o.cacheTtlSeconds),t}s(sn,"ApiKeyInboundPolicy");async function Fc(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(Fc,"hashValue");var Vi=sn;var at=require("jose");var Hr={},$c=s(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new f("Invalid State - jwkUrl not set");Hr[e.jwkUrl]||(Hr[e.jwkUrl]=(0,at.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:n}=await(0,at.jwtVerify)(t,Hr[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return n},"jwkVerifier"),jc=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"),q=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),i="bearer ",a=s(R=>w.unauthorized(t,e,{detail:R}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?$c:jc,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 R=o.substring(i.length);if(!R||R.length===0)return a("No bearer token on authorization header");try{return await u(R,n)}catch(g){let h=new URL(t.url);return"code"in g&&g.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${h.pathname} `,g):e.log.warn(`Invalid token on: ${t.method} ${h.pathname}`,g),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return n.allowUnauthenticatedRequests===!0?t:l;let d=n.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var Wi=s(async(t,e,n,r)=>q(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var Ji=s(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",i=s(l=>w.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 R=d.substring(0,p),g=d.substring(p+1),h=n.accounts.find(E=>E.username===R&&E.password===g);return h||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 zc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Bc(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(Bc,"digestMessage");var Gc=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 Bc(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 Ki(t,e,n,r){let o=await Z(r,n),i=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Gc(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 R=n?.expirationSecondsTtl??60,g=new Response(p.body,p);zc.forEach(h=>g.headers.delete(h)),g.headers.set("cache-control",`s-maxage=${R}`),e.waitUntil(i.put(u,g))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}s(Ki,"CachingInboundPolicy");var Yi=s(async(t,e,n,r)=>{if(!n.method)throw new f(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new L(t,{method:n.method})},"ChangeMethodInboundPolicy");var Qi=s(async(t,e,n)=>{let r=[...n.exclude??[]],o=new Headers;return r.forEach(a=>{let u=t.headers.get(a);u&&o.set(a,u)}),new L(t,{headers:o})},"ClearHeadersInboundPolicy");var Xi=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 es=s(async(t,e,n,r)=>{let o=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",q(t,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var ts=s(async(t,e,n,r)=>{if(!n.userPoolId)throw new f("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new f("region must be set in the options for CognitoJwtInboundPolicy");return q(t,e,{issuer:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}`,jwkUrl:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var ns=s(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new f(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=G.instance,i=Ye(n.policies,o?.routeData.policies);return Xn(i)(t,e)},"CompositeInboundPolicy");var rs=s(async(t,e,n)=>{let r=t.user;if(!r)return w.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 w.unauthorized(t,e,{title:"Metering bucket not configured",detail:"Specify one using the bucketId option on the policy"});let i=n.bucketId,a=await Vc(i,o,e);if(!a)return w.unauthorized(t,e,{title:"No valid, active subscription found"});if(!a.quotas)return w.forbidden(t,e,{title:"Insufficient credits"});for(let u of Object.keys(a.quotas))if(a.quotas[u]<=0)return w.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 Wc(i,a.id,c,e)}),t},"CreditsMeteringInboundPolicy");async function Vc(t,e,n){let{authApiJWT:r,meteringServiceUrl:o}=y.instance,i=new URL(`${o}/internal/v1/metering/${t}/subscriptions`);i.search=new URLSearchParams({customerRef:e,status:"active"}).toString();let a=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${r}`}});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(Vc,"getSubscription");async function Wc(t,e,n,r){let{authApiJWT:o,meteringServiceUrl:i}=y.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}`}});u.ok||r.log.error(`Error consuming subscription quotas for credits metering ': ${u.status} - ${await u.text()}`)}s(Wc,"consumeSubscription");var os=s(async(t,e,n,r)=>{let o=t.headers.get("Authorization");if(!o)return w.unauthorized(t,e,{detail:"No authorization header"});let i=Jc(o);if(!i)return w.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await Z(r,n),u=new N(a,e),c=await u.get(i);if(!c){let l=await fetch(n.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${n.clientId}:${n.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+i+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(i,c,n.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),w.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):w.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${c}`),t},"CurityPhantomTokenInboundPolicy");function Jc(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}s(Jc,"getToken");var is=s(async(t,e,n,r)=>(M(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),q(t,e,{issuer:`https://securetoken.google.com/${n.projectId}`,audience:n.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var ss=s(async(t,e,n)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",i=t.headers.get("content-type")?.toLowerCase();if(!i||![o,r].includes(i))return n&&n.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(n&&n.optionalHoneypotName&&a.get(n.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new L(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var Ne="__unknown__",as=s(async(t,e,n,r)=>{let o={allow:{countries:Ze(n.allow?.countries,"allow.countries",r),regionCodes:Ze(n.allow?.regionCodes,"allow.regionCode",r),asns:Ze(n.allow?.asns,"allow.asOrganization",r)},block:{countries:Ze(n.block?.countries,"block.countries",r),regionCodes:Ze(n.block?.regionCodes,"block.regionCode",r),asns:Ze(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??Ne,a=e.incomingRequestProperties.regionCode?.toLowerCase()??Ne,u=e.incomingRequestProperties.asn?.toString()??Ne,c=o.ignoreUnknown&&i===Ne,l=o.ignoreUnknown&&a===Ne,d=o.ignoreUnknown&&u===Ne,p=o.allow.countries,R=o.allow.regionCodes,g=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||R.length>0&&!R.includes(a)&&!l||g.length>0&&!g.includes(u)&&!d)return Me(t,e,r,i,a,u);let h=o.block.countries,E=o.block.regionCodes,P=o.block.asns;return h.length>0&&h.includes(i)&&!c||E.length>0&&E.includes(a)&&!l||P.length>0&&P.includes(u)&&!d?Me(t,e,r,i,a,u):t},"GeoFilterInboundPolicy");function Me(t,e,n,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),w.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(Me,"blockedResponse");function Ze(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 f(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}s(Ze,"toLowerStringArray");var us=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 ls=s(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return Ur(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 Ur(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(R=>{a.push({responseName:u,contentName:l,exampleName:R,exampleValue:d[R]})})})}),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 cs(a[u])}else return a.length>0?cs(a[0]):Ur(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 cs(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(cs,"generateResponse");var Ur=s((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return w.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var Kc="Incoming",Yc={logRequestBody:!0,logResponseBody:!0};function ds(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}s(ds,"headersToObject");function ps(){return new Date().toISOString()}s(ps,"timestamp");var Nr=new WeakMap,Qc={};function fs(t,e){let n=Nr.get(t);n||(n=Qc);let r=Object.assign({...n},e);Nr.set(t,r)}s(fs,"setMoesifContext");async function ms(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(ms,"readBody");var Xc={},Mr;function gs(){if(!Mr)throw new I("Invalid State - no _lastLogger");return Mr}s(gs,"getLastLogger");function el(t){let e=Xc[t];return e||(e=new C("moesif-inbound",100,async n=>{let r=JSON.stringify(n);gs().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||gs().error({status:o.status,body:await o.text()})})),e}s(el,"getDispatcher");async function hs(t,e,n,r){Mr=e.log;let o=ps(),i=Object.assign(Yc,n);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await ms(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=el(i.applicationId),d=t.headers.get("true-client-ip"),p=Nr.get(e)??{},R={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:ds(t.headers)},g=i.logResponseBody?await ms(u,e):void 0,h={time:ps(),status:u.status,headers:ds(u.headers),body:g},E={request:R,response:h,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Kc};l.enqueue(E),e.waitUntil(l.waitUntilFlushed())}),t}s(hs,"MoesifInboundPolicy");var ys=s(async(t,e,n,r)=>q(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var bs=require("jose");var Zr,Rs=s(async(t,e,n,r)=>{if(!Zr)try{Zr=await(0,bs.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return q(t,e,{issuer:n.authUrl,secret:Zr,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Ps=xe(be());var an=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},qr=class extends an{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Fr=class extends an{static{s(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function tl(t,e){if($o(t))throw new qr(e)}s(tl,"throwIfUndefinedOrNull");function ut(t,e){if(tl(t,e),!K(t))throw new Fr(e,"string")}s(ut,"throwIfNotString");var un=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 _("Redis client failed with 401: Unauthorized"):new _(`Redis client failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},cn=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 _("The in-memory redis client only supports /rate-limit calls")}};var ln=(0,Ps.debug)("zuplo:policies:RateLimitInboundPolicy"),nl="strict",rl=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"),ol=s(async t=>({key:`ip-${rl(t)}`}),"getIP"),il=s(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),sl=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),dn;function al(t,e){let n;if(dn)return dn;if(y.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new cn,dn=n,n;let{authApiJWT:r,redisURL:o}=y.instance;if(!K(o))throw new _(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!K(r))throw new _(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=un.initialize(o,r,y.instance.deploymentName??"unknown",y.instance.systemUserAgent)),!n||!n.isEnabled())throw new _(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return dn=n,n}s(al,"getRedisClient");async function ws(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(ws,"getCountAndUpdateExpiry");function ul(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new f(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new f(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new f(`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 f(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return s(async(o,i,a)=>{let u=await n(o,i,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw i.log.error(c),new I(c)}return u},"outerFunction")}s(ul,"wrapUserFunction");var cl="Retry-After",$r=s(async(t,e,n,r)=>{let o=Date.now(),i=S.getLogger(e),a=s((c,l)=>{if(n.throwOnFailure)throw new _(c,{cause:l});i.error(c,l)},"throwOrLog"),u=s((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[cl]=l.toString()),w.tooManyRequests(t,e,void 0,d)},"rateLimited");try{let l={function:ul(n,r),user:il,ip:ol,all:sl}[n.rateLimitBy],d=await l(t,e,r),p=d.key,R=d.requestsAllowed??n.requestsAllowed,g=d.timeWindowMinutes??n.timeWindowMinutes,h=n.headerMode??"retry-after",E=al(r,i),x=`bucket/${y.instance.build.BUILD_ID}/${r}/${p}`;if((n.mode??nl)==="async"){let A=await Z(r,n),j=new ue(A,{logger:S.getLogger(e)}),W=ws(x,g,E,i,e.requestId),J=await j.get(x);if(J!==void 0&&J<=Date.now()){ln(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${x}' (async mode)`);let Ee=Math.round((J-Date.now())/1e3);return u(h,Ee)}return e.addEventListener("responseSending",Ee=>{try{let Ie=Ee,Rn=Ie.mutableResponse;Ie.mutableResponse=(async()=>{let ct=await W;if(ct.count>R){let na=Date.now()+ct.ttlSeconds*1e3;return j.put(x,na,ct.ttlSeconds).catch(Yr=>{throw i.error(Yr),Yr}),ln(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${x}' (async mode)`),u(h,ct.ttlSeconds)}return Rn})()}catch(Ie){i.error(`RateLimitInboundPolicy '${r}' -error in responseSending`,Ie)}}),t}let k=await ws(x,g,E,i,e.requestId);return k.count>R?(ln(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${x}' (strict mode)`),u(h,k.ttlSeconds)):t}catch(c){return a(c.message,c),t}finally{let c=Date.now()-o;ln(`RateLimitInboundPolicy '${r}' - latency ${c}ms`)}},"RateLimitInboundPolicy");var jr;function Es(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}s(Es,"headersToNameValuePairs");function ll(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}s(ll,"queryToNameValueParis");function dl(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}s(dl,"parseIntOrUndefined");var Is={};async function xs(t,e,n,r){let o=new Date,i=Date.now();return jr||(jr={name:"zuplo",version:y.instance.build.ZUPLO_VERSION,comment:`zuplo/${y.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?we(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?we(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:y.instance.isDeno,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:jr,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:Es(t.headers),queryString:ll(t.query)},response:{status:a.status,statusText:a.statusText,headers:Es(a.headers),content:{size:dl(t.headers.get("content-length"))}}}]}}},d=Is[n.apiKey];if(!d){let p=n.apiKey;d=new C("readme-metering-inbound-policy",10,async R=>{try{let g=n.url??"https://metrics.readme.io/request",h=await fetch(g,{method:"POST",body:JSON.stringify(R),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});h.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${h.status}: '${await h.text()}'`)}catch(g){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${g.message}'`),g}}),Is[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}s(xs,"ReadmeMetricsInboundPolicy");var vs=s(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new f(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(t.headers);return o.forEach(u=>{i.delete(u)}),new L(t,{headers:i})},"RemoveHeadersInboundPolicy");var Os=s(async(t,e,n,r,o)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new f(`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 Ts=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new f(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(t.url);return o.forEach(u=>{i.searchParams.delete(u)}),new L(i.toString(),t)},"RemoveQueryParamsInboundPolicy");var Ss=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 Cs=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),As=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?Cs():i&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?Cs():t},"RequestSizeLimitInboundPolicy");function Ls(t,e,n){return`_${he(t+"_"+e+"_"+n)}`}s(Ls,"getRawOperationDataIdentifierName");function pn(t,e,n,r){return`_${he(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}s(pn,"getIdForParameterSchema");function mn(t,e,n){return`_${he(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${he(n.toLowerCase())}`}s(mn,"getIdForRequestBodySchema");function _s(t,e){return`_${he(t)}__${he(e)}`}s(_s,"getIdForRefSchema");function he(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(he,"sanitizedIdentifierName");var qe=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=>{if(c.required&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else{let l=pn(n,r,o,c.name),d=G.instance.schemaValidator[l],p=d(e[c.name]),R=zr(d.errors);p||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${R.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),Q=s((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),X=s(t=>t==="log-only"||t==="reject-and-log","shouldLog"),ee=s(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),zr=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 ks(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(g){let h=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,E=w.badRequest(e,t,{detail:`${h}, see errors property for more details`,errors:`${g}`});if(X(n.validateBody)&&Q(t,n.logLevel??"info",h,[r],g),ee(n.validateBody))return E}if(!e.headers.get("Content-Type")){let g=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,h=w.badRequest(e,t,{detail:g});return X(n.validateBody)&&Q(t,n.logLevel??"info",g,[r],[g]),ee(n.validateBody)?h:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=mn(t.route.path,e.method,o),u=G.instance.schemaValidator[a];if(!u){let g=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,h=w.badRequest(e,t,{detail:g});return X(n.validateBody)&&Q(t,n.logLevel??"info",g,[r],[g]),ee(n.validateBody)?h:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=zr(l),R=w.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(X(n.validateBody)&&Q(t,n.logLevel??"info",d,[r],p),ee(n.validateBody))return R}s(ks,"handleBodyValidation");function Ds(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=qe(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=w.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:i.errors});if(X(n.validateHeaders)&&Q(t,n.logLevel??"info",a,i.invalidValues,i.errors),ee(n.validateHeaders))return u}}s(Ds,"handleHeadersValidation");function Hs(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=qe(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=w.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(X(n.validatePathParameters)&&Q(t,n.logLevel??"info",i,o.invalidValues,o.errors),ee(n.validatePathParameters))return a}}s(Hs,"handlePathParameterValidation");function Us(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=qe(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=w.badRequest(e,t,{detail:`${i}, see errors property for more details`,errors:o.errors});if(X(n.validateQueryParameters)&&Q(t,n.logLevel??"info",i,o.invalidValues,o.errors),ee(n.validateQueryParameters))return a}}s(Us,"handleQueryParameterValidation");var Br=s(async(t,e,n)=>{let r=Us(e,t,n);if(r!==void 0||(r=Hs(e,t,n),r!==void 0)||(r=Ds(e,t,n),r!==void 0))return r;let o=await ks(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),Ns=Br;var Ms=s(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new f(`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 w.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var Zs=s(async(t,e,n)=>new L(t,{body:n.body}),"SetBodyInboundPolicy");var qs=s(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new f(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new f(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new L(t,{headers:i})},"SetHeadersInboundPolicy");var Fs=s(async(t,e,n,r,o)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new f(`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 f(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");var $s=s(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new f(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new f(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new L(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 pl=s(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),zs=s(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new f(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await pl(n.sleepInMs),t},"SleepInboundPolicy");var Bs=s(async(t,e,n,r)=>{M(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},i=await q(t,e,o,r);if(i instanceof Response)return i;if(!(i instanceof L))throw new _("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=n.requiredClaims;if(!a)return i;let u=t.user?.data.app_metadata;if(!u)throw new I(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?w.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var Gs=s(async(t,e,n,r)=>{M(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await Z(r,n),i=new N(o,{logger:S.getLogger(e)}),a=await i.get(r);if(!a){let u=await ml(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 ml(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await Ae({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:n});if(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new I("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new I("Response returned from Azure AD is not in the expected format.")}s(ml,"getAccessToken");var Vs="https://accounts.google.com/o/oauth2/token",Gr,Ws=s(async(t,e,n,r)=>{M(n,r).required("serviceAccountJson","string"),Gr||(Gr=await B.init(n.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},i=await Z(r,n),a=new N(i,{logger:S.getLogger(e)}),u=await a.get(r);if(!u){let c=await ne({serviceAccount:Gr,audience:Vs,payload:o}),l=await _t(Vs,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new I("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");var gl="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",fl=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Vr,Js=s(async(t,e,n,r)=>{if(M(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new f(`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(fl.indexOf(p)!==-1)throw new f(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}Vr||(Vr=await B.init(n.serviceAccountJson));let i=n.userId;if(!i&&!n.userIdPropertyPath){if(!t.user)throw new I("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");i=t.user?.sub}else if(n.userIdPropertyPath){if(!t.user)throw new I(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=we(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new I(`Unable to determine user from for the policy ${r}`);let a=await Z(r,n),u=new N(a,{logger:S.getLogger(e)}),c={uid:i,claims:o},l=await on(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await ne({serviceAccount:Vr,audience:gl,payload:c}),R=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,g=await si(R,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!g.idToken)throw new I("Invalid token response from Firebase");d=g.idToken,u.put(l,d,(g.expiresIn?parseInt(g.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var Wr,Ks=s(async(t,e,n,r)=>{M(n,r).required("audience","string").required("serviceAccountJson","string"),Wr||(Wr=await B.init(n.serviceAccountJson));let o=await ne({serviceAccount:Wr,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var Ys="https://www.googleapis.com/oauth2/v4/token",Jr,Qs=s(async(t,e,n,r)=>{M(n,r).required("audience","string").required("serviceAccountJson","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Jr||(Jr=await B.init(n.serviceAccountJson));let o=await Z(r,n),i;n.useMemoryCacheOnly?i=new ve(o):i=new N(o,e);let a=await i.get(r);if(!a){let u=await ne({serviceAccount:Jr,audience:Ys,payload:{target_audience:`${n.audience}`}}),{id_token:c}=await _t(Ys,u,{retries:n.tokenRetries??3,retryDelayMs:10});if(!c)throw new I("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 Xs=s(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return w.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 _("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 w.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var ea=s(async(t,e,n,r)=>{let o=S.getLogger(e);e.addResponseSendingFinalHook(async(l,d,p)=>{let R=ae.get(p,"subscription");if((n.allowRequestsWithoutSubscription??!1)&&!R)return;let h=n.bucketId;if(!h){p.log.error(`MeteringInboundPolicy '${r}' - no bucketName property provided`);return}let{authApiJWT:E,meteringServiceUrl:P}=y.instance;l.ok&&R&&n.meters&&fetch(`${P}/internal/v1/metering/${h}/subscriptions/${R.id}/quotas/consume`,{headers:{Authorization:`Bearer ${E}`},method:"POST",body:JSON.stringify({meters:n.meters})}).catch(x=>{p.log.error(`MeteringInboundPolicy '${r}' -error in serviceResponse`),o.error(`MeteringInboundPolicy '${r}' -error in serviceResponse`,x)})});let i=ae.get(e,"subscription"),a=n.allowRequestsWithoutSubscription??!1;if(!i){if(a)return t;throw new f("Subscription is not available for user")}if(i&&Object.keys(i.quotas).length===0)return w.forbidden(t,e,{detail:`Quota is not set up for subscription '${e.custom.subscription.id}'`});let c=Object.keys(n.meters).filter(l=>!Object.keys(i.quotas).includes(l));if(c.length>0)throw new f(`The following policy meters are not present in the subscription: ${c.join(", ")}`);for(let l of Object.keys(i.quotas))if(i.quotas[l]<=0)return w.forbidden(t,e,{detail:`Quota exceeded for meter '${l}'`});return t},"MeteringInboundPolicy");var ta=s(async(t,e,n,r)=>{let o=S.getLogger(e),i=n.allowRequestsWithoutSubscription??!1,a=t.user;if(!a)return i?t:w.unauthorized(t,e,{detail:"Unable to check subscription for anonymous user"});let u=n.bucketId;if(!u)throw new f(`LoadSubscriptionInboundPolicy '${r}' - no bucketName property provided`);let{authApiJWT:c,meteringServiceUrl:l}=y.instance,{sub:d}=a,p,R;try{if(p=await fetch(`${l}/internal/v1/metering/${u}/subscriptions?customerRef=${d}&status=active`,{headers:{Authorization:`Bearer ${c}`},method:"GET"}),!p.ok)return e.log.error(await p.text()),w.forbidden(t,e);R=await p.json()}catch(h){o.error(`LoadSubscriptionInboundPolicy '${r}' -error in serviceResponse`,h)}if((!R||!R.data||R.data.length===0)&&!i)return w.unauthorized(t,e,{detail:"No valid, active subscription found"});if((!R||!R.data||R.data.length===0)&&i)return t;let g=R&&R.data?R.data[0]:void 0;return ae.set(e,"subscription",g),t},"LoadSubscriptionInboundPolicy");var gn=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 _(`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 Kr=["sha-1","sha-256","sha-384","sha-512"],fn=class{static{s(this,"BaseCryptoBeta")}};var hn=class extends fn{static{s(this,"WorkerCryptoBeta")}async digest(e,n){if(!Kr.includes(e.toLowerCase()))throw new I(`Algorithm ${e} is not supported. Try using ${Kr.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 yn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var bn=class extends yn{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 f("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.1680.0",
3
+ "version": "5.1682.0",
4
4
  "repository": "https://github.com/zuplo/zuplo",
5
5
  "author": "Zuplo, Inc.",
6
6
  "exports": {