@zuplo/runtime 5.2486.0 → 5.2488.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.
Files changed (2) hide show
  1. package/out/esm/index.js +18 -18
  2. package/package.json +1 -1
package/out/esm/index.js CHANGED
@@ -22,17 +22,17 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{a as f,b as Ze,e as Pe,f as Ya,g as Bn,h as Gn,i as Xa,j as eu}from"./chunk-WS4HN7WC.js";import{a as i}from"./chunk-OQPRFCK5.js";var tu=!1;function ct(n,e){return{open:`\x1B[${n.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}i(ct,"code");function lt(n,e){return tu?`${e.open}${n.replace(e.regexp,e.open)}${e.close}`:n}i(lt,"run");function nu(n){return lt(n,ct([31],39))}i(nu,"red");function ru(n){return lt(n,ct([32],39))}i(ru,"green");function ou(n){return lt(n,ct([33],39))}i(ou,"yellow");function iu(n){return lt(n,ct([34],39))}i(iu,"blue");function su(n){return lt(n,ct([35],39))}i(su,"magenta");function au(n){return lt(n,ct([36],39))}i(au,"cyan");var Ld=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");var Ti=[nu,ru,ou,iu,su,au];function uu(n){let e=0,t=n.length,r=0;if(t>0)for(;r<t;)e=(e<<5)-e+n.charCodeAt(r++)|0;return e}i(uu,"hashCode");function vi(n){let e=Math.abs(uu(n));return Ti[e%Ti.length]}i(vi,"generateColor");function Ci(n,e,...t){let r=0,o=t.length,s=String(e).replace(/%[sdjoO%]/g,a=>{if(a==="%%")return"%";if(r>=o)return a;switch(a){case"%s":return String(t[r++]);case"%d":return Number(t[r++]).toString();case"%o":return n(t[r++]).split(`
26
- `).map(u=>u.trim()).join(" ");case"%O":return n(t[r++]);case"%j":try{return JSON.stringify(t[r++])}catch{return"[Circular]"}default:return a}});for(let a of t.splice(r))a===null||!(typeof a=="object"&&a!==null)?s+=" "+a:s+=" "+n(a);return s}i(Ci,"format");function $e(n,e,t,r){let o={seen:[],stylize:cu,showHidden:e??!1,depth:t??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=du),en(o,n,o.depth)}i($e,"inspect");$e.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]};$e.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function cu(n,e){return n}i(cu,"stylizeNoColor");function lu(n){return typeof n=="boolean"}i(lu,"isBoolean");function Oi(n){return n===void 0}i(Oi,"isUndefined");function du(n,e){let t=$e.styles[e];return t?"\x1B["+$e.colors[t][0]+"m"+n+"\x1B["+$e.colors[t][1]+"m":n}i(du,"stylizeWithColor");function Vn(n){return typeof n=="function"}i(Vn,"isFunction");function Ai(n){return typeof n=="string"}i(Ai,"isString");function pu(n){return typeof n=="number"}i(pu,"isNumber");function ki(n){return n===null}i(ki,"isNull");function Li(n,e){return Object.prototype.hasOwnProperty.call(n,e)}i(Li,"hasOwn");function Wn(n){return Yn(n)&&Xn(n)==="[object RegExp]"}i(Wn,"isRegExp");function Yn(n){return typeof n=="object"&&n!==null}i(Yn,"isObject");function Kn(n){return Yn(n)&&(Xn(n)==="[object Error]"||n instanceof Error)}i(Kn,"isError");function Si(n){return Yn(n)&&Xn(n)==="[object Date]"}i(Si,"isDate");function Xn(n){return Object.prototype.toString.call(n)}i(Xn,"objectToString");function mu(n){let e={};return n.forEach(function(t,r){e[t]=!0}),e}i(mu,"arrayToHash");function gu(n,e,t,r,o){let s=[];for(let a=0,u=e.length;a<u;++a)Li(e,String(a))?s.push(Qn(n,e,t,r,String(a),!0)):s.push("");return o.forEach(function(a){a.match(/^\d+$/)||s.push(Qn(n,e,t,r,a,!0))}),s}i(gu,"formatArray");function Jn(n){return"["+Error.prototype.toString.call(n)+"]"}i(Jn,"formatError");function en(n,e,t){if(n.customInspect&&e&&Vn(e.inspect)&&e.inspect!==$e&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(t,n);return Ai(d)||(d=en(n,d,t)),d}let r=fu(n,e);if(r)return r;let o=Object.keys(e),s=mu(o);try{n.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(Kn(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return Jn(e);if(o.length===0){if(Vn(e)){let d=e.name?": "+e.name:"";return n.stylize("[Function"+d+"]","special")}if(Wn(e))return n.stylize(RegExp.prototype.toString.call(e),"regexp");if(Si(e))return n.stylize(Date.prototype.toString.call(e),"date");if(Kn(e))return Jn(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),Vn(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),Wn(e)&&(a=" "+RegExp.prototype.toString.call(e)),Si(e)&&(a=" "+Date.prototype.toUTCString.call(e)),Kn(e)&&(a=" "+Jn(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(t<0)return Wn(e)?n.stylize(RegExp.prototype.toString.call(e),"regexp"):n.stylize("[Object]","special");n.seen.push(e);let l;return u?l=gu(n,e,t,s,o):l=o.map(function(d){return Qn(n,e,t,s,d,u)}),n.seen.pop(),hu(l,a,c)}i(en,"formatValue");function Qn(n,e,t,r,o,s){let a,u,c;c={value:void 0};try{c.value=e[o]}catch{}try{Object.getOwnPropertyDescriptor&&(c=Object.getOwnPropertyDescriptor(e,o)||c)}catch{}if(c.get?c.set?u=n.stylize("[Getter/Setter]","special"):u=n.stylize("[Getter]","special"):c.set&&(u=n.stylize("[Setter]","special")),Li(r,o)||(a="["+o+"]"),u||(n.seen.indexOf(c.value)<0?(ki(t)?u=en(n,c.value,null):u=en(n,c.value,t-1),u.indexOf(`
25
+ import{a as h,b as Ze,e as Pe,f as Ya,g as Bn,h as Gn,i as Xa,j as eu}from"./chunk-WS4HN7WC.js";import{a as i}from"./chunk-OQPRFCK5.js";var tu=!1;function ct(n,e){return{open:`\x1B[${n.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}i(ct,"code");function lt(n,e){return tu?`${e.open}${n.replace(e.regexp,e.open)}${e.close}`:n}i(lt,"run");function nu(n){return lt(n,ct([31],39))}i(nu,"red");function ru(n){return lt(n,ct([32],39))}i(ru,"green");function ou(n){return lt(n,ct([33],39))}i(ou,"yellow");function iu(n){return lt(n,ct([34],39))}i(iu,"blue");function su(n){return lt(n,ct([35],39))}i(su,"magenta");function au(n){return lt(n,ct([36],39))}i(au,"cyan");var Ld=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");var Ti=[nu,ru,ou,iu,su,au];function uu(n){let e=0,t=n.length,r=0;if(t>0)for(;r<t;)e=(e<<5)-e+n.charCodeAt(r++)|0;return e}i(uu,"hashCode");function vi(n){let e=Math.abs(uu(n));return Ti[e%Ti.length]}i(vi,"generateColor");function Ci(n,e,...t){let r=0,o=t.length,s=String(e).replace(/%[sdjoO%]/g,a=>{if(a==="%%")return"%";if(r>=o)return a;switch(a){case"%s":return String(t[r++]);case"%d":return Number(t[r++]).toString();case"%o":return n(t[r++]).split(`
26
+ `).map(u=>u.trim()).join(" ");case"%O":return n(t[r++]);case"%j":try{return JSON.stringify(t[r++])}catch{return"[Circular]"}default:return a}});for(let a of t.splice(r))a===null||!(typeof a=="object"&&a!==null)?s+=" "+a:s+=" "+n(a);return s}i(Ci,"format");function $e(n,e,t,r){let o={seen:[],stylize:cu,showHidden:e??!1,depth:t??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=du),en(o,n,o.depth)}i($e,"inspect");$e.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]};$e.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function cu(n,e){return n}i(cu,"stylizeNoColor");function lu(n){return typeof n=="boolean"}i(lu,"isBoolean");function Si(n){return n===void 0}i(Si,"isUndefined");function du(n,e){let t=$e.styles[e];return t?"\x1B["+$e.colors[t][0]+"m"+n+"\x1B["+$e.colors[t][1]+"m":n}i(du,"stylizeWithColor");function Vn(n){return typeof n=="function"}i(Vn,"isFunction");function Ai(n){return typeof n=="string"}i(Ai,"isString");function pu(n){return typeof n=="number"}i(pu,"isNumber");function ki(n){return n===null}i(ki,"isNull");function Li(n,e){return Object.prototype.hasOwnProperty.call(n,e)}i(Li,"hasOwn");function Wn(n){return Yn(n)&&Xn(n)==="[object RegExp]"}i(Wn,"isRegExp");function Yn(n){return typeof n=="object"&&n!==null}i(Yn,"isObject");function Kn(n){return Yn(n)&&(Xn(n)==="[object Error]"||n instanceof Error)}i(Kn,"isError");function Oi(n){return Yn(n)&&Xn(n)==="[object Date]"}i(Oi,"isDate");function Xn(n){return Object.prototype.toString.call(n)}i(Xn,"objectToString");function mu(n){let e={};return n.forEach(function(t,r){e[t]=!0}),e}i(mu,"arrayToHash");function gu(n,e,t,r,o){let s=[];for(let a=0,u=e.length;a<u;++a)Li(e,String(a))?s.push(Qn(n,e,t,r,String(a),!0)):s.push("");return o.forEach(function(a){a.match(/^\d+$/)||s.push(Qn(n,e,t,r,a,!0))}),s}i(gu,"formatArray");function Jn(n){return"["+Error.prototype.toString.call(n)+"]"}i(Jn,"formatError");function en(n,e,t){if(n.customInspect&&e&&Vn(e.inspect)&&e.inspect!==$e&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(t,n);return Ai(d)||(d=en(n,d,t)),d}let r=fu(n,e);if(r)return r;let o=Object.keys(e),s=mu(o);try{n.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(Kn(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return Jn(e);if(o.length===0){if(Vn(e)){let d=e.name?": "+e.name:"";return n.stylize("[Function"+d+"]","special")}if(Wn(e))return n.stylize(RegExp.prototype.toString.call(e),"regexp");if(Oi(e))return n.stylize(Date.prototype.toString.call(e),"date");if(Kn(e))return Jn(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),Vn(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),Wn(e)&&(a=" "+RegExp.prototype.toString.call(e)),Oi(e)&&(a=" "+Date.prototype.toUTCString.call(e)),Kn(e)&&(a=" "+Jn(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(t<0)return Wn(e)?n.stylize(RegExp.prototype.toString.call(e),"regexp"):n.stylize("[Object]","special");n.seen.push(e);let l;return u?l=gu(n,e,t,s,o):l=o.map(function(d){return Qn(n,e,t,s,d,u)}),n.seen.pop(),hu(l,a,c)}i(en,"formatValue");function Qn(n,e,t,r,o,s){let a,u,c;c={value:void 0};try{c.value=e[o]}catch{}try{Object.getOwnPropertyDescriptor&&(c=Object.getOwnPropertyDescriptor(e,o)||c)}catch{}if(c.get?c.set?u=n.stylize("[Getter/Setter]","special"):u=n.stylize("[Getter]","special"):c.set&&(u=n.stylize("[Setter]","special")),Li(r,o)||(a="["+o+"]"),u||(n.seen.indexOf(c.value)<0?(ki(t)?u=en(n,c.value,null):u=en(n,c.value,t-1),u.indexOf(`
27
27
  `)>-1&&(s?u=u.split(`
28
28
  `).map(function(l){return" "+l}).join(`
29
29
  `).substr(2):u=`
30
30
  `+u.split(`
31
31
  `).map(function(l){return" "+l}).join(`
32
- `))):u=n.stylize("[Circular]","special")),Oi(a)){if(s&&o.match(/^\d+$/))return u;a=JSON.stringify(""+o),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=n.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=n.stylize(a,"string"))}return a+": "+u}i(Qn,"formatProperty");function fu(n,e){if(Oi(e))return n.stylize("undefined","undefined");if(Ai(e)){let t="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return n.stylize(t,"string")}if(pu(e))return n.stylize(""+e,"number");if(lu(e))return n.stylize(""+e,"boolean");if(ki(e))return n.stylize("null","null")}i(fu,"formatPrimitive");function hu(n,e,t){let r=0;return n.reduce(function(s,a){return r++,a.indexOf(`
32
+ `))):u=n.stylize("[Circular]","special")),Si(a)){if(s&&o.match(/^\d+$/))return u;a=JSON.stringify(""+o),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=n.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=n.stylize(a,"string"))}return a+": "+u}i(Qn,"formatProperty");function fu(n,e){if(Si(e))return n.stylize("undefined","undefined");if(Ai(e)){let t="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return n.stylize(t,"string")}if(pu(e))return n.stylize(""+e,"number");if(lu(e))return n.stylize(""+e,"boolean");if(ki(e))return n.stylize("null","null")}i(fu,"formatPrimitive");function hu(n,e,t){let r=0;return n.reduce(function(s,a){return r++,a.indexOf(`
33
33
  `)>=0&&r++,s+a.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?t[0]+(e===""?"":e+`
34
34
  `)+" "+n.join(`,
35
- `)+" "+t[1]:t[0]+e+" "+n.join(", ")+" "+t[1]}i(hu,"reduceToSingleString");var _i=i((n,...e)=>Ci($e,n,e),"format");var er=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=vi(t),this.last=0,this.enabled=e.enabled.some(r=>r.test(t))}log(...e){if(!this.enabled)return;let t,r=e[0];typeof r=="function"?t=r():t=String(r);let o=Date.now()-(this.last||Date.now());t=_i(t,...e);let s=`${this.color(this.ns)} ${t} ${this.color(`+${o}ms`)}`;console.log(s),this.last=Date.now()}},tr=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function yu(n){return!n||n.length===0?[]:(n=n.replace(/\s/g,"").replace(/\*/g,".+"),n.split(",").map(e=>new RegExp(`^${e}$`)))}i(yu,"extract");var tn;function he(n){let e=globalThis.DEBUG;tn||(tn=new tr(yu(e)));let t=new er(tn,n);return tn.debuggers.set(n,t),Object.assign(t.log.bind(t),{self:t})}i(he,"debug");var W=class extends Error{static{i(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},A=class extends Error{static{i(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},m=class extends A{static{i(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}},nn=class extends A{static{i(this,"FeatureNotEnabledError")}constructor(e,t){super(e,t),this.name="FeatureNotEnabledError"}};var Ye=he("zuplo:runtime:external-service");function bu(){let n,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=f.instance.runtime;if(e&&e!=="undefined")try{let t=atob(e);n=JSON.parse(t)}catch{}return n}i(bu,"getServiceAuth");async function Di(n,e){let t=bu();if(t)if(Ye(`Using external service auth. ClientId: ${t.clientId})`),typeof n=="string"){let r=new URL(n),o=r.hostname,s=e??{},a=new Headers(s.headers||{});a.set("CF-Access-Client-Id",t.clientId),a.set("CF-Access-Client-Secret",t.clientSecret),s.headers=a;let u;if(t.customServiceMapping&&t.customServiceMapping[o])u=`https://${t.customServiceMapping[o]}`;else if(f.instance.useLegacyServiceRouting)u=`https://${o}.zuptunnel.com`;else{Ye("Using sha256 service routing");let d=f.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)u=`https://${await wu(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw Ye("Cannot use sha256 service routing, missing build variables"),new A("Failed to generate fully qualified tunnel url.")}let c=new URL(`${u}${r.pathname}${r.search}`);Ye(`Calling external service: ${c.toString()}`);let l=await Z.fetch(c.toString(),s);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:t.clientId,tunnelHost:u}),new A("Could not connect to secure tunnel.");return l}else throw Ye("Cannot call external service with Request object"),new A("Currently, we only support fetch(<some_string>, ...).");else throw Ye("There is no external service auth configured for this zup."),new A("There are no external services configured for this zup.")}i(Di,"externalServiceHandler");async function wu(n,e,t,r){let o=n.toLowerCase(),s=e.toLowerCase(),a=t.toLowerCase(),u=Ru(r);Ye(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await Ni(`${s}-${o}`),l=await Ni(`${s}-${a}-${u}`);return`${c}.${l}`}i(wu,"hashServiceName");async function Ni(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("").slice(0,-1)}i(Ni,"hashSegment");function Ru(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(Ru,"sanitizeEnvironmentType");var qi=new Map;qi.set("service:",Di);var Mi=globalThis.fetch;function nr(n,e){let t=Pu(e);if(typeof n=="string"){let r=new URL(n),o=qi.get(r.protocol);return o?o(n,t):Mi(n,t)}else return Mi(n,t)}i(nr,"internalFetch");globalThis.fetch=nr;var Pu=i(n=>{if(!n||n instanceof Request)return n;let e=n;if(!e.zuplo)return n;let t=n;return t.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete n.zuplo,n},"transformInit");var Iu={fetch:nr},Z=Iu;Function.prototype.toString=function(){return"[native code]"};var rn=globalThis,Ui=rn.caches;if(Ui){let n=Ui.open;rn.caches.open=function(e){let t=f.instance.deploymentName??f.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete rn.caches.default,Object.freeze(rn.caches)}var Hi=new Map,rr=class{static{i(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let t=this.#n.get(e);if(!t)return;let r=Date.now();if(r>t.expiresAt){this.#n.delete(e);return}return t.lastUsed=r,this.#o(),t?.data}put(e,t,r){if(r<=0)return;if(this.#n.size>=this.#e){let a=this.#r.shift();a&&this.#n.delete(a)}let o=Date.now(),s={created:o,lastUsed:o,expiresAt:o+r*1e3,data:t};this.#r.push(e),this.#n.set(e,s)}delete(e){let t=this.#r.indexOf(e);t>=0&&this.#r.slice(t,1),this.#n.delete(e)}get size(){return this.#n.size}#o(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#n.forEach((t,r)=>{t.expiresAt>=e&&this.#n.delete(r)})}},Fe=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=Hi.get(e);r||(r=new rr(t),Hi.set(e,r)),this.#e=r}name;#e;get(e){return this.#e.get(e)}put(e,t,r){return this.#e.put(e,t,r)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var or="__zuplo-expiry-header",Ot=class{static{i(this,"ZoneCache")}constructor(e,t){this.#t=e,this.#e=t}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let t=await this.#r(),r=this.#o(e),o=await t.match(r);if(!o)return;let s=o.headers.get(or);if(!s){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(s);if(Date.now()>=a){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),await this.deleteFallback(e)}return}return await o.json()}catch(t){this.logDebug(t)}}async put(e,t,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(or,`${Date.now()+r*1e3}`);let s=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(t),{headers:o});await s.put(a,u)}async delete(e){let t=await this.#r(),r=this.#o(e);try{await t.delete(r)}catch(o){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",o),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});t.set(or,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),s=new Response("",{headers:t});await r.put(o,s)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var re=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Fe(r),this.#n=new Ot(r,t),this.#r=t}#e;#t;#n;#r;async get(e){let t=this.#t.get(e);if(t)return t;let r=await this.#n.get(e);if(r){let o=Math.floor((r.expires-Date.now())/1e3);if(o>0)return this.#t.put(e,r.data,o),r.data}}put(e,t,r){this.#t.put(e,t,r);let o={data:t,expires:Date.now()+r*1e3},s=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(s)}};var Zi="zuplo-request-id",Xe="zp-rid",ir="zp-body-removed",et="cf-ray",$i="x-real-ip",sr="cf-ipcity",ar="cf-ipcontinent",ur="cf-ipcountry",cr="cf-iplongitude",lr="cf-iplatitude",Fi="cf-region",ji="cf-region-code",zi="cf-metro-code",Bi="cf-postal-code",Gi="cf-timezone",Vi="zp-ipcity",Wi="zp-ipcontinent",Ki="zp-ipcountry",Ji="zp-iplongitude",Qi="zp-iplatitude",Yi="true-client-ip",dr="zp-asn",pr="zp-asorg",mr="zp-colo",gr="zp-postalcode",fr="zp-metrocode",hr="zp-region",yr="zp-regioncode",br="zp-timezone",Xi=[sr,ar,ur,cr,lr,dr,pr,mr,gr,fr,hr,yr,br],es=["zp-","cf-"],ts=[Xe,et,ir];var At=Symbol("zuplo_meters"),kt=Symbol("zuplo_dynamic_meters"),on="system-logger";var oe=class n{static{i(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,t){n.set(e,this.#t,t)}get(e){return n.get(e,this.#t)}static set(e,t,r){n.#e||(n.#e=new WeakMap);let o=n.#e.get(e);o||(o=new Map),o.set(t,r),n.#e.set(e,o)}static get(e,t){return n.#e||(n.#e=new WeakMap),n.#e.get(e)?.get(t)}};import{trace as oc}from"@opentelemetry/api";import{SpanStatusCode as Eu,trace as xu}from"@opentelemetry/api";import{SpanStatusCode as Ir,trace as Er}from"@opentelemetry/api";var ns=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function rs(n){ns=n}i(rs,"setTelemetryInitFunction");var os=i(n=>ns(n),"proxyHandler");var je=class{static{i(this,"RuntimePlugin")}},qe=class extends je{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},sn=class extends qe{static{i(this,"MeteringPlugin")}},Lt=class extends je{static{i(this,"TelemetryPlugin")}};var an=new Set,is=new Set;function g(n){is.has(n)||(is.add(n),an.add(n))}i(g,"trackFeature");function ss(){let n=[...an];return an.clear(),n}i(ss,"getUnsentFeatures");function as(n){for(let e of n)an.add(e)}i(as,"restoreFeatures");var _t=class n{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=i(async e=>{let t=e.problem,r=JSON.stringify(t,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})},"problemResponseFormat");static setProblemResponseFormat(e){e&&(g("runtime.problem-response-formatter"),n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(s){throw new A("Error in custom 'problemResponseFormat'",{cause:s})}})}},tt=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,r){return await _t.problemResponseFormat(e,t,r)}};function un(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&un(t)}return Object.freeze(n)}i(un,"deepFreeze");var te=class n extends Request{static{i(this,"ZuploRequest")}#e=void 0;#t;constructor(e,t){super(e,t);let r=t?.params;r?this.#t=r:e instanceof n?this.#t=e.#t:this.#t={};let o=t?.user;o?this.user=o:e instanceof n&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},t=new URL(this.url).searchParams;for(let[r,o]of t.entries())e[r]=o;this.#e=e}return un(this.#e)}get params(){return un(this.#t)}user};var Nt={},Ue=[],wr=[],Rr=[],Pr=[];var cn={addPlugin(n){Ue.push(n)},addRequestHook(n){wr.push(n)},addResponseSendingHook(n){Rr.push(n)},addResponseSendingFinalHook(n){Pr.push(n)}},cs=i(async(n,e)=>{if(wr.length===0)return n;let t=Er.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let s of wr){let a=await t.startActiveSpan(s.name,async u=>{let c=await s(o,e);if(c instanceof te||c instanceof Response)return u.end(),c;{let l=new m(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw u.end(),u.recordException(l),u.setStatus({code:Ir.ERROR}),l}});if(a instanceof te)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),ls=i(async(n,e,t)=>{if(Rr.length===0)return n;let r=Er.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let s=n;for(let a of Rr)await r.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)s=c,u.end();else{let l=new m(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof s}.`);throw u.recordException(l),u.setStatus({code:Ir.ERROR}),u.end(),l}});return s}finally{o.end()}})},"invokeOnResponseSendingExtensions"),ds=i(async(n,e,t)=>{if(Pr.length===0)return;let r=Er.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let s of Pr)await r.startActiveSpan(s.name,async a=>{try{await s(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:Ir.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),us=!1;async function ps(n){if(!us){n&&(g("runtime.extensions"),await n(cn)),Nt.value=cn;for(let e of Ue)if(e instanceof Lt){let{requestHandlerProxy:t}=e.instrument({accountName:f.instance.build.ACCOUNT_NAME,projectName:f.instance.build.PROJECT_NAME,buildId:f.instance.build.BUILD_ID,zuploVersion:f.instance.build.ZUPLO_VERSION,compatibilityDate:f.instance.build.COMPATIBILITY_DATE,instanceId:f.instance.instanceId,environmentType:f.instance.loggingEnvironmentType,environmentStage:f.instance.loggingEnvironmentStage,deploymentName:f.instance.deploymentName});rs(t)}for(let e of Ue)e instanceof qe&&await e.initialize(cn);_t.setProblemResponseFormat(cn.problemResponseFormat),us=!0}}i(ps,"initializeRuntime");var xr={Json:"application/json",Form:"application/x-www-form-urlencoded"};function Tr(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(xr.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(xr.Json)||!e?JSON.stringify(n):n}i(Tr,"serialize");function dt(n){return ge.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(ge.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}i(dt,"isSystemRoute");var me=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=i((e,t)=>async(r,o)=>xu.getTracer("pipeline").startActiveSpan(`handler:${o.route.handler.export}`,async a=>{try{return await e(r,o)}catch(u){o.log.error("Error executing request handler.",u);let c=t.errorHandler(r,o,u);return a.setStatus({code:Eu.ERROR}),c}finally{a.end()}}),"#errorWrappedHandler");#t=i(({processors:e,gateway:t,handler:r})=>async(o,s)=>{let a=[...e],u=i(async P=>{let v=a.pop();return v?v(o,s,t,u):await this.#e(async j=>{let q=await r(j,s);return Tu(q)},t)(P,s)},"nextPipe"),l=await u(o),d=new URL(o.url);if(dt(d)&&f.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new Dt(o,l);s.dispatchEvent(p);let h=be.getContextExtensions(s),y=h.latestRequest,O;try{O=await p.mutableResponse}catch(P){return s.log.error(P),t.errorHandler(o,s,P)}try{O=await h.onResponseSending(O,y,s)}catch(P){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(o,s,P)}try{O=await ls(O,y,s)}catch(P){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(o,s,P)}s.dispatchEvent(new Mt(o,O));try{await h.onResponseSendingFinal(l,y,s)}catch(P){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}try{await ds(l,y,s)}catch(P){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}return O},"#toZuploPipeline")};function Tu(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(Tr(n),{headers:{"content-type":"application/json"}})}i(Tu,"resultToResponse");var ln=(w=>(w[w.CONTINUE=100]="CONTINUE",w[w.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",w[w.PROCESSING=102]="PROCESSING",w[w.EARLY_HINTS=103]="EARLY_HINTS",w[w.OK=200]="OK",w[w.CREATED=201]="CREATED",w[w.ACCEPTED=202]="ACCEPTED",w[w.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",w[w.NO_CONTENT=204]="NO_CONTENT",w[w.RESET_CONTENT=205]="RESET_CONTENT",w[w.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",w[w.MULTI_STATUS=207]="MULTI_STATUS",w[w.ALREADY_REPORTED=208]="ALREADY_REPORTED",w[w.IM_USED=226]="IM_USED",w[w.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",w[w.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",w[w.FOUND=302]="FOUND",w[w.SEE_OTHER=303]="SEE_OTHER",w[w.NOT_MODIFIED=304]="NOT_MODIFIED",w[w.USE_PROXY=305]="USE_PROXY",w[w.SWITCH_PROXY=306]="SWITCH_PROXY",w[w.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",w[w.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",w[w.BAD_REQUEST=400]="BAD_REQUEST",w[w.UNAUTHORIZED=401]="UNAUTHORIZED",w[w.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",w[w.FORBIDDEN=403]="FORBIDDEN",w[w.NOT_FOUND=404]="NOT_FOUND",w[w.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",w[w.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",w[w.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",w[w.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",w[w.CONFLICT=409]="CONFLICT",w[w.GONE=410]="GONE",w[w.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",w[w.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",w[w.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",w[w.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",w[w.URI_TOO_LONG=414]="URI_TOO_LONG",w[w.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",w[w.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",w[w.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",w[w.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",w[w.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",w[w.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",w[w.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",w[w.LOCKED=423]="LOCKED",w[w.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",w[w.TOO_EARLY=425]="TOO_EARLY",w[w.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",w[w.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",w[w.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",w[w.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",w[w.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",w[w.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",w[w.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",w[w.BAD_GATEWAY=502]="BAD_GATEWAY",w[w.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",w[w.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",w[w.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",w[w.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",w[w.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",w[w.LOOP_DETECTED=508]="LOOP_DETECTED",w[w.NOT_EXTENDED=510]="NOT_EXTENDED",w[w.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",w))(ln||{}),ms={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 vu={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"},vr=vu;function Cu(n){return`${new URL(n.url).pathname}`}i(Cu,"instance");function Su(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:f.instance.build.BUILD_ID},r=n.headers.get(et);return r&&(t.rayId=r),t}i(Su,"trace");var Ou=i((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:Cu(e),trace:Su(e,t),...r},additionalHeaders:o,statusText:vr[n.status]}),"merge"),Cr=class{static{i(this,"HttpProblemsBase")}static format=i((e,t,r)=>"problem"in e?tt.format(e,t,r):tt.format({problem:e},t,r),"format");static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:ms[e],...t}}},x=class extends Cr{static{i(this,"HttpProblems")}static#e(e,t,r,o,s){let a=Ou(this.getProblemFromStatus(e),t,r,o,s);return tt.format(a,t,r)}static continue=i((e,t,r,o)=>this.#e(200,e,t,r,o),"continue");static switchingProtocols=i((e,t,r,o)=>this.#e(101,e,t,r,o),"switchingProtocols");static processing=i((e,t,r,o)=>this.#e(102,e,t,r,o),"processing");static earlyHints=i((e,t,r,o)=>this.#e(103,e,t,r,o),"earlyHints");static ok=i((e,t,r,o)=>this.#e(200,e,t,r,o),"ok");static created=i((e,t,r,o)=>this.#e(201,e,t,r,o),"created");static accepted=i((e,t,r,o)=>this.#e(202,e,t,r,o),"accepted");static nonAuthoritativeInformation=i((e,t,r,o)=>this.#e(203,e,t,r,o),"nonAuthoritativeInformation");static noContent=i((e,t,r,o)=>this.#e(204,e,t,r,o),"noContent");static resetContent=i((e,t,r,o)=>this.#e(205,e,t,r,o),"resetContent");static partialContent=i((e,t,r,o)=>this.#e(206,e,t,r,o),"partialContent");static multiStatus=i((e,t,r,o)=>this.#e(207,e,t,r,o),"multiStatus");static alreadyReported=i((e,t,r,o)=>this.#e(208,e,t,r,o),"alreadyReported");static imUsed=i((e,t,r,o)=>this.#e(226,e,t,r,o),"imUsed");static multipleChoices=i((e,t,r,o)=>this.#e(300,e,t,r,o),"multipleChoices");static movedPermanently=i((e,t,r,o)=>this.#e(301,e,t,r,o),"movedPermanently");static found=i((e,t,r,o)=>this.#e(302,e,t,r,o),"found");static seeOther=i((e,t,r,o)=>this.#e(303,e,t,r,o),"seeOther");static notModified=i((e,t,r,o)=>this.#e(304,e,t,r,o),"notModified");static useProxy=i((e,t,r,o)=>this.#e(305,e,t,r,o),"useProxy");static switchProxy=i((e,t,r,o)=>this.#e(306,e,t,r,o),"switchProxy");static temporaryRedirect=i((e,t,r,o)=>this.#e(307,e,t,r,o),"temporaryRedirect");static permanentRedirect=i((e,t,r,o)=>this.#e(308,e,t,r,o),"permanentRedirect");static badRequest=i((e,t,r,o)=>this.#e(400,e,t,r,o),"badRequest");static unauthorized=i((e,t,r,o)=>this.#e(401,e,t,r,o),"unauthorized");static paymentRequired=i((e,t,r,o)=>this.#e(402,e,t,r,o),"paymentRequired");static forbidden=i((e,t,r,o)=>this.#e(403,e,t,r,o),"forbidden");static notFound=i((e,t,r,o)=>this.#e(404,e,t,r,o),"notFound");static methodNotAllowed=i((e,t,r,o)=>this.#e(405,e,t,r,o),"methodNotAllowed");static notAcceptable=i((e,t,r,o)=>this.#e(406,e,t,r,o),"notAcceptable");static proxyAuthenticationRequired=i((e,t,r,o)=>this.#e(407,e,t,r,o),"proxyAuthenticationRequired");static requestTimeout=i((e,t,r,o)=>this.#e(408,e,t,r,o),"requestTimeout");static conflict=i((e,t,r,o)=>this.#e(409,e,t,r,o),"conflict");static gone=i((e,t,r,o)=>this.#e(410,e,t,r,o),"gone");static lengthRequired=i((e,t,r,o)=>this.#e(411,e,t,r,o),"lengthRequired");static preconditionFailed=i((e,t,r,o)=>this.#e(412,e,t,r,o),"preconditionFailed");static contentTooLarge=i((e,t,r,o)=>this.#e(413,e,t,r,o),"contentTooLarge");static uriTooLong=i((e,t,r,o)=>this.#e(414,e,t,r,o),"uriTooLong");static unsupportedMediaType=i((e,t,r,o)=>this.#e(415,e,t,r,o),"unsupportedMediaType");static rangeNotSatisfiable=i((e,t,r,o)=>this.#e(416,e,t,r,o),"rangeNotSatisfiable");static expectationFailed=i((e,t,r,o)=>this.#e(417,e,t,r,o),"expectationFailed");static imATeapot=i((e,t,r,o)=>this.#e(418,e,t,r,o),"imATeapot");static misdirectedRequest=i((e,t,r,o)=>this.#e(421,e,t,r,o),"misdirectedRequest");static unprocessableContent=i((e,t,r,o)=>this.#e(422,e,t,r,o),"unprocessableContent");static locked=i((e,t,r,o)=>this.#e(423,e,t,r,o),"locked");static failedDependency=i((e,t,r,o)=>this.#e(424,e,t,r,o),"failedDependency");static tooEarly=i((e,t,r,o)=>this.#e(425,e,t,r,o),"tooEarly");static upgradeRequired=i((e,t,r,o)=>this.#e(426,e,t,r,o),"upgradeRequired");static preconditionRequired=i((e,t,r,o)=>this.#e(428,e,t,r,o),"preconditionRequired");static tooManyRequests=i((e,t,r,o)=>this.#e(429,e,t,r,o),"tooManyRequests");static requestHeaderFieldsTooLarge=i((e,t,r,o)=>this.#e(431,e,t,r,o),"requestHeaderFieldsTooLarge");static unavailableForLegalReasons=i((e,t,r,o)=>this.#e(451,e,t,r,o),"unavailableForLegalReasons");static internalServerError=i((e,t,r,o)=>this.#e(500,e,t,r,o),"internalServerError");static notImplemented=i((e,t,r,o)=>this.#e(501,e,t,r,o),"notImplemented");static badGateway=i((e,t,r,o)=>this.#e(502,e,t,r,o),"badGateway");static serviceUnavailable=i((e,t,r,o)=>this.#e(503,e,t,r,o),"serviceUnavailable");static gatewayTimeout=i((e,t,r,o)=>this.#e(504,e,t,r,o),"gatewayTimeout");static httpVersionNotSupported=i((e,t,r,o)=>this.#e(505,e,t,r,o),"httpVersionNotSupported");static variantAlsoNegotiates=i((e,t,r,o)=>this.#e(506,e,t,r,o),"variantAlsoNegotiates");static insufficientStorage=i((e,t,r,o)=>this.#e(507,e,t,r,o),"insufficientStorage");static loopDetected=i((e,t,r,o)=>this.#e(508,e,t,r,o),"loopDetected");static notExtended=i((e,t,r,o)=>this.#e(510,e,t,r,o),"notExtended");static networkAuthenticationRequired=i((e,t,r,o)=>this.#e(511,e,t,r,o),"networkAuthenticationRequired")};var ze=class extends je{static{i(this,"MetricsPlugin")}};var Q=class n{static{i(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let t=n.#e.get(e);if(!t){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new W(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var Y=class{static{i(this,"BatchDispatch")}constructor(e,t,r,o){this.#t=e,this.#i=t,this.#r=r,this.#n=o??console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=i(e=>{this.#o.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{t()})}},this.#i)}))},"enqueue");waitUntilFlushed=i(async()=>{if(this.#e)return this.#e},"waitUntilFlushed")};var dn=class{static{i(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=f.instance.loggingId,this.#e=e,this.#t=new Y("ellie-metrics-transport",10,this.dispatchFunction,Q.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=i(async e=>{if(e.length===0)return;let{remoteLogURL:t,deploymentName:r}=f.instance,{ACCOUNT_NAME:o,PROJECT_NAME:s}=f.instance.build,a=e.map(d=>{let p=Object.assign({},d);return delete p.requestContentLength,delete p.responseContentLength,p}),u=ss(),c={metadata:{timestamp:new Date,accountName:o,projectName:s,deploymentName:r},metrics:a,features:u},l=await Z.fetch(`${t}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(c),headers:{"content-type":"application/json","zp-dn":f.instance.deploymentName??"unknown","user-agent":f.instance.systemUserAgent}});if(!l.ok){let d=await l.text();Q.getLogger(this.#e).error(`Metrics POST responded ${l.status}: ${l.statusText}`,d),as(u)}},"dispatchFunction")};var ce=class{static{i(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:r,systemRouteName:o,corsPolicy:s="none"}){this.label=e,this.path=t,this.methods=r,this.corsPolicy=s,this.version=qt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},qt={name:"__system-no-version",pathPrefix:""};var we=i(async(n,e,t,r)=>{let o=new Date,s=Date.now(),a=await r(n),u=n.headers.get(et)??void 0,c=n.headers.get(Yi)??void 0,l=e.incomingRequestProperties,d;e.route instanceof ce&&(d=e.route.systemRouteName);let p=be.getContextExtensions(e).latestRequest,h={timestamp:o,statusCode:a.status,durationMs:Date.now()-s,requestContentLength:n.headers.get("content-length")?Number(n.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:n.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:f.instance.instanceId,userSub:p.user?.sub,clientIp:c},y=[];return y.push(new dn(e)),Ue.forEach(O=>{if(O instanceof ze){let P=O.getTransport();y.push(P)}}),y.forEach(O=>{O.pushMetrics(h,e)}),a},"metricsProcessor");var Sr=i((n,e)=>{let t=i(async(s,a)=>{let c=new URL(s.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return x.notFound(s,a);let l=f.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,compatibilityDate:l.COMPATIBILITY_DATE,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.ENVIRONMENT_TYPE==="PRODUCTION"},p=s.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&Q.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new me({processors:[we],handler:t,gateway:e}),o=new ce({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var{toString:Au}=Object.prototype,{propertyIsEnumerable:ku}=Object.prototype;function Or(n){return Au.call(n)}i(Or,"toString");function xe(n){return typeof n=="string"}i(xe,"isString");function pt(n){return xe(n)&&n!==""}i(pt,"isNonEmptyString");function gs(n){return Or(n)==="[object RegExp]"}i(gs,"isRegexp");function fs(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>ku.call(n,e))]}i(fs,"getOwnEnumerableKeys");function nt(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}i(nt,"isObject");function Ar(n){return typeof n=="number"&&!isNaN(n)}i(Ar,"isNumber");function kr(n){return n===!0||n===!1}i(kr,"isBoolean");function hs(n){return typeof n>"u"}i(hs,"isUndefined");function ys(n){return hs(n)||n===null}i(ys,"isUndefinedOrNull");function Ut(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(Ut,"isErrorLike");var bs=new Map;function Be(n){if(Array.isArray(n)&&!n.some(o=>typeof o!="number"))return n;if(typeof n!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(n))throw new Error("Malformed input string");let e=bs.get(n);if(e)return e;let t=n.split(","),r=[];for(let o of t){let s=o.split("-");if(s.length===2){let a=parseInt(s[0],10),u=parseInt(s[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return bs.set(n,r),r}i(Be,"statusCodesStringToNumberArray");function rt(n,e,t){if(!e.startsWith("."))throw new m(`Invalid ${t} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=n;return r.forEach(s=>{if(o===void 0)throw new A(`Error applying ${t} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i(rt,"getValueFromRequestUser");function ot(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new m("Received an array that contains non-string values.");return n}if(xe(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new m(`Expected type of string, received type '${typeof n}'`)}i(ot,"parseValueToStringArray");function ws(n){if(n==null)return[];if(!Array.isArray(n))throw new m(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!nt(t))throw new m(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!pt(t.name))throw new m("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!Ar(t.maxAge))throw new m(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!kr(t.allowCredentials))throw new m("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let r=Lr(t,"allowedHeaders"),o=Lr(t,"allowedMethods"),s=Lr(t,"exposeHeaders"),a;try{a=ot(t.allowedOrigins)}catch(c){throw new m(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:t.name,allowCredentials:typeof t.allowCredentials=="boolean"?String(t.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:r?r.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:s?s.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}i(ws,"parseCorsPolicies");function Lr(n,e){let t;if(n[e]!==void 0)try{t=ot(n[e])}catch(r){throw new m(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return t}i(Lr,"parseOptionalProperty");var pn=i((n,e)=>{if(e===null)return;if(n.find(a=>a==="*"))return e;let r=n.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),mn=i((n,e)=>{let t={"access-control-allow-origin":e};n.allowedHeaders&&(t["access-control-allow-headers"]=n.allowedHeaders),n.allowedMethods&&(t["access-control-allow-methods"]=n.allowedMethods),n.exposeHeaders&&(t["access-control-expose-headers"]=n.exposeHeaders);let r=n.allowCredentials;r&&(t["access-control-allow-credentials"]=r);let o=n.maxAge?.toString()??void 0;return o&&(t["access-control-max-age"]=o),t},"generateCorsHeaders");var _r=i((n,e)=>{let t=e.routeData.corsPolicies,r=i(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return x.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let h=n.lookup(l,c);if(!h)return x.notFound(a,u);let y=h.routeConfiguration,O=Lu(l,d,p,y,t);return O.isValid?new Response(void 0,{status:200,statusText:"OK",headers:O.headers}):(O.error&&u.log.warn(O.error),x.notFound(a,u))},"optionsHandler"),o=new me({processors:[we],handler:r,gateway:e}),s=new ce({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(s,o.execute)},"registerCorsRoute"),Lu=i((n,e,t,r,o)=>{let s={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":t,"access-control-allow-methods":n,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...s,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new m(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=pn(a.allowedOrigins,t);return u?{isValid:!0,headers:mn(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var Rs=i((n,e)=>{let t=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new me({processors:[we],handler:t,gateway:e}),o=new ce({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});n.addRoute(o,r.execute)},"registerNoRoutes");var Nr=new ce({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Ps=i((n,e)=>{let t=i(async(o,s)=>{let a=Nt.value?.notFoundHandler;if(a){let u=be.getContextExtensions(s);return a(o,s,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return x.notFound(o,s)},"notFoundHandler"),r=new me({processors:[we],handler:t,gateway:e});n.addRoute(Nr,r.execute)},"registerNotMatchedHandler");var _u=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Is=i(n=>{_u.forEach(e=>n.delete(e))},"stripCorsHeaders"),gn=i(async(n,e,t,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await r(n),p=new Headers(d.headers);return Is(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await r(n);if(!(s instanceof Response))throw new W(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=Nu(o,t.routeData.corsPolicies),u=Du(n,a),c=new Headers(s.headers);return Is(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(s.body,{status:s.status,statusText:s.statusText,headers:c,webSocket:s.webSocket})},"corsProcessor"),Nu=i((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(r=>r.name===n.corsPolicy);if(t===void 0)throw new m(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),Du=i((n,e)=>{let t=pn(e.allowedOrigins,n.headers.get("origin"));return t?mn(e,t):{}},"getCorsHeaders");var Dr=i((n,e)=>{let t=i(async()=>new Response(JSON.stringify({buildId:f.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new me({processors:[gn],handler:t,gateway:e}),o=new ce({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");import{SpanStatusCode as Es,trace as xs}from"@opentelemetry/api";var _e={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var fn=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!xe(t))throw new A(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},ae=class extends fn{static{i(this,"InboundPolicy")}},Ge=class extends fn{static{i(this,"OutboundPolicy")}};var Ur=class extends ae{static{i(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t){return this.#e(e,t,this.options,this.policyName)}},Hr=class extends Ge{static{i(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t,r){return this.#e(e,t,r,this.options,this.policyName)}},Mr=new Map;function Ht(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(s=>!Mr.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new m(`Invalid state - no Policy with the name '${s}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof ae)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new Ur(u,a.handler.options,a.name);else throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${s}' on route '${r}' (typeof handler '${typeof c.handler}')`);Mr.set(a.name,c)}),t.map(s=>{let a=Mr.get(s);if(a===void 0)throw new A("Internal error. Policy not found in cache.");return a})}i(Ht,"getInboundPolicyInstances");var qr=new Map;function Zt(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.outbound??[],r=n.path),t.filter(s=>!qr.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new m(`Invalid state - no Policy with the name '${s}' on route '${r}' was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export],c;if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof Ge)c=new u(a.handler.options??{},a.name);else if(typeof u=="function")c=new Hr(u,a.handler.options??{},a.name);else throw new m(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${s}' on route '${r}'`);qr.set(a.name,c)}),t.map(s=>{let a=qr.get(s);if(a===void 0)throw new A("Internal error. Policy not found in cache.");return a})}i(Zt,"getOutboundPolicyInstances");var Zr=i(n=>async(e,t)=>{let r=be.getContextExtensions(t),o=xs.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;let l=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{let p=await c.handler(u,t);if(p instanceof Request||p instanceof te||p instanceof Response)return d.end(),p;{let h=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${t.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:Es.ERROR}),d.recordException(h),h}});if(l instanceof te)u=l;else if(l instanceof Request)u=new te(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),$r=i(n=>async(e,t,r)=>{let o=xs.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(_e.PolicyName,c.policyName),d.setAttribute(_e.PolicyType,c.policyType);let p=await c.handler(u,t,r);if(p instanceof Response)return p;{let h=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:Es.ERROR}),d.recordException(h),h}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),hn=i(async(n,e,t,r)=>{let o=Ht(e.route,t.routeData.policies),s=Zt(e.route,t.routeData.policies);return vs({request:n,context:e,inboundPolicies:o,outboundPolicies:s,gateway:t,next:r})},"policyProcessor");function Ts({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>vs({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(Ts,"createInternalPolicyProcessor");async function vs({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:s}){let a=Zr(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await s(u),l=$r(r),d;return f.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,n,e):d=c.ok?l(c,n,e):c,d}catch(u){return e.log.error(u),o.errorHandler(n,e,u)}}i(vs,"executePolicyProcessor");function Cs(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||Mu,s=0;for(;s<n.length;){let a=n.indexOf("=",s);if(a===-1)break;let u=n.indexOf(";",s);if(u===-1)u=n.length;else if(u<a){s=n.lastIndexOf(";",a-1)+1;continue}let c=n.slice(s,a).trim();if(t[c]===void 0){let l=n.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),t[c]=qu(l,o)}s=u+1}return t}i(Cs,"parse");function Mu(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}i(Mu,"decode");function qu(n,e){try{return e(n)}catch{return n}}i(qu,"tryDecode");function Ss(n,e){try{let t=/v\d+(-\d+)?/g,o=Cs(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}i(Ss,"devPortalBaseURL");var Os="/__zuplo/dev-portal",Uu="dev-portal-id",Hu="dev-portal-host",Zu="zp-account",$u="zp-project",Fu="dev-portal-build",ju=`
35
+ `)+" "+t[1]:t[0]+e+" "+n.join(", ")+" "+t[1]}i(hu,"reduceToSingleString");var _i=i((n,...e)=>Ci($e,n,e),"format");var er=class{static{i(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=vi(t),this.last=0,this.enabled=e.enabled.some(r=>r.test(t))}log(...e){if(!this.enabled)return;let t,r=e[0];typeof r=="function"?t=r():t=String(r);let o=Date.now()-(this.last||Date.now());t=_i(t,...e);let s=`${this.color(this.ns)} ${t} ${this.color(`+${o}ms`)}`;console.log(s),this.last=Date.now()}},tr=class{static{i(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function yu(n){return!n||n.length===0?[]:(n=n.replace(/\s/g,"").replace(/\*/g,".+"),n.split(",").map(e=>new RegExp(`^${e}$`)))}i(yu,"extract");var tn;function he(n){let e=globalThis.DEBUG;tn||(tn=new tr(yu(e)));let t=new er(tn,n);return tn.debuggers.set(n,t),Object.assign(t.log.bind(t),{self:t})}i(he,"debug");var W=class extends Error{static{i(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},S=class extends Error{static{i(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},g=class extends S{static{i(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}},nn=class extends S{static{i(this,"FeatureNotEnabledError")}constructor(e,t){super(e,t),this.name="FeatureNotEnabledError"}};var Ye=he("zuplo:runtime:external-service");function bu(){let n,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=h.instance.runtime;if(e&&e!=="undefined")try{let t=atob(e);n=JSON.parse(t)}catch{}return n}i(bu,"getServiceAuth");async function Di(n,e){let t=bu();if(t)if(Ye(`Using external service auth. ClientId: ${t.clientId})`),typeof n=="string"){let r=new URL(n),o=r.hostname,s=e??{},a=new Headers(s.headers||{});a.set("CF-Access-Client-Id",t.clientId),a.set("CF-Access-Client-Secret",t.clientSecret),s.headers=a;let u,c;if(h.instance.useLegacyServiceRouting)u=`https://${o}.zuptunnel.com`;else{Ye("Using sha256 service routing");let m=h.instance.build;if(m.ACCOUNT_NAME&&m.PROJECT_NAME&&m.ENVIRONMENT_TYPE){let y=await wu(o,m.ACCOUNT_NAME,m.PROJECT_NAME,m.ENVIRONMENT_TYPE);u=`https://${y}.t.zuplo.app`,c=`https://${y}.zuptunnel.com`}else throw Ye("Cannot use sha256 service routing, missing build variables"),new S("Failed to generate fully qualified tunnel url.")}let l=new URL(`${u}${r.pathname}${r.search}`);Ye(`Calling external service: ${l.toString()}`);let d=new Request(l.toString(),s),p;c&&(p=new Request(`${c}${r.pathname}${r.search}`,d.clone()));try{let m=await Z.fetch(d);if(m.status===403&&m.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:t.clientId,tunnelHost:u}),new S("Could not connect to secure tunnel.");return m.status===522&&p?await Z.fetch(p):m}catch{if(p){let y=await Z.fetch(p);if(y.status===403&&y.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:t.clientId,tunnelHost:u}),new S("Could not connect to secure tunnel.");return y}else throw new S("Could not connect to secure tunnel.")}}else throw Ye("Cannot call external service with Request object"),new S("Currently, we only support fetch(<some_string>, ...).");else throw Ye("There is no external service auth configured for this zup."),new S("There are no external services configured for this zup.")}i(Di,"externalServiceHandler");async function wu(n,e,t,r){let o=n.toLowerCase(),s=e.toLowerCase(),a=t.toLowerCase(),u=Ru(r);Ye(`Hashing service name: ${s}-${o}.${s}-${a}-${u}`);let c=await Ni(`${s}-${o}`),l=await Ni(`${s}-${a}-${u}`);return`${c}.${l}`}i(wu,"hashServiceName");async function Ni(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("").slice(0,-1)}i(Ni,"hashSegment");function Ru(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}i(Ru,"sanitizeEnvironmentType");var qi=new Map;qi.set("service:",Di);var Mi=globalThis.fetch;function nr(n,e){let t=Pu(e);if(typeof n=="string"){let r=new URL(n),o=qi.get(r.protocol);return o?o(n,t):Mi(n,t)}else return Mi(n,t)}i(nr,"internalFetch");globalThis.fetch=nr;var Pu=i(n=>{if(!n||n instanceof Request)return n;let e=n;if(!e.zuplo)return n;let t=n;return t.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete n.zuplo,n},"transformInit");var Iu={fetch:nr},Z=Iu;Function.prototype.toString=function(){return"[native code]"};var rn=globalThis,Hi=rn.caches;if(Hi){let n=Hi.open;rn.caches.open=function(e){let t=h.instance.deploymentName??h.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete rn.caches.default,Object.freeze(rn.caches)}var Ui=new Map,rr=class{static{i(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let t=this.#n.get(e);if(!t)return;let r=Date.now();if(r>t.expiresAt){this.#n.delete(e);return}return t.lastUsed=r,this.#o(),t?.data}put(e,t,r){if(r<=0)return;if(this.#n.size>=this.#e){let a=this.#r.shift();a&&this.#n.delete(a)}let o=Date.now(),s={created:o,lastUsed:o,expiresAt:o+r*1e3,data:t};this.#r.push(e),this.#n.set(e,s)}delete(e){let t=this.#r.indexOf(e);t>=0&&this.#r.slice(t,1),this.#n.delete(e)}get size(){return this.#n.size}#o(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#n.forEach((t,r)=>{t.expiresAt>=e&&this.#n.delete(r)})}},Fe=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=Ui.get(e);r||(r=new rr(t),Ui.set(e,r)),this.#e=r}name;#e;get(e){return this.#e.get(e)}put(e,t,r){return this.#e.put(e,t,r)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var or="__zuplo-expiry-header",St=class{static{i(this,"ZoneCache")}constructor(e,t){this.#t=e,this.#e=t}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let t=await this.#r(),r=this.#o(e),o=await t.match(r);if(!o)return;let s=o.headers.get(or);if(!s){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(s);if(Date.now()>=a){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),await this.deleteFallback(e)}return}return await o.json()}catch(t){this.logDebug(t)}}async put(e,t,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(or,`${Date.now()+r*1e3}`);let s=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(t),{headers:o});await s.put(a,u)}async delete(e){let t=await this.#r(),r=this.#o(e);try{await t.delete(r)}catch(o){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",o),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});t.set(or,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),s=new Response("",{headers:t});await r.put(o,s)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var re=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Fe(r),this.#n=new St(r,t),this.#r=t}#e;#t;#n;#r;async get(e){let t=this.#t.get(e);if(t)return t;let r=await this.#n.get(e);if(r){let o=Math.floor((r.expires-Date.now())/1e3);if(o>0)return this.#t.put(e,r.data,o),r.data}}put(e,t,r){this.#t.put(e,t,r);let o={data:t,expires:Date.now()+r*1e3},s=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(s)}};var Zi="zuplo-request-id",Xe="zp-rid",ir="zp-body-removed",et="cf-ray",$i="x-real-ip",sr="cf-ipcity",ar="cf-ipcontinent",ur="cf-ipcountry",cr="cf-iplongitude",lr="cf-iplatitude",Fi="cf-region",ji="cf-region-code",zi="cf-metro-code",Bi="cf-postal-code",Gi="cf-timezone",Vi="zp-ipcity",Wi="zp-ipcontinent",Ki="zp-ipcountry",Ji="zp-iplongitude",Qi="zp-iplatitude",Yi="true-client-ip",dr="zp-asn",pr="zp-asorg",mr="zp-colo",gr="zp-postalcode",fr="zp-metrocode",hr="zp-region",yr="zp-regioncode",br="zp-timezone",Xi=[sr,ar,ur,cr,lr,dr,pr,mr,gr,fr,hr,yr,br],es=["zp-","cf-"],ts=[Xe,et,ir];var At=Symbol("zuplo_meters"),kt=Symbol("zuplo_dynamic_meters"),on="system-logger";var oe=class n{static{i(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,t){n.set(e,this.#t,t)}get(e){return n.get(e,this.#t)}static set(e,t,r){n.#e||(n.#e=new WeakMap);let o=n.#e.get(e);o||(o=new Map),o.set(t,r),n.#e.set(e,o)}static get(e,t){return n.#e||(n.#e=new WeakMap),n.#e.get(e)?.get(t)}};import{trace as oc}from"@opentelemetry/api";import{SpanStatusCode as Eu,trace as xu}from"@opentelemetry/api";import{SpanStatusCode as Ir,trace as Er}from"@opentelemetry/api";var ns=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function rs(n){ns=n}i(rs,"setTelemetryInitFunction");var os=i(n=>ns(n),"proxyHandler");var je=class{static{i(this,"RuntimePlugin")}},qe=class extends je{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},sn=class extends qe{static{i(this,"MeteringPlugin")}},Lt=class extends je{static{i(this,"TelemetryPlugin")}};var an=new Set,is=new Set;function f(n){is.has(n)||(is.add(n),an.add(n))}i(f,"trackFeature");function ss(){let n=[...an];return an.clear(),n}i(ss,"getUnsentFeatures");function as(n){for(let e of n)an.add(e)}i(as,"restoreFeatures");var _t=class n{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=i(async e=>{let t=e.problem,r=JSON.stringify(t,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})},"problemResponseFormat");static setProblemResponseFormat(e){e&&(f("runtime.problem-response-formatter"),n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(s){throw new S("Error in custom 'problemResponseFormat'",{cause:s})}})}},tt=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,r){return await _t.problemResponseFormat(e,t,r)}};function un(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&un(t)}return Object.freeze(n)}i(un,"deepFreeze");var te=class n extends Request{static{i(this,"ZuploRequest")}#e=void 0;#t;constructor(e,t){super(e,t);let r=t?.params;r?this.#t=r:e instanceof n?this.#t=e.#t:this.#t={};let o=t?.user;o?this.user=o:e instanceof n&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},t=new URL(this.url).searchParams;for(let[r,o]of t.entries())e[r]=o;this.#e=e}return un(this.#e)}get params(){return un(this.#t)}user};var Nt={},He=[],wr=[],Rr=[],Pr=[];var cn={addPlugin(n){He.push(n)},addRequestHook(n){wr.push(n)},addResponseSendingHook(n){Rr.push(n)},addResponseSendingFinalHook(n){Pr.push(n)}},cs=i(async(n,e)=>{if(wr.length===0)return n;let t=Er.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let s of wr){let a=await t.startActiveSpan(s.name,async u=>{let c=await s(o,e);if(c instanceof te||c instanceof Response)return u.end(),c;{let l=new g(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw u.end(),u.recordException(l),u.setStatus({code:Ir.ERROR}),l}});if(a instanceof te)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),ls=i(async(n,e,t)=>{if(Rr.length===0)return n;let r=Er.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let s=n;for(let a of Rr)await r.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)s=c,u.end();else{let l=new g(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof s}.`);throw u.recordException(l),u.setStatus({code:Ir.ERROR}),u.end(),l}});return s}finally{o.end()}})},"invokeOnResponseSendingExtensions"),ds=i(async(n,e,t)=>{if(Pr.length===0)return;let r=Er.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let s of Pr)await r.startActiveSpan(s.name,async a=>{try{await s(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:Ir.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),us=!1;async function ps(n){if(!us){n&&(f("runtime.extensions"),await n(cn)),Nt.value=cn;for(let e of He)if(e instanceof Lt){let{requestHandlerProxy:t}=e.instrument({accountName:h.instance.build.ACCOUNT_NAME,projectName:h.instance.build.PROJECT_NAME,buildId:h.instance.build.BUILD_ID,zuploVersion:h.instance.build.ZUPLO_VERSION,compatibilityDate:h.instance.build.COMPATIBILITY_DATE,instanceId:h.instance.instanceId,environmentType:h.instance.loggingEnvironmentType,environmentStage:h.instance.loggingEnvironmentStage,deploymentName:h.instance.deploymentName});rs(t)}for(let e of He)e instanceof qe&&await e.initialize(cn);_t.setProblemResponseFormat(cn.problemResponseFormat),us=!0}}i(ps,"initializeRuntime");var xr={Json:"application/json",Form:"application/x-www-form-urlencoded"};function Tr(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(xr.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(xr.Json)||!e?JSON.stringify(n):n}i(Tr,"serialize");function dt(n){return ge.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(ge.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}i(dt,"isSystemRoute");var me=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=i((e,t)=>async(r,o)=>xu.getTracer("pipeline").startActiveSpan(`handler:${o.route.handler.export}`,async a=>{try{return await e(r,o)}catch(u){o.log.error("Error executing request handler.",u);let c=t.errorHandler(r,o,u);return a.setStatus({code:Eu.ERROR}),c}finally{a.end()}}),"#errorWrappedHandler");#t=i(({processors:e,gateway:t,handler:r})=>async(o,s)=>{let a=[...e],u=i(async P=>{let v=a.pop();return v?v(o,s,t,u):await this.#e(async j=>{let q=await r(j,s);return Tu(q)},t)(P,s)},"nextPipe"),l=await u(o),d=new URL(o.url);if(dt(d)&&h.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new Dt(o,l);s.dispatchEvent(p);let m=be.getContextExtensions(s),y=m.latestRequest,A;try{A=await p.mutableResponse}catch(P){return s.log.error(P),t.errorHandler(o,s,P)}try{A=await m.onResponseSending(A,y,s)}catch(P){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(o,s,P)}try{A=await ls(A,y,s)}catch(P){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(o,s,P)}s.dispatchEvent(new Mt(o,A));try{await m.onResponseSendingFinal(l,y,s)}catch(P){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}try{await ds(l,y,s)}catch(P){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}return A},"#toZuploPipeline")};function Tu(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(Tr(n),{headers:{"content-type":"application/json"}})}i(Tu,"resultToResponse");var ln=(w=>(w[w.CONTINUE=100]="CONTINUE",w[w.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",w[w.PROCESSING=102]="PROCESSING",w[w.EARLY_HINTS=103]="EARLY_HINTS",w[w.OK=200]="OK",w[w.CREATED=201]="CREATED",w[w.ACCEPTED=202]="ACCEPTED",w[w.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",w[w.NO_CONTENT=204]="NO_CONTENT",w[w.RESET_CONTENT=205]="RESET_CONTENT",w[w.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",w[w.MULTI_STATUS=207]="MULTI_STATUS",w[w.ALREADY_REPORTED=208]="ALREADY_REPORTED",w[w.IM_USED=226]="IM_USED",w[w.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",w[w.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",w[w.FOUND=302]="FOUND",w[w.SEE_OTHER=303]="SEE_OTHER",w[w.NOT_MODIFIED=304]="NOT_MODIFIED",w[w.USE_PROXY=305]="USE_PROXY",w[w.SWITCH_PROXY=306]="SWITCH_PROXY",w[w.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",w[w.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",w[w.BAD_REQUEST=400]="BAD_REQUEST",w[w.UNAUTHORIZED=401]="UNAUTHORIZED",w[w.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",w[w.FORBIDDEN=403]="FORBIDDEN",w[w.NOT_FOUND=404]="NOT_FOUND",w[w.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",w[w.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",w[w.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",w[w.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",w[w.CONFLICT=409]="CONFLICT",w[w.GONE=410]="GONE",w[w.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",w[w.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",w[w.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",w[w.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",w[w.URI_TOO_LONG=414]="URI_TOO_LONG",w[w.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",w[w.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",w[w.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",w[w.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",w[w.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",w[w.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",w[w.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",w[w.LOCKED=423]="LOCKED",w[w.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",w[w.TOO_EARLY=425]="TOO_EARLY",w[w.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",w[w.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",w[w.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",w[w.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",w[w.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",w[w.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",w[w.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",w[w.BAD_GATEWAY=502]="BAD_GATEWAY",w[w.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",w[w.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",w[w.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",w[w.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",w[w.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",w[w.LOOP_DETECTED=508]="LOOP_DETECTED",w[w.NOT_EXTENDED=510]="NOT_EXTENDED",w[w.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",w))(ln||{}),ms={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 vu={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"},vr=vu;function Cu(n){return`${new URL(n.url).pathname}`}i(Cu,"instance");function Ou(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:h.instance.build.BUILD_ID},r=n.headers.get(et);return r&&(t.rayId=r),t}i(Ou,"trace");var Su=i((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:Cu(e),trace:Ou(e,t),...r},additionalHeaders:o,statusText:vr[n.status]}),"merge"),Cr=class{static{i(this,"HttpProblemsBase")}static format=i((e,t,r)=>"problem"in e?tt.format(e,t,r):tt.format({problem:e},t,r),"format");static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:ms[e],...t}}},x=class extends Cr{static{i(this,"HttpProblems")}static#e(e,t,r,o,s){let a=Su(this.getProblemFromStatus(e),t,r,o,s);return tt.format(a,t,r)}static continue=i((e,t,r,o)=>this.#e(200,e,t,r,o),"continue");static switchingProtocols=i((e,t,r,o)=>this.#e(101,e,t,r,o),"switchingProtocols");static processing=i((e,t,r,o)=>this.#e(102,e,t,r,o),"processing");static earlyHints=i((e,t,r,o)=>this.#e(103,e,t,r,o),"earlyHints");static ok=i((e,t,r,o)=>this.#e(200,e,t,r,o),"ok");static created=i((e,t,r,o)=>this.#e(201,e,t,r,o),"created");static accepted=i((e,t,r,o)=>this.#e(202,e,t,r,o),"accepted");static nonAuthoritativeInformation=i((e,t,r,o)=>this.#e(203,e,t,r,o),"nonAuthoritativeInformation");static noContent=i((e,t,r,o)=>this.#e(204,e,t,r,o),"noContent");static resetContent=i((e,t,r,o)=>this.#e(205,e,t,r,o),"resetContent");static partialContent=i((e,t,r,o)=>this.#e(206,e,t,r,o),"partialContent");static multiStatus=i((e,t,r,o)=>this.#e(207,e,t,r,o),"multiStatus");static alreadyReported=i((e,t,r,o)=>this.#e(208,e,t,r,o),"alreadyReported");static imUsed=i((e,t,r,o)=>this.#e(226,e,t,r,o),"imUsed");static multipleChoices=i((e,t,r,o)=>this.#e(300,e,t,r,o),"multipleChoices");static movedPermanently=i((e,t,r,o)=>this.#e(301,e,t,r,o),"movedPermanently");static found=i((e,t,r,o)=>this.#e(302,e,t,r,o),"found");static seeOther=i((e,t,r,o)=>this.#e(303,e,t,r,o),"seeOther");static notModified=i((e,t,r,o)=>this.#e(304,e,t,r,o),"notModified");static useProxy=i((e,t,r,o)=>this.#e(305,e,t,r,o),"useProxy");static switchProxy=i((e,t,r,o)=>this.#e(306,e,t,r,o),"switchProxy");static temporaryRedirect=i((e,t,r,o)=>this.#e(307,e,t,r,o),"temporaryRedirect");static permanentRedirect=i((e,t,r,o)=>this.#e(308,e,t,r,o),"permanentRedirect");static badRequest=i((e,t,r,o)=>this.#e(400,e,t,r,o),"badRequest");static unauthorized=i((e,t,r,o)=>this.#e(401,e,t,r,o),"unauthorized");static paymentRequired=i((e,t,r,o)=>this.#e(402,e,t,r,o),"paymentRequired");static forbidden=i((e,t,r,o)=>this.#e(403,e,t,r,o),"forbidden");static notFound=i((e,t,r,o)=>this.#e(404,e,t,r,o),"notFound");static methodNotAllowed=i((e,t,r,o)=>this.#e(405,e,t,r,o),"methodNotAllowed");static notAcceptable=i((e,t,r,o)=>this.#e(406,e,t,r,o),"notAcceptable");static proxyAuthenticationRequired=i((e,t,r,o)=>this.#e(407,e,t,r,o),"proxyAuthenticationRequired");static requestTimeout=i((e,t,r,o)=>this.#e(408,e,t,r,o),"requestTimeout");static conflict=i((e,t,r,o)=>this.#e(409,e,t,r,o),"conflict");static gone=i((e,t,r,o)=>this.#e(410,e,t,r,o),"gone");static lengthRequired=i((e,t,r,o)=>this.#e(411,e,t,r,o),"lengthRequired");static preconditionFailed=i((e,t,r,o)=>this.#e(412,e,t,r,o),"preconditionFailed");static contentTooLarge=i((e,t,r,o)=>this.#e(413,e,t,r,o),"contentTooLarge");static uriTooLong=i((e,t,r,o)=>this.#e(414,e,t,r,o),"uriTooLong");static unsupportedMediaType=i((e,t,r,o)=>this.#e(415,e,t,r,o),"unsupportedMediaType");static rangeNotSatisfiable=i((e,t,r,o)=>this.#e(416,e,t,r,o),"rangeNotSatisfiable");static expectationFailed=i((e,t,r,o)=>this.#e(417,e,t,r,o),"expectationFailed");static imATeapot=i((e,t,r,o)=>this.#e(418,e,t,r,o),"imATeapot");static misdirectedRequest=i((e,t,r,o)=>this.#e(421,e,t,r,o),"misdirectedRequest");static unprocessableContent=i((e,t,r,o)=>this.#e(422,e,t,r,o),"unprocessableContent");static locked=i((e,t,r,o)=>this.#e(423,e,t,r,o),"locked");static failedDependency=i((e,t,r,o)=>this.#e(424,e,t,r,o),"failedDependency");static tooEarly=i((e,t,r,o)=>this.#e(425,e,t,r,o),"tooEarly");static upgradeRequired=i((e,t,r,o)=>this.#e(426,e,t,r,o),"upgradeRequired");static preconditionRequired=i((e,t,r,o)=>this.#e(428,e,t,r,o),"preconditionRequired");static tooManyRequests=i((e,t,r,o)=>this.#e(429,e,t,r,o),"tooManyRequests");static requestHeaderFieldsTooLarge=i((e,t,r,o)=>this.#e(431,e,t,r,o),"requestHeaderFieldsTooLarge");static unavailableForLegalReasons=i((e,t,r,o)=>this.#e(451,e,t,r,o),"unavailableForLegalReasons");static internalServerError=i((e,t,r,o)=>this.#e(500,e,t,r,o),"internalServerError");static notImplemented=i((e,t,r,o)=>this.#e(501,e,t,r,o),"notImplemented");static badGateway=i((e,t,r,o)=>this.#e(502,e,t,r,o),"badGateway");static serviceUnavailable=i((e,t,r,o)=>this.#e(503,e,t,r,o),"serviceUnavailable");static gatewayTimeout=i((e,t,r,o)=>this.#e(504,e,t,r,o),"gatewayTimeout");static httpVersionNotSupported=i((e,t,r,o)=>this.#e(505,e,t,r,o),"httpVersionNotSupported");static variantAlsoNegotiates=i((e,t,r,o)=>this.#e(506,e,t,r,o),"variantAlsoNegotiates");static insufficientStorage=i((e,t,r,o)=>this.#e(507,e,t,r,o),"insufficientStorage");static loopDetected=i((e,t,r,o)=>this.#e(508,e,t,r,o),"loopDetected");static notExtended=i((e,t,r,o)=>this.#e(510,e,t,r,o),"notExtended");static networkAuthenticationRequired=i((e,t,r,o)=>this.#e(511,e,t,r,o),"networkAuthenticationRequired")};var ze=class extends je{static{i(this,"MetricsPlugin")}};var Q=class n{static{i(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let t=n.#e.get(e);if(!t){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new W(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var Y=class{static{i(this,"BatchDispatch")}constructor(e,t,r,o){this.#t=e,this.#i=t,this.#r=r,this.#n=o??console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=i(e=>{this.#o.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{t()})}},this.#i)}))},"enqueue");waitUntilFlushed=i(async()=>{if(this.#e)return this.#e},"waitUntilFlushed")};var dn=class{static{i(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=h.instance.loggingId,this.#e=e,this.#t=new Y("ellie-metrics-transport",10,this.dispatchFunction,Q.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=i(async e=>{if(e.length===0)return;let{remoteLogURL:t,deploymentName:r}=h.instance,{ACCOUNT_NAME:o,PROJECT_NAME:s}=h.instance.build,a=e.map(d=>{let p=Object.assign({},d);return delete p.requestContentLength,delete p.responseContentLength,p}),u=ss(),c={metadata:{timestamp:new Date,accountName:o,projectName:s,deploymentName:r},metrics:a,features:u},l=await Z.fetch(`${t}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(c),headers:{"content-type":"application/json","zp-dn":h.instance.deploymentName??"unknown","user-agent":h.instance.systemUserAgent}});if(!l.ok){let d=await l.text();Q.getLogger(this.#e).error(`Metrics POST responded ${l.status}: ${l.statusText}`,d),as(u)}},"dispatchFunction")};var ce=class{static{i(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:r,systemRouteName:o,corsPolicy:s="none"}){this.label=e,this.path=t,this.methods=r,this.corsPolicy=s,this.version=qt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},qt={name:"__system-no-version",pathPrefix:""};var we=i(async(n,e,t,r)=>{let o=new Date,s=Date.now(),a=await r(n),u=n.headers.get(et)??void 0,c=n.headers.get(Yi)??void 0,l=e.incomingRequestProperties,d;e.route instanceof ce&&(d=e.route.systemRouteName);let p=be.getContextExtensions(e).latestRequest,m={timestamp:o,statusCode:a.status,durationMs:Date.now()-s,requestContentLength:n.headers.get("content-length")?Number(n.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:n.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:h.instance.instanceId,userSub:p.user?.sub,clientIp:c},y=[];return y.push(new dn(e)),He.forEach(A=>{if(A instanceof ze){let P=A.getTransport();y.push(P)}}),y.forEach(A=>{A.pushMetrics(m,e)}),a},"metricsProcessor");var Or=i((n,e)=>{let t=i(async(s,a)=>{let c=new URL(s.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return x.notFound(s,a);let l=h.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,compatibilityDate:l.COMPATIBILITY_DATE,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.ENVIRONMENT_TYPE==="PRODUCTION"},p=s.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&Q.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new me({processors:[we],handler:t,gateway:e}),o=new ce({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var{toString:Au}=Object.prototype,{propertyIsEnumerable:ku}=Object.prototype;function Sr(n){return Au.call(n)}i(Sr,"toString");function xe(n){return typeof n=="string"}i(xe,"isString");function pt(n){return xe(n)&&n!==""}i(pt,"isNonEmptyString");function gs(n){return Sr(n)==="[object RegExp]"}i(gs,"isRegexp");function fs(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>ku.call(n,e))]}i(fs,"getOwnEnumerableKeys");function nt(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}i(nt,"isObject");function Ar(n){return typeof n=="number"&&!isNaN(n)}i(Ar,"isNumber");function kr(n){return n===!0||n===!1}i(kr,"isBoolean");function hs(n){return typeof n>"u"}i(hs,"isUndefined");function ys(n){return hs(n)||n===null}i(ys,"isUndefinedOrNull");function Ht(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(Ht,"isErrorLike");var bs=new Map;function Be(n){if(Array.isArray(n)&&!n.some(o=>typeof o!="number"))return n;if(typeof n!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(n))throw new Error("Malformed input string");let e=bs.get(n);if(e)return e;let t=n.split(","),r=[];for(let o of t){let s=o.split("-");if(s.length===2){let a=parseInt(s[0],10),u=parseInt(s[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return bs.set(n,r),r}i(Be,"statusCodesStringToNumberArray");function rt(n,e,t){if(!e.startsWith("."))throw new g(`Invalid ${t} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=n;return r.forEach(s=>{if(o===void 0)throw new S(`Error applying ${t} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i(rt,"getValueFromRequestUser");function ot(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new g("Received an array that contains non-string values.");return n}if(xe(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new g(`Expected type of string, received type '${typeof n}'`)}i(ot,"parseValueToStringArray");function ws(n){if(n==null)return[];if(!Array.isArray(n))throw new g(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!nt(t))throw new g(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!pt(t.name))throw new g("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!Ar(t.maxAge))throw new g(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!kr(t.allowCredentials))throw new g("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let r=Lr(t,"allowedHeaders"),o=Lr(t,"allowedMethods"),s=Lr(t,"exposeHeaders"),a;try{a=ot(t.allowedOrigins)}catch(c){throw new g(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:t.name,allowCredentials:typeof t.allowCredentials=="boolean"?String(t.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:r?r.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:s?s.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}i(ws,"parseCorsPolicies");function Lr(n,e){let t;if(n[e]!==void 0)try{t=ot(n[e])}catch(r){throw new g(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return t}i(Lr,"parseOptionalProperty");var pn=i((n,e)=>{if(e===null)return;if(n.find(a=>a==="*"))return e;let r=n.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),mn=i((n,e)=>{let t={"access-control-allow-origin":e};n.allowedHeaders&&(t["access-control-allow-headers"]=n.allowedHeaders),n.allowedMethods&&(t["access-control-allow-methods"]=n.allowedMethods),n.exposeHeaders&&(t["access-control-expose-headers"]=n.exposeHeaders);let r=n.allowCredentials;r&&(t["access-control-allow-credentials"]=r);let o=n.maxAge?.toString()??void 0;return o&&(t["access-control-max-age"]=o),t},"generateCorsHeaders");var _r=i((n,e)=>{let t=e.routeData.corsPolicies,r=i(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return x.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let m=n.lookup(l,c);if(!m)return x.notFound(a,u);let y=m.routeConfiguration,A=Lu(l,d,p,y,t);return A.isValid?new Response(void 0,{status:200,statusText:"OK",headers:A.headers}):(A.error&&u.log.warn(A.error),x.notFound(a,u))},"optionsHandler"),o=new me({processors:[we],handler:r,gateway:e}),s=new ce({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(s,o.execute)},"registerCorsRoute"),Lu=i((n,e,t,r,o)=>{let s={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":t,"access-control-allow-methods":n,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...s,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new g(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=pn(a.allowedOrigins,t);return u?{isValid:!0,headers:mn(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var Rs=i((n,e)=>{let t=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new me({processors:[we],handler:t,gateway:e}),o=new ce({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});n.addRoute(o,r.execute)},"registerNoRoutes");var Nr=new ce({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Ps=i((n,e)=>{let t=i(async(o,s)=>{let a=Nt.value?.notFoundHandler;if(a){let u=be.getContextExtensions(s);return a(o,s,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return x.notFound(o,s)},"notFoundHandler"),r=new me({processors:[we],handler:t,gateway:e});n.addRoute(Nr,r.execute)},"registerNotMatchedHandler");var _u=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Is=i(n=>{_u.forEach(e=>n.delete(e))},"stripCorsHeaders"),gn=i(async(n,e,t,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await r(n),p=new Headers(d.headers);return Is(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await r(n);if(!(s instanceof Response))throw new W(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=Nu(o,t.routeData.corsPolicies),u=Du(n,a),c=new Headers(s.headers);return Is(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(s.body,{status:s.status,statusText:s.statusText,headers:c,webSocket:s.webSocket})},"corsProcessor"),Nu=i((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(r=>r.name===n.corsPolicy);if(t===void 0)throw new g(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),Du=i((n,e)=>{let t=pn(e.allowedOrigins,n.headers.get("origin"));return t?mn(e,t):{}},"getCorsHeaders");var Dr=i((n,e)=>{let t=i(async()=>new Response(JSON.stringify({buildId:h.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new me({processors:[gn],handler:t,gateway:e}),o=new ce({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");import{SpanStatusCode as Es,trace as xs}from"@opentelemetry/api";var _e={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var fn=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!xe(t))throw new S(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},ae=class extends fn{static{i(this,"InboundPolicy")}},Ge=class extends fn{static{i(this,"OutboundPolicy")}};var Hr=class extends ae{static{i(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t){return this.#e(e,t,this.options,this.policyName)}},Ur=class extends Ge{static{i(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t,r){return this.#e(e,t,r,this.options,this.policyName)}},Mr=new Map;function Ut(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(s=>!Mr.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new g(`Invalid state - no Policy with the name '${s}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof ae)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new Hr(u,a.handler.options,a.name);else throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new g(`Invalid state - invalid handler on policy '${s}' on route '${r}' (typeof handler '${typeof c.handler}')`);Mr.set(a.name,c)}),t.map(s=>{let a=Mr.get(s);if(a===void 0)throw new S("Internal error. Policy not found in cache.");return a})}i(Ut,"getInboundPolicyInstances");var qr=new Map;function Zt(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.outbound??[],r=n.path),t.filter(s=>!qr.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new g(`Invalid state - no Policy with the name '${s}' on route '${r}' was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export],c;if(typeof u!="function")throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof Ge)c=new u(a.handler.options??{},a.name);else if(typeof u=="function")c=new Ur(u,a.handler.options??{},a.name);else throw new g(`Invalid state - invalid policy '${s}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new g(`Invalid state - invalid handler on policy '${s}' on route '${r}'`);qr.set(a.name,c)}),t.map(s=>{let a=qr.get(s);if(a===void 0)throw new S("Internal error. Policy not found in cache.");return a})}i(Zt,"getOutboundPolicyInstances");var Zr=i(n=>async(e,t)=>{let r=be.getContextExtensions(t),o=xs.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;let l=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{let p=await c.handler(u,t);if(p instanceof Request||p instanceof te||p instanceof Response)return d.end(),p;{let m=new g(`Invalid state - invalid handler on policy '${c.policyName}' on route '${t.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:Es.ERROR}),d.recordException(m),m}});if(l instanceof te)u=l;else if(l instanceof Request)u=new te(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),$r=i(n=>async(e,t,r)=>{let o=xs.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(_e.PolicyName,c.policyName),d.setAttribute(_e.PolicyType,c.policyType);let p=await c.handler(u,t,r);if(p instanceof Response)return p;{let m=new g(`Invalid state - invalid handler on policy '${c.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:Es.ERROR}),d.recordException(m),m}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),hn=i(async(n,e,t,r)=>{let o=Ut(e.route,t.routeData.policies),s=Zt(e.route,t.routeData.policies);return vs({request:n,context:e,inboundPolicies:o,outboundPolicies:s,gateway:t,next:r})},"policyProcessor");function Ts({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(r,o,s,a)=>vs({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(Ts,"createInternalPolicyProcessor");async function vs({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:s}){let a=Zr(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await s(u),l=$r(r),d;return h.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,n,e):d=c.ok?l(c,n,e):c,d}catch(u){return e.log.error(u),o.errorHandler(n,e,u)}}i(vs,"executePolicyProcessor");function Cs(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||Mu,s=0;for(;s<n.length;){let a=n.indexOf("=",s);if(a===-1)break;let u=n.indexOf(";",s);if(u===-1)u=n.length;else if(u<a){s=n.lastIndexOf(";",a-1)+1;continue}let c=n.slice(s,a).trim();if(t[c]===void 0){let l=n.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),t[c]=qu(l,o)}s=u+1}return t}i(Cs,"parse");function Mu(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}i(Mu,"decode");function qu(n,e){try{return e(n)}catch{return n}}i(qu,"tryDecode");function Os(n,e){try{let t=/v\d+(-\d+)?/g,o=Cs(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}i(Os,"devPortalBaseURL");var Ss="/__zuplo/dev-portal",Hu="dev-portal-id",Uu="dev-portal-host",Zu="zp-account",$u="zp-project",Fu="dev-portal-build",ju=`
36
36
  <!DOCTYPE html>
37
37
  <html lang="en">
38
38
  <head>
@@ -46,20 +46,20 @@ import{a as f,b as Ze,e as Pe,f as Ya,g as Bn,h as Gn,i as Xa,j as eu}from"./chu
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
- `,As=i((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=f.instance.deploymentName,o=f.instance.devPortalBaseUrl,s=i(async(c,l)=>{if(f.instance.isLocalDevelopment)return new Response(ju,{headers:{"content-type":"text/html"}});if(!r)return x.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=Ss(o,c.headers),h=new URL(`${d.pathname}${d.search}`,p),{headers:y,method:O,body:P}=c;return f.instance.build.ACCOUNT_NAME&&y.set(Zu,f.instance.build.ACCOUNT_NAME),f.instance.build.PROJECT_NAME&&y.set($u,f.instance.build.PROJECT_NAME),y.set(Uu,r),y.set(Hu,d.host),y.set(Fu,f.instance.build.BUILD_ID),await Z.fetch(h.toString(),{headers:y,method:O,body:P,redirect:"manual"})},"devPortalRoute"),a=new me({processors:[we,hn],handler:s,gateway:e}),u=new ce({label:"SYSTEM_API_DOCS_V3_ROUTE",methods:["GET","PUT","POST","DELETE","PATCH","HEAD"],path:`(${t}|/_next)(.*)`,systemRouteName:"developer-portal"});n.addRoute(u,a.execute)},"registerDevPortalV3Route"),ks=i((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=i(async a=>{let u=new URL(a.url);return u.pathname=`${t}${u.pathname.substring(Os.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new me({processors:[we],handler:r,gateway:e}),s=new ce({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${Os}(.*)`,systemRouteName:"developer-portal-legacy"});n.addRoute(s,o.execute)},"registerDevPortalLegacyRedirectRoute");var Fr=0,$t=class{static{i(this,"CoreLogger")}constructor(e,t,r,o,s){this.#n=t,this.#r=r??"local",this.#o=o,this.#i=s,this.#e(e)}#e=i(e=>{let t=["error","warn","info","debug"],r=!1,o=i(()=>{},"emptyFunction"),s=i((a,u)=>{this.#i.forEach(c=>{c.log(a,u)})},"pushFunction");t.forEach(a=>{this.#t[a]=r?o:s,a==e&&(r=!0)})},"#setupMethods");#t={};#n;#r;#o;#i;log(e,t,r,o,s,a){Fr>=Number.MAX_SAFE_INTEGER&&(Fr=0);let u={requestId:r,rayId:o,level:e,logSource:t,messages:s,timestamp:new Date,logOwner:this.#n,loggingId:this.#r,buildId:this.#o,vectorClock:Fr++};this.#t[e](u,a)}};var fe=class extends je{static{i(this,"LogPlugin")}};var yn=class{static{i(this,"LoggingContext")}constructor(e,t,r){this.#e=e,this.custom=t,this.originalRequest=r}#e;custom;originalRequest;waitUntil=i(e=>{this.#e.waitUntil(e)},"waitUntil")};var Ft=class{static{i(this,"RequestLogger")}constructor(e,t,r,o){this.#t=e,this.#n=t,this.#r=r,this.#o=o}#e="request";#t;#n;#r;#o;debug=i((...e)=>{this.#r.log("debug",this.#e,this.#t,this.#n,e,this.#o)},"debug");info=i((...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)},"info");log=i((...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)},"log");warn=i((...e)=>{this.#r.log("warn",this.#e,this.#t,this.#n,e,this.#o)},"warn");error=i((...e)=>{this.#r.log("error",this.#e,this.#t,this.#n,e,this.#o)},"error")};var zu=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(n=>[n.name,n]),Bu=new Map(zu);var Gu=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],jr=Symbol(".toJSON was called"),Vu=i(n=>{n[jr]=!0;let e=n.toJSON();return delete n[jr],e},"toJSON"),Wu=i(n=>Bu.get(n)??Error,"getErrorConstructor"),Ls=i(({from:n,seen:e,to:t,forceEnumerable:r,maxDepth:o,depth:s,useToJSON:a,serialize:u})=>{if(!t)if(Array.isArray(n))t=[];else if(!u&&Ut(n)){let l=Wu(n.name);t=new l}else t={};if(e.push(n),s>=o)return t;if(a&&typeof n.toJSON=="function"&&n[jr]!==!0)return Vu(n);let c=i(l=>Ls({from:l,seen:[...e],forceEnumerable:r,maxDepth:o,depth:s,useToJSON:a,serialize:u}),"continueDestroyCircular");for(let[l,d]of Object.entries(n)){if(typeof Buffer=="function"&&Buffer.isBuffer(d)){t[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){t[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){t[l]=d;continue}if(!e.includes(n[l])){s++,t[l]=c(n[l]);continue}t[l]="[Circular]"}}for(let{property:l,enumerable:d}of Gu)typeof n[l]<"u"&&n[l]!==null&&Object.defineProperty(t,l,{value:Ut(n[l])?c(n[l]):n[l],enumerable:r?!0:d,configurable:!0,writable:!0});return t},"destroyCircular");function Ie(n,e){let t=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof n=="object"&&n!==null?Ls({from:n,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:r,serialize:!0}):typeof n=="function"?`[Function: ${n.name??"anonymous"}]`:n}i(Ie,"serializeError");var Ku=/file:\/\/\/(.*?)\/dist\//g,Ju="at async Event.respondWith";function _s(n){return typeof n!="string"?n:n.split(`
49
+ `,As=i((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=h.instance.deploymentName,o=h.instance.devPortalBaseUrl,s=i(async(c,l)=>{if(h.instance.isLocalDevelopment)return new Response(ju,{headers:{"content-type":"text/html"}});if(!r)return x.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=Os(o,c.headers),m=new URL(`${d.pathname}${d.search}`,p),{headers:y,method:A,body:P}=c;return h.instance.build.ACCOUNT_NAME&&y.set(Zu,h.instance.build.ACCOUNT_NAME),h.instance.build.PROJECT_NAME&&y.set($u,h.instance.build.PROJECT_NAME),y.set(Hu,r),y.set(Uu,d.host),y.set(Fu,h.instance.build.BUILD_ID),await Z.fetch(m.toString(),{headers:y,method:A,body:P,redirect:"manual"})},"devPortalRoute"),a=new me({processors:[we,hn],handler:s,gateway:e}),u=new ce({label:"SYSTEM_API_DOCS_V3_ROUTE",methods:["GET","PUT","POST","DELETE","PATCH","HEAD"],path:`(${t}|/_next)(.*)`,systemRouteName:"developer-portal"});n.addRoute(u,a.execute)},"registerDevPortalV3Route"),ks=i((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=i(async a=>{let u=new URL(a.url);return u.pathname=`${t}${u.pathname.substring(Ss.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new me({processors:[we],handler:r,gateway:e}),s=new ce({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${Ss}(.*)`,systemRouteName:"developer-portal-legacy"});n.addRoute(s,o.execute)},"registerDevPortalLegacyRedirectRoute");var Fr=0,$t=class{static{i(this,"CoreLogger")}constructor(e,t,r,o,s){this.#n=t,this.#r=r??"local",this.#o=o,this.#i=s,this.#e(e)}#e=i(e=>{let t=["error","warn","info","debug"],r=!1,o=i(()=>{},"emptyFunction"),s=i((a,u)=>{this.#i.forEach(c=>{c.log(a,u)})},"pushFunction");t.forEach(a=>{this.#t[a]=r?o:s,a==e&&(r=!0)})},"#setupMethods");#t={};#n;#r;#o;#i;log(e,t,r,o,s,a){Fr>=Number.MAX_SAFE_INTEGER&&(Fr=0);let u={requestId:r,rayId:o,level:e,logSource:t,messages:s,timestamp:new Date,logOwner:this.#n,loggingId:this.#r,buildId:this.#o,vectorClock:Fr++};this.#t[e](u,a)}};var fe=class extends je{static{i(this,"LogPlugin")}};var yn=class{static{i(this,"LoggingContext")}constructor(e,t,r){this.#e=e,this.custom=t,this.originalRequest=r}#e;custom;originalRequest;waitUntil=i(e=>{this.#e.waitUntil(e)},"waitUntil")};var Ft=class{static{i(this,"RequestLogger")}constructor(e,t,r,o){this.#t=e,this.#n=t,this.#r=r,this.#o=o}#e="request";#t;#n;#r;#o;debug=i((...e)=>{this.#r.log("debug",this.#e,this.#t,this.#n,e,this.#o)},"debug");info=i((...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)},"info");log=i((...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)},"log");warn=i((...e)=>{this.#r.log("warn",this.#e,this.#t,this.#n,e,this.#o)},"warn");error=i((...e)=>{this.#r.log("error",this.#e,this.#t,this.#n,e,this.#o)},"error")};var zu=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(n=>[n.name,n]),Bu=new Map(zu);var Gu=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],jr=Symbol(".toJSON was called"),Vu=i(n=>{n[jr]=!0;let e=n.toJSON();return delete n[jr],e},"toJSON"),Wu=i(n=>Bu.get(n)??Error,"getErrorConstructor"),Ls=i(({from:n,seen:e,to:t,forceEnumerable:r,maxDepth:o,depth:s,useToJSON:a,serialize:u})=>{if(!t)if(Array.isArray(n))t=[];else if(!u&&Ht(n)){let l=Wu(n.name);t=new l}else t={};if(e.push(n),s>=o)return t;if(a&&typeof n.toJSON=="function"&&n[jr]!==!0)return Vu(n);let c=i(l=>Ls({from:l,seen:[...e],forceEnumerable:r,maxDepth:o,depth:s,useToJSON:a,serialize:u}),"continueDestroyCircular");for(let[l,d]of Object.entries(n)){if(typeof Buffer=="function"&&Buffer.isBuffer(d)){t[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){t[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){t[l]=d;continue}if(!e.includes(n[l])){s++,t[l]=c(n[l]);continue}t[l]="[Circular]"}}for(let{property:l,enumerable:d}of Gu)typeof n[l]<"u"&&n[l]!==null&&Object.defineProperty(t,l,{value:Ht(n[l])?c(n[l]):n[l],enumerable:r?!0:d,configurable:!0,writable:!0});return t},"destroyCircular");function Ie(n,e){let t=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof n=="object"&&n!==null?Ls({from:n,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:r,serialize:!0}):typeof n=="function"?`[Function: ${n.name??"anonymous"}]`:n}i(Ie,"serializeError");var Ku=/file:\/\/\/(.*?)\/dist\//g,Ju="at async Event.respondWith";function _s(n){return typeof n!="string"?n:n.split(`
50
50
  `).filter(e=>!e.trim().startsWith("at async file")).map((e,t)=>{let r=e.replaceAll(Ku,"").replaceAll(Ju,"").trim();return t===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
51
51
  `)}i(_s,"cleanStack");function bn(n,e,t=""){let r=[],o=e?.maxDepth??3;return i(function s(a,u={},c,l){let d=u.indent||" ",p;u.inlineCharacterLimit===void 0?p={newline:`
52
52
  `,newlineOrSpace:`
53
- `,pad:c,indent:c+d}:p={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let h=i(y=>{if(u.inlineCharacterLimit===void 0)return y;let O=y.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return O.length<=u.inlineCharacterLimit?O:y.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
54
- `).replace(new RegExp(p.pad,"g"),c).replace(new RegExp(p.indent,"g"),c+d)},"expandWhiteSpace");if(r.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||gs(a))return String(a);if(a instanceof Date)return`new Date('${a.toISOString()}')`;if(l>o)return"...";if(Array.isArray(a)){if(a.length===0)return"[]";r.push(a);let y="["+p.newline+a.map((O,P)=>{let v=a.length-1===P?p.newline:","+p.newlineOrSpace,N=s(O,u,c+d,l+1);return u.transform&&(N=u.transform(a,P,N)),p.indent+N+v}).join("")+p.pad+"]";return r.pop(),h(y)}if(nt(a)){let y=fs(a);if(u.filter&&(y=y.filter(P=>u.filter?.(a,P))),y.length===0)return"{}";r.push(a);let O="{"+p.newline+y.map((P,v)=>{let N=y.length-1===v?p.newline:","+p.newlineOrSpace,k=typeof P=="symbol",j=!k&&/^[a-z$_][$\w]*$/i.test(P),q=k||j?P:s(P,u,"",l+1),$=s(a[P],u,c+d,l+1);return u.transform&&($=u.transform(a,P,$)),p.indent+String(q)+": "+$+N}).join("")+p.pad+"}";return r.pop(),h(O)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,y=>y===`
55
- `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}i(bn,"stringifyObject");function Ve(n){return n.map(e=>Ie(e))}i(Ve,"makeErrorsSerializable");function mt(n){if(n.length===0)return"<no data provided to log>";let e=n[0];return typeof e=="string"?e:e instanceof Error?e.message:He(Ie(e))}i(mt,"extractBestMessage");function Ns(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(Ut(t))if(t.stack)e.push(t.stack);else{let r=bn(Ie(t));e.push(r)}else if(typeof t=="object"){let r=bn(t);e.push(r)}else{let r=zr(t);e.push(r)}}),e.join(`
56
- `)}i(Ns,"messagesToMultilineText");function He(n){return typeof n=="string"?n:JSON.stringify(n)}i(He,"stringifyNonString");function zr(n){return typeof n=="string"?n:n===null?"null":typeof n>"u"?"undefined":typeof n=="number"||typeof n=="boolean"||typeof n=="bigint"||typeof n=="symbol"?n.toString():typeof n=="function"?`[function ${n.name}]`:typeof n=="object"&&Array.isArray(n)?`[array ${n.length}]`:n instanceof Error?`${n.name??"Error"}: ${n.message??"unknown"}`:typeof n=="object"?Or(n):"unknown"}i(zr,"stringifyNonStringToText");import{importPKCS8 as Qu,SignJWT as Yu}from"jose";async function ye(n,e,t){for(let r=0;r<=n.retries;r++){let o=Z.fetch(e,t);if(r===n.retries)return o;let s=await o;if(s.status<500&&s.status!==429)return s;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,r)))}throw new m("An unknown error occurred, ensure retries is not negative")}i(ye,"fetchRetry");async function Ne({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=n;return await new Yu(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(Ne,"getTokenFromGcpServiceAccount");async function Ds(n,e,t){if(!n.startsWith("projects/"))throw new m(`The provided audience is invalid: ${n}. It must start with 'projects/'.`);return Br("https://sts.googleapis.com/v1/token",{audience:`//iam.googleapis.com/${n}`,grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token_type:"urn:ietf:params:oauth:token-type:jwt",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,scope:"https://www.googleapis.com/auth/cloud-platform"},t)}i(Ds,"exchangeIDTokenForGcpWorkloadToken");async function Ms({serviceAccountEmailOrIdentifier:n,audience:e,accessToken:t},r){let o={audience:e,includeEmail:!0};return Us(`https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${encodeURIComponent(n)}:generateIdToken`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},redirect:"follow",body:JSON.stringify(o)},r)}i(Ms,"generateServiceAccountIDToken");async function qs(n,e,t){return Br(n,{token:e,returnSecureToken:!0},t)}i(qs,"exchangeFirebaseJwtForIdToken");async function wn(n,e,t){return Br(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(wn,"exchangeGgpJwtForIdToken");async function Br(n,e,t){let r={method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)};return Us(n,r,t)}i(Br,"fetchTokenFromBody");async function Us(n,e,t){let r=await ye(t,n,e);if(r.status!==200){let s;try{let a=await r.text(),u=JSON.parse(a);s={cause:u.error_description??u.error??u}}catch{}throw new A({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(Us,"fetchToken");var Te=class n{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),r=await Qu(t.private_key.trim(),"RS256");return new n({serviceAccount:t,privateKey:r})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};async function le(n){if(n.level==="error"&&console.error(n.messages),!f.instance.remoteLogURL||!f.instance.loggingId||!f.instance.remoteLogToken){console.warn("Remote logger is not configured. Skipping log entry.");return}try{let e={logOwner:"user",logSource:"runtime",rayId:null,requestId:`global-${crypto.randomUUID()}`,timestamp:new Date,buildId:f.instance.build.BUILD_ID,loggingId:f.instance.loggingId,...n,vectorClock:0};await Hs({loggingUrl:f.instance.remoteLogURL,loggingId:f.instance.loggingId,loggingToken:f.instance.remoteLogToken},[e])}catch(e){console.error(e)}}i(le,"sendRemoteGlobalLog");async function Hs({loggingUrl:n,loggingId:e,loggingToken:t},r){try{await Z.fetch(`${n}/publish/${e}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:r.map(o=>({...o,messages:Ve(o.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${t}`,"user-agent":f.instance.systemUserAgent,"zp-dn":f.instance.deploymentName??"unknown"}})}catch(o){console.error(o)}}i(Hs,"sendRemoteLogs");var Xu=i(({url:n,remoteLogToken:e,loggingId:t,sendOnlyErrors:r})=>async o=>{let s;r===!0?s=o.filter(a=>a.level==="error"):s=o,s.length!==0&&await Hs({loggingUrl:n,loggingId:t,loggingToken:e},s)},"dispatchFunction"),Rn,Pn=class{static{i(this,"RemoteLogTransport")}constructor(e){Rn||(Rn=new Y("remote-log-transport",1,Xu(e)))}log(e,t){Rn.enqueue(e),t.waitUntil(Rn.waitUntilFlushed())}};var Gr=class extends fe{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new jt(this.options)}},ec="https://logging.googleapis.com/v2/entries:write?alt=json",Vr={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},jt=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=f.instance.loggingEnvironmentType,this.#i=f.instance.loggingEnvironmentStage,this.#r=f.instance.deploymentName,g("logging.google-cloud")}#e;#t;#n;#r;#o;#i;async init(){this.#t=await Te.init(this.#e)}log(e,t){if(!this.#t)throw new W("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:Ve(e.messages)},o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:Vr[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(s.labels.rayId=e.rayId);let a=mt(r.allMessages);s.jsonPayload={...r,message:a},this.batcher.enqueue(s),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length===0)return;this.#t||(this.#t=await Te.init(this.#e));let t=await Ne({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"});try{let r=await Z.fetch(ec,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});if(!r.ok){let o="";try{o=await r.text()}catch{}await le({level:"error",messages:[`Failed to send logs to Google: ${r.status} - ${r.statusText}`,o]})}}catch{await le({level:"error",messages:["Failed to connect to Google logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new Y("google-log-transport",1,this.dispatchFunction)};var In="gcp";function En(n){let e={allMessages:Ve(n.messages)},t="zuplo-production",r=mt(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:Vr[n.level],timestamp:n.timestamp,"logging.googleapis.com/labels":{buildId:n.buildId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${n.requestId}`,allMessages:e.allMessages};return n.rayId&&(o["logging.googleapis.com/labels"].rayId=n.rayId),o}i(En,"gcpLogFormat");var zt=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===In){if(e.messages.length===0)return;this.#e[e.level].apply(null,[En(e)])}else this.#e.log(JSON.stringify(e))}};var Qr=class extends fe{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new Bt(this.options)}},Wr="__ddtags",Kr="__ddattr",Jr=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),tc=i(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(Jr(r)):t.push(`${Jr(r)}:${Jr(o.toString())}`)}),t.join(",")},"formatTags"),Bt=class{static{i(this,"DataDogTransport")}constructor(e){g("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=f.instance.loggingEnvironmentType,this.#o=f.instance.loggingEnvironmentStage,this.#n=f.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[Wr];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(y=>y[Wr]!==void 0);a>-1&&(Object.assign(r,s[a][Wr]),s.splice(a,1));let u={},c=t.custom[Kr];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(y=>y[Kr]!==void 0);l>-1&&(Object.assign(u,s[l][Kr]),s.splice(l,1));let d=Ve(s),h={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:mt(d),service:e.loggingId,ddtags:tc(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(h,u),this.batcher.enqueue(h),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let t=await Z.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!t.ok){let r="";try{r=await t.text()}catch{}await le({level:"error",messages:[`Failed to send logs to DataDog: ${t.status} - ${t.statusText}`,r]})}}catch{await le({level:"error",messages:["Failed to connect to DataDog logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new Y("data-dog-transport",10,this.dispatchFunction)};var Gt=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===In){if(e.messages.length===0)return;this.#e[e.level].apply(null,[En(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 nc={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},Zs=i((n,e)=>t=>{let r={};return r.deploymentName=n,r.labels={requestId:t.requestId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},r.rayId=t.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=t.vectorClock,{timestamp:t.timestamp,observerdTimestamp:t.timestamp,traceId:t.requestId,severityText:t.level,severityNumber:nc[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var rc=i(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let s=Zs(t,r);try{await Z.fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":f.instance.systemUserAgent,"zp-dn":f.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),xn,Tn=class{static{i(this,"UnifiedLogTransport")}constructor(e){xn||(xn=new Y("unified-log-transport",1,rc(e)))}async log(e,t){xn.enqueue(e),t.waitUntil(xn.waitUntilFlushed())}};var Yr=he("zuplo:logging"),vn=class n{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(f.instance,e),r=await n.setupUserCoreLogger(f.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;Yr("Gateway.setupSystemCoreLogger");let o=[],s=t.getService(on);return s?o.push(new Gt(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new zt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Tn({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new $t(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){Yr("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=t.getService(on);if(a&&a.captureUserLogs===!0?r.push(new Gt(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new zt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new Pn({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:!e.isWorkingCopy})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&(g("logging.google.legacy-initialization"),r.push(new jt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME}))),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){g("logging.datadog.legacy-initialization");let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new Bt({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return Ue.forEach(u=>{u instanceof fe&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new $t(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,t,r,o,s){Yr("Gateway.createRequestLoggers");let a=new yn(r,o,s),u=new Ft(e,t,this.systemCoreLogger,a);return{userRequestLogger:new Ft(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var it=class{static{i(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};var Xr=class{static{i(this,"RouterEntry")}constructor(e,t,r,o){this.fullPath=e,this.urlPattern=t,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},Vt=class{static{i(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},eo=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}},Wt=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof it||e instanceof ce))throw new W("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(s=>s.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let s=new URLPattern({pathname:o}),a=new Xr(o,s,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new eo(`addRoute-error: Invalid path '${o}'. '${s.message}'`,{cause:s})}}lookup(e,t){if(typeof e>"u")throw new m(`Invalid request - Method was undefined. Path: '${t}'`);let r=this.routeEntries.filter(o=>o.config.methods.includes(e));if(r.length!==0)for(let o=0;o<r.length;o++){let s=r[o],u=s.urlPattern.exec({pathname:t});if(u!==null)return new Vt(s.config,s.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],a=o.urlPattern.exec({pathname:e});if(a!==null){let u=new Vt(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var to;function $s(n){to=n}i($s,"setGlobalZuploEventContext");function Cn(){if(to===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return to}i(Cn,"getGlobalZuploEventContext");function Fs({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);es.includes(o.toLowerCase())&&!ts.includes(r.toLowerCase())&&t.delete(r)}t.delete($i)}else Xi.forEach(r=>{t.delete(r)});return t}i(Fs,"normalizeIncomingRequestHeaders");var De=he("zuplo:runtime"),ic=i(n=>{let e=n.findIndex(t=>t.name===qt.name);return e>-1?[...n.splice(e),qt]:[...n,qt]},"setupSystemNoVersion"),ge=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;De("Gateway.constructor"),_e,this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(De("Gateway.initialize"),!n.#e){let s=await vn.init(r),a=await e(),u={...a,corsPolicies:ws(a.corsPolicies)},c=new n(u,t,s,o);n.#e=c}if(!n.#e)throw new W("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){De("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new W("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[hn,gn,we];#o;setupRoutes=i(()=>{De("Gateway.setupRoutes");let e=this.routeData,t=ic(e.versions),r=new Wt(t);if(e.routes.length===0)return Sr(r,this),Dr(r,this),_r(r,this),Rs(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(ks(r,this),As(r,this)),Sr(r,this),Dr(r,this),_r(r,this);for(let s of Ue)s instanceof qe&&s.registerRoutes(r,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new m(`Invalid state - No handler on route for path '${s.path}'`);let u=new me({processors:this.#r,handler:a,gateway:this}),c=new it(s);r.addRoute(c,u.execute)}),Ps(r,this),r},"setupRoutes");setupErrorHandler=i(()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new m("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=i((t,r,o)=>this.#i(t,r,o),"errorHandler");return e},"setupErrorHandler");errorHandler(e,t,r){try{return this.#o(e,t,r)}catch(o){return De("An error occurred in the user's errorHandler",o),this.#i(e,t,o)}}#i(e,t,r){De("Gateway.internalErrorResponse");let o={};if(f.instance.isLocalDevelopment||f.instance.isWorkingCopy){if(r instanceof A&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let s=Ie(r.cause);"stack"in s&&(s.stack=_s(s.stack)),o={cause:s}}}return x.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t,r){let{requestId:o,rayId:s}=t;$s(r);let a=Fs({headers:e.headers,removeAllVendorHeadersExceptListed:f.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(Xe,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let j=new Headers(u.headers);j.set(ir,"true"),u=new Request(u,{headers:j,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(o,s,r,c,u),p=new URL(u.url),h=p.pathname,y=this.#n.lookup(u.method,h);if(!y)throw new W(`Invalid state - no route match - should have been picked up by the not found handler, path: '${h}'`);let O=new Sn(e.headers),P=new te(u,{params:y.params}),v=new On({logger:l,route:y.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:O}),N=y.routeConfiguration.raw();oc.getActiveSpan()?.setAttributes({"http.route":v.route.path??v.route.pathPattern,"cloud.region":v.incomingRequestProperties.colo,[_e.RoutePathPattern]:v.route.pathPattern,[_e.RouteOperationId]:N.operationId,[_e.RouteTrace]:N["x-zuplo-trace"],[_e.RouteSystem]:dt(p)?!0:void 0});let k=be.initialize(v,P);if(y.routeConfiguration===Nr&&Nt.value?.notFoundHandler!==void 0){let j=this.#n.lookupByPathOnly(h);k.pathOnlyMatches=j.map(q=>q.routeConfiguration).filter(q=>q instanceof it)}try{if(Q.addLogger(v,d),f.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!dt(p):!p.pathname.startsWith("/__zuplo")){let E=await cs(P,v);if(E instanceof Response)return E;{let U=be.getContextExtensions(v);P=E,U.latestRequest=P}}dt(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:y.routeConfiguration.path});let j=y.executableHandler;sc(j,y,u),De("Gateway.handleRequest - call user handler");let q=await j(P,v);if(De("Gateway.handleRequest - user handler"),!(q instanceof Response))throw new A(`Invalid Response type from the request handler: ${typeof q}`);if(q.bodyUsed)throw new A("The response object has already been used. Return a new response instead.");let $;if(q.headers.get(Xe)===null&&!q.webSocket){let E=new Headers(q.headers);E.set(Xe,o),$=new Response(q.body,{status:q.status,statusText:q.statusText,headers:E,cf:q.cf})}else $=q;return $}catch(j){return De("Gateway - error executing handler",j),j instanceof A?(l.error(j),d.warn(j)):d.error(j),await this.#i(P,v,j)}}};function sc(n,e,t){if(De("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new m(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new m(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}i(sc,"checkHandler");var js=i(async(n,e,t)=>{let r=ge.instance.routeData.policies,o=Ht([n],r);if(o.length===0)throw new A(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy"),zs=i(async(n,e,t,r)=>{let o=ge.instance.routeData.policies,s=Zt([n],o);if(s.length===0)throw new A(`Invalid 'invokeOutboundPolicy call' - no policy '${n}' found.`);return s[0].handler(e,t,r)},"invokeOutboundPolicy");var Sn=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(dr);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(pr)??void 0}get city(){return this.#e.get(sr)??this.#e.get(Vi)??void 0}get continent(){return this.#e.get(ar)??this.#e.get(Wi)??void 0}get country(){return this.#e.get(ur)??this.#e.get(Ki)??void 0}get latitude(){return this.#e.get(lr)??this.#e.get(Qi)??void 0}get longitude(){return this.#e.get(cr)??this.#e.get(Ji)??void 0}get colo(){return this.#e.get(mr)??void 0}get postalCode(){return this.#e.get(Bi)??this.#e.get(gr)??void 0}get metroCode(){return this.#e.get(zi)??this.#e.get(fr)??void 0}get region(){return this.#e.get(Fi)??this.#e.get(hr)??void 0}get regionCode(){return this.#e.get(ji)??this.#e.get(yr)??void 0}get timezone(){return this.#e.get(Gi)??this.#e.get(br)??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}}},Dt=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},Mt=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},be=class n{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let r=new n(t);return n.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=n.#e.get(e);if(!t)throw new A(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=i(async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)},"onResponseSendingFinal");onResponseSending=i(async(e,t,r)=>{let o=e;for(let s of this.#n)o=await s(e,t,r);return o},"onResponseSending")},On=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=s,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>js(u,c,this),this.invokeOutboundPolicy=(u,c,l)=>zs(u,c,l,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{be.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{be.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;invokeOutboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=i(s=>{try{typeof t=="function"?t(s):t.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};import{AsyncLocalStorage as ac}from"node:async_hooks";var Bs={request:new ac};var uc="Error initializing gateway. Check your configuration for errors or contact support.",cc="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",no=class{constructor(e,t,r,o,s,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=i(async(e,t,r)=>{let o=e.headers.get(Xe)??e.headers.get(Zi)??crypto.randomUUID(),s=e.headers.get(et),a={requestId:o,rayId:s};return Bs.request.run(a,async()=>{f.initialize({build:this.buildEnvironment,runtime:t});try{await ps(this.runtimeInit)}catch(c){this.handleError(c,cc,e)}return os(i(async(c,l)=>{let d;try{d=await ge.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,uc,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,r)})},"requestHandler");handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof m&&(t=e.message);let o={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:t,instance:r.url,trace:{timestamp:Date.now(),rayId:r.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:f.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};function lc(n){for(var e=[],t=0;t<n.length;){var r=n[t];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:t,value:n[t++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:n[t++]});continue}if(r==="{"){e.push({type:"OPEN",index:t,value:n[t++]});continue}if(r==="}"){e.push({type:"CLOSE",index:t,value:n[t++]});continue}if(r===":"){for(var o="",s=t+1;s<n.length;){var a=n.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=n[s++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:o}),t=s;continue}if(r==="("){var u=1,c="",s=t+1;if(n[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<n.length;){if(n[s]==="\\"){c+=n[s++]+n[s++];continue}if(n[s]===")"){if(u--,u===0){s++;break}}else if(n[s]==="("&&(u++,n[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));c+=n[s++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(t));if(!c)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:c}),t=s;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}i(lc,"lexer");function ro(n,e){e===void 0&&(e={});for(var t=lc(n),r=e.prefixes,o=r===void 0?"./":r,s="[^".concat(pc(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=i(function(E){if(c<t.length&&t[c].type===E)return t[c++].value},"tryConsume"),p=i(function(E){var U=d(E);if(U!==void 0)return U;var G=t[c],V=G.type,C=G.index;throw new TypeError("Unexpected ".concat(V," at ").concat(C,", expected ").concat(E))},"mustConsume"),h=i(function(){for(var E="",U;U=d("CHAR")||d("ESCAPED_CHAR");)E+=U;return E},"consumeText");c<t.length;){var y=d("CHAR"),O=d("NAME"),P=d("PATTERN");if(O||P){var v=y||"";o.indexOf(v)===-1&&(l+=v,v=""),l&&(a.push(l),l=""),a.push({name:O||u++,prefix:v,suffix:"",pattern:P||s,modifier:d("MODIFIER")||""});continue}var N=y||d("ESCAPED_CHAR");if(N){l+=N;continue}l&&(a.push(l),l="");var k=d("OPEN");if(k){var v=h(),j=d("NAME")||"",q=d("PATTERN")||"",$=h();p("CLOSE"),a.push({name:j||(q?u++:""),pattern:j&&!q?s:q,prefix:v,suffix:$,modifier:d("MODIFIER")||""});continue}p("END")}return a}i(ro,"parse");function Gs(n,e){return dc(ro(n,e),e)}i(Gs,"compile");function dc(n,e){e===void 0&&(e={});var t=mc(e),r=e.encode,o=r===void 0?function(c){return c}:r,s=e.validate,a=s===void 0?!0:s,u=n.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var h=c?c[p.name]:void 0,y=p.modifier==="?"||p.modifier==="*",O=p.modifier==="*"||p.modifier==="+";if(Array.isArray(h)){if(!O)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(h.length===0){if(y)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var P=0;P<h.length;P++){var v=o(h[P],p);if(a&&!u[d].test(v))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(v,'"'));l+=p.prefix+v+p.suffix}continue}if(typeof h=="string"||typeof h=="number"){var v=o(String(h),p);if(a&&!u[d].test(v))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(v,'"'));l+=p.prefix+v+p.suffix;continue}if(!y){var N=O?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(N))}}return l}}i(dc,"tokensToFunction");function pc(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(pc,"escapeString");function mc(n){return n&&n.sensitive?"":"i"}i(mc,"flags");var gc=he("zuplo:runtime"),io=new TextEncoder,Vs={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"},fc=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],gt=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:o,region:s,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=r,this.service=o,this.region=s,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,t){let r=new so(Object.assign({url:e},t,this,t&&t.aws)),o=Object.assign({},t,await r.sign());return delete o.aws,{url:o.url.toString(),request:o}}async fetch(e,t){gc("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,t),a=Z.fetch(o,s);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new m("An unknown error occurred, ensure retries is not negative")}},so=class{static{i(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:r,body:o,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:h,appendSessionToken:y,allHeaders:O,singleEncode:P}){if(t==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let v,N;(!c||!l)&&([v,N]=hc(this.url,this.headers)),this.service=c||v||"",this.region=l||N||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=h,this.appendSessionToken=y||this.service==="iotdevicegateway",this.headers.delete("Host");let k=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),k.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&k.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(q=>O||!fc.includes(q)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(q=>q+":"+(q==="host"?this.url.host:(this.headers.get(q)||"").replace(/\s+/g," "))).join(`
57
- `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!k.has("X-Amz-Expires")&&k.set("X-Amz-Expires","86400"),k.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),k.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),k.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");P||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=Ks(this.encodedPath);let j=new Set;this.encodedSearch=[...this.url.searchParams].filter(([q])=>{if(!q)return!1;if(this.service==="s3"){if(j.has(q))return!1;j.add(q)}return!0}).map(q=>q.map($=>Ks(encodeURIComponent($)))).sort(([q,$],[E,U])=>q<E?-1:q>E?1:$<U?-1:$>U?1:0).map(q=>q.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),t=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(t);if(!r){let o=await Kt("AWS4"+this.secretAccessKey,e),s=await Kt(o,this.region),a=await Kt(s,this.service);r=await Kt(a,"aws4_request"),this.cache.set(t,r)}return oo(await Kt(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,oo(await Ws(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 m=i(y=>{if(u.inlineCharacterLimit===void 0)return y;let A=y.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return A.length<=u.inlineCharacterLimit?A:y.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
54
+ `).replace(new RegExp(p.pad,"g"),c).replace(new RegExp(p.indent,"g"),c+d)},"expandWhiteSpace");if(r.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||gs(a))return String(a);if(a instanceof Date)return`new Date('${a.toISOString()}')`;if(l>o)return"...";if(Array.isArray(a)){if(a.length===0)return"[]";r.push(a);let y="["+p.newline+a.map((A,P)=>{let v=a.length-1===P?p.newline:","+p.newlineOrSpace,N=s(A,u,c+d,l+1);return u.transform&&(N=u.transform(a,P,N)),p.indent+N+v}).join("")+p.pad+"]";return r.pop(),m(y)}if(nt(a)){let y=fs(a);if(u.filter&&(y=y.filter(P=>u.filter?.(a,P))),y.length===0)return"{}";r.push(a);let A="{"+p.newline+y.map((P,v)=>{let N=y.length-1===v?p.newline:","+p.newlineOrSpace,k=typeof P=="symbol",j=!k&&/^[a-z$_][$\w]*$/i.test(P),q=k||j?P:s(P,u,"",l+1),$=s(a[P],u,c+d,l+1);return u.transform&&($=u.transform(a,P,$)),p.indent+String(q)+": "+$+N}).join("")+p.pad+"}";return r.pop(),m(A)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,y=>y===`
55
+ `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}i(bn,"stringifyObject");function Ve(n){return n.map(e=>Ie(e))}i(Ve,"makeErrorsSerializable");function mt(n){if(n.length===0)return"<no data provided to log>";let e=n[0];return typeof e=="string"?e:e instanceof Error?e.message:Ue(Ie(e))}i(mt,"extractBestMessage");function Ns(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(Ht(t))if(t.stack)e.push(t.stack);else{let r=bn(Ie(t));e.push(r)}else if(typeof t=="object"){let r=bn(t);e.push(r)}else{let r=zr(t);e.push(r)}}),e.join(`
56
+ `)}i(Ns,"messagesToMultilineText");function Ue(n){return typeof n=="string"?n:JSON.stringify(n)}i(Ue,"stringifyNonString");function zr(n){return typeof n=="string"?n:n===null?"null":typeof n>"u"?"undefined":typeof n=="number"||typeof n=="boolean"||typeof n=="bigint"||typeof n=="symbol"?n.toString():typeof n=="function"?`[function ${n.name}]`:typeof n=="object"&&Array.isArray(n)?`[array ${n.length}]`:n instanceof Error?`${n.name??"Error"}: ${n.message??"unknown"}`:typeof n=="object"?Sr(n):"unknown"}i(zr,"stringifyNonStringToText");import{importPKCS8 as Qu,SignJWT as Yu}from"jose";async function ye(n,e,t){for(let r=0;r<=n.retries;r++){let o=Z.fetch(e,t);if(r===n.retries)return o;let s=await o;if(s.status<500&&s.status!==429)return s;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,r)))}throw new g("An unknown error occurred, ensure retries is not negative")}i(ye,"fetchRetry");async function Ne({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=n;return await new Yu(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(Ne,"getTokenFromGcpServiceAccount");async function Ds(n,e,t){if(!n.startsWith("projects/"))throw new g(`The provided audience is invalid: ${n}. It must start with 'projects/'.`);return Br("https://sts.googleapis.com/v1/token",{audience:`//iam.googleapis.com/${n}`,grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token_type:"urn:ietf:params:oauth:token-type:jwt",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,scope:"https://www.googleapis.com/auth/cloud-platform"},t)}i(Ds,"exchangeIDTokenForGcpWorkloadToken");async function Ms({serviceAccountEmailOrIdentifier:n,audience:e,accessToken:t},r){let o={audience:e,includeEmail:!0};return Hs(`https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${encodeURIComponent(n)}:generateIdToken`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},redirect:"follow",body:JSON.stringify(o)},r)}i(Ms,"generateServiceAccountIDToken");async function qs(n,e,t){return Br(n,{token:e,returnSecureToken:!0},t)}i(qs,"exchangeFirebaseJwtForIdToken");async function wn(n,e,t){return Br(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(wn,"exchangeGgpJwtForIdToken");async function Br(n,e,t){let r={method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)};return Hs(n,r,t)}i(Br,"fetchTokenFromBody");async function Hs(n,e,t){let r=await ye(t,n,e);if(r.status!==200){let s;try{let a=await r.text(),u=JSON.parse(a);s={cause:u.error_description??u.error??u}}catch{}throw new S({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i(Hs,"fetchToken");var Te=class n{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),r=await Qu(t.private_key.trim(),"RS256");return new n({serviceAccount:t,privateKey:r})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};async function le(n){if(n.level==="error"&&console.error(n.messages),!h.instance.remoteLogURL||!h.instance.loggingId||!h.instance.remoteLogToken){console.warn("Remote logger is not configured. Skipping log entry.");return}try{let e={logOwner:"user",logSource:"runtime",rayId:null,requestId:`global-${crypto.randomUUID()}`,timestamp:new Date,buildId:h.instance.build.BUILD_ID,loggingId:h.instance.loggingId,...n,vectorClock:0};await Us({loggingUrl:h.instance.remoteLogURL,loggingId:h.instance.loggingId,loggingToken:h.instance.remoteLogToken},[e])}catch(e){console.error(e)}}i(le,"sendRemoteGlobalLog");async function Us({loggingUrl:n,loggingId:e,loggingToken:t},r){try{await Z.fetch(`${n}/publish/${e}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:r.map(o=>({...o,messages:Ve(o.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${t}`,"user-agent":h.instance.systemUserAgent,"zp-dn":h.instance.deploymentName??"unknown"}})}catch(o){console.error(o)}}i(Us,"sendRemoteLogs");var Xu=i(({url:n,remoteLogToken:e,loggingId:t,sendOnlyErrors:r})=>async o=>{let s;r===!0?s=o.filter(a=>a.level==="error"):s=o,s.length!==0&&await Us({loggingUrl:n,loggingId:t,loggingToken:e},s)},"dispatchFunction"),Rn,Pn=class{static{i(this,"RemoteLogTransport")}constructor(e){Rn||(Rn=new Y("remote-log-transport",1,Xu(e)))}log(e,t){Rn.enqueue(e),t.waitUntil(Rn.waitUntilFlushed())}};var Gr=class extends fe{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new jt(this.options)}},ec="https://logging.googleapis.com/v2/entries:write?alt=json",Vr={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},jt=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=h.instance.loggingEnvironmentType,this.#i=h.instance.loggingEnvironmentStage,this.#r=h.instance.deploymentName,f("logging.google-cloud")}#e;#t;#n;#r;#o;#i;async init(){this.#t=await Te.init(this.#e)}log(e,t){if(!this.#t)throw new W("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:Ve(e.messages)},o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:Vr[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(s.labels.rayId=e.rayId);let a=mt(r.allMessages);s.jsonPayload={...r,message:a},this.batcher.enqueue(s),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length===0)return;this.#t||(this.#t=await Te.init(this.#e));let t=await Ne({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"});try{let r=await Z.fetch(ec,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});if(!r.ok){let o="";try{o=await r.text()}catch{}await le({level:"error",messages:[`Failed to send logs to Google: ${r.status} - ${r.statusText}`,o]})}}catch{await le({level:"error",messages:["Failed to connect to Google logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new Y("google-log-transport",1,this.dispatchFunction)};var In="gcp";function En(n){let e={allMessages:Ve(n.messages)},t="zuplo-production",r=mt(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:Vr[n.level],timestamp:n.timestamp,"logging.googleapis.com/labels":{buildId:n.buildId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${n.requestId}`,allMessages:e.allMessages};return n.rayId&&(o["logging.googleapis.com/labels"].rayId=n.rayId),o}i(En,"gcpLogFormat");var zt=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===In){if(e.messages.length===0)return;this.#e[e.level].apply(null,[En(e)])}else this.#e.log(JSON.stringify(e))}};var Qr=class extends fe{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new Bt(this.options)}},Wr="__ddtags",Kr="__ddattr",Jr=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),tc=i(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(Jr(r)):t.push(`${Jr(r)}:${Jr(o.toString())}`)}),t.join(",")},"formatTags"),Bt=class{static{i(this,"DataDogTransport")}constructor(e){f("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=h.instance.loggingEnvironmentType,this.#o=h.instance.loggingEnvironmentStage,this.#n=h.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[Wr];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(y=>y[Wr]!==void 0);a>-1&&(Object.assign(r,s[a][Wr]),s.splice(a,1));let u={},c=t.custom[Kr];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(y=>y[Kr]!==void 0);l>-1&&(Object.assign(u,s[l][Kr]),s.splice(l,1));let d=Ve(s),m={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:mt(d),service:e.loggingId,ddtags:tc(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(m,u),this.batcher.enqueue(m),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let t=await Z.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!t.ok){let r="";try{r=await t.text()}catch{}await le({level:"error",messages:[`Failed to send logs to DataDog: ${t.status} - ${t.statusText}`,r]})}}catch{await le({level:"error",messages:["Failed to connect to DataDog logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new Y("data-dog-transport",10,this.dispatchFunction)};var Gt=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===In){if(e.messages.length===0)return;this.#e[e.level].apply(null,[En(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 nc={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},Zs=i((n,e)=>t=>{let r={};return r.deploymentName=n,r.labels={requestId:t.requestId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},r.rayId=t.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=t.vectorClock,{timestamp:t.timestamp,observerdTimestamp:t.timestamp,traceId:t.requestId,severityText:t.level,severityNumber:nc[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var rc=i(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let s=Zs(t,r);try{await Z.fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":h.instance.systemUserAgent,"zp-dn":h.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),xn,Tn=class{static{i(this,"UnifiedLogTransport")}constructor(e){xn||(xn=new Y("unified-log-transport",1,rc(e)))}async log(e,t){xn.enqueue(e),t.waitUntil(xn.waitUntilFlushed())}};var Yr=he("zuplo:logging"),vn=class n{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(h.instance,e),r=await n.setupUserCoreLogger(h.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;Yr("Gateway.setupSystemCoreLogger");let o=[],s=t.getService(on);return s?o.push(new Gt(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new zt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Tn({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new $t(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){Yr("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=t.getService(on);if(a&&a.captureUserLogs===!0?r.push(new Gt(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new zt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new Pn({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:!e.isWorkingCopy})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&(f("logging.google.legacy-initialization"),r.push(new jt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME}))),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){f("logging.datadog.legacy-initialization");let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new Bt({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return He.forEach(u=>{u instanceof fe&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new $t(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,t,r,o,s){Yr("Gateway.createRequestLoggers");let a=new yn(r,o,s),u=new Ft(e,t,this.systemCoreLogger,a);return{userRequestLogger:new Ft(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var it=class{static{i(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};var Xr=class{static{i(this,"RouterEntry")}constructor(e,t,r,o){this.fullPath=e,this.urlPattern=t,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},Vt=class{static{i(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},eo=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}},Wt=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof it||e instanceof ce))throw new W("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(s=>s.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let s=new URLPattern({pathname:o}),a=new Xr(o,s,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new eo(`addRoute-error: Invalid path '${o}'. '${s.message}'`,{cause:s})}}lookup(e,t){if(typeof e>"u")throw new g(`Invalid request - Method was undefined. Path: '${t}'`);let r=this.routeEntries.filter(o=>o.config.methods.includes(e));if(r.length!==0)for(let o=0;o<r.length;o++){let s=r[o],u=s.urlPattern.exec({pathname:t});if(u!==null)return new Vt(s.config,s.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],a=o.urlPattern.exec({pathname:e});if(a!==null){let u=new Vt(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var to;function $s(n){to=n}i($s,"setGlobalZuploEventContext");function Cn(){if(to===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return to}i(Cn,"getGlobalZuploEventContext");function Fs({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);es.includes(o.toLowerCase())&&!ts.includes(r.toLowerCase())&&t.delete(r)}t.delete($i)}else Xi.forEach(r=>{t.delete(r)});return t}i(Fs,"normalizeIncomingRequestHeaders");var De=he("zuplo:runtime"),ic=i(n=>{let e=n.findIndex(t=>t.name===qt.name);return e>-1?[...n.splice(e),qt]:[...n,qt]},"setupSystemNoVersion"),ge=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;De("Gateway.constructor"),_e,this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(De("Gateway.initialize"),!n.#e){let s=await vn.init(r),a=await e(),u={...a,corsPolicies:ws(a.corsPolicies)},c=new n(u,t,s,o);n.#e=c}if(!n.#e)throw new W("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){De("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new W("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[hn,gn,we];#o;setupRoutes=i(()=>{De("Gateway.setupRoutes");let e=this.routeData,t=ic(e.versions),r=new Wt(t);if(e.routes.length===0)return Or(r,this),Dr(r,this),_r(r,this),Rs(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(ks(r,this),As(r,this)),Or(r,this),Dr(r,this),_r(r,this);for(let s of He)s instanceof qe&&s.registerRoutes(r,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new g(`Invalid state - No handler on route for path '${s.path}'`);let u=new me({processors:this.#r,handler:a,gateway:this}),c=new it(s);r.addRoute(c,u.execute)}),Ps(r,this),r},"setupRoutes");setupErrorHandler=i(()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new g("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=i((t,r,o)=>this.#i(t,r,o),"errorHandler");return e},"setupErrorHandler");errorHandler(e,t,r){try{return this.#o(e,t,r)}catch(o){return De("An error occurred in the user's errorHandler",o),this.#i(e,t,o)}}#i(e,t,r){De("Gateway.internalErrorResponse");let o={};if(h.instance.isLocalDevelopment||h.instance.isWorkingCopy){if(r instanceof S&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let s=Ie(r.cause);"stack"in s&&(s.stack=_s(s.stack)),o={cause:s}}}return x.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t,r){let{requestId:o,rayId:s}=t;$s(r);let a=Fs({headers:e.headers,removeAllVendorHeadersExceptListed:h.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(Xe,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let j=new Headers(u.headers);j.set(ir,"true"),u=new Request(u,{headers:j,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(o,s,r,c,u),p=new URL(u.url),m=p.pathname,y=this.#n.lookup(u.method,m);if(!y)throw new W(`Invalid state - no route match - should have been picked up by the not found handler, path: '${m}'`);let A=new On(e.headers),P=new te(u,{params:y.params}),v=new Sn({logger:l,route:y.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:A}),N=y.routeConfiguration.raw();oc.getActiveSpan()?.setAttributes({"http.route":v.route.path??v.route.pathPattern,"cloud.region":v.incomingRequestProperties.colo,[_e.RoutePathPattern]:v.route.pathPattern,[_e.RouteOperationId]:N.operationId,[_e.RouteTrace]:N["x-zuplo-trace"],[_e.RouteSystem]:dt(p)?!0:void 0});let k=be.initialize(v,P);if(y.routeConfiguration===Nr&&Nt.value?.notFoundHandler!==void 0){let j=this.#n.lookupByPathOnly(m);k.pathOnlyMatches=j.map(q=>q.routeConfiguration).filter(q=>q instanceof it)}try{if(Q.addLogger(v,d),h.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!dt(p):!p.pathname.startsWith("/__zuplo")){let E=await cs(P,v);if(E instanceof Response)return E;{let H=be.getContextExtensions(v);P=E,H.latestRequest=P}}dt(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:y.routeConfiguration.path});let j=y.executableHandler;sc(j,y,u),De("Gateway.handleRequest - call user handler");let q=await j(P,v);if(De("Gateway.handleRequest - user handler"),!(q instanceof Response))throw new S(`Invalid Response type from the request handler: ${typeof q}`);if(q.bodyUsed)throw new S("The response object has already been used. Return a new response instead.");let $;if(q.headers.get(Xe)===null&&!q.webSocket){let E=new Headers(q.headers);E.set(Xe,o),$=new Response(q.body,{status:q.status,statusText:q.statusText,headers:E,cf:q.cf})}else $=q;return $}catch(j){return De("Gateway - error executing handler",j),j instanceof S?(l.error(j),d.warn(j)):d.error(j),await this.#i(P,v,j)}}};function sc(n,e,t){if(De("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new g(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new g(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}i(sc,"checkHandler");var js=i(async(n,e,t)=>{let r=ge.instance.routeData.policies,o=Ut([n],r);if(o.length===0)throw new S(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy"),zs=i(async(n,e,t,r)=>{let o=ge.instance.routeData.policies,s=Zt([n],o);if(s.length===0)throw new S(`Invalid 'invokeOutboundPolicy call' - no policy '${n}' found.`);return s[0].handler(e,t,r)},"invokeOutboundPolicy");var On=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(dr);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(pr)??void 0}get city(){return this.#e.get(sr)??this.#e.get(Vi)??void 0}get continent(){return this.#e.get(ar)??this.#e.get(Wi)??void 0}get country(){return this.#e.get(ur)??this.#e.get(Ki)??void 0}get latitude(){return this.#e.get(lr)??this.#e.get(Qi)??void 0}get longitude(){return this.#e.get(cr)??this.#e.get(Ji)??void 0}get colo(){return this.#e.get(mr)??void 0}get postalCode(){return this.#e.get(Bi)??this.#e.get(gr)??void 0}get metroCode(){return this.#e.get(zi)??this.#e.get(fr)??void 0}get region(){return this.#e.get(Fi)??this.#e.get(hr)??void 0}get regionCode(){return this.#e.get(ji)??this.#e.get(yr)??void 0}get timezone(){return this.#e.get(Gi)??this.#e.get(br)??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}}},Dt=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},Mt=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},be=class n{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let r=new n(t);return n.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=n.#e.get(e);if(!t)throw new S(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=i(async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)},"onResponseSendingFinal");onResponseSending=i(async(e,t,r)=>{let o=e;for(let s of this.#n)o=await s(e,t,r);return o},"onResponseSending")},Sn=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=s,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>js(u,c,this),this.invokeOutboundPolicy=(u,c,l)=>zs(u,c,l,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{be.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{be.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;invokeOutboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=i(s=>{try{typeof t=="function"?t(s):t.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};import{AsyncLocalStorage as ac}from"node:async_hooks";var Bs={request:new ac};var uc="Error initializing gateway. Check your configuration for errors or contact support.",cc="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",no=class{constructor(e,t,r,o,s,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=i(async(e,t,r)=>{let o=e.headers.get(Xe)??e.headers.get(Zi)??crypto.randomUUID(),s=e.headers.get(et),a={requestId:o,rayId:s};return Bs.request.run(a,async()=>{h.initialize({build:this.buildEnvironment,runtime:t});try{await ps(this.runtimeInit)}catch(c){this.handleError(c,cc,e)}return os(i(async(c,l)=>{let d;try{d=await ge.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,uc,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,r)})},"requestHandler");handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof g&&(t=e.message);let o={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:t,instance:r.url,trace:{timestamp:Date.now(),rayId:r.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:h.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};function lc(n){for(var e=[],t=0;t<n.length;){var r=n[t];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:t,value:n[t++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:n[t++]});continue}if(r==="{"){e.push({type:"OPEN",index:t,value:n[t++]});continue}if(r==="}"){e.push({type:"CLOSE",index:t,value:n[t++]});continue}if(r===":"){for(var o="",s=t+1;s<n.length;){var a=n.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=n[s++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:o}),t=s;continue}if(r==="("){var u=1,c="",s=t+1;if(n[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<n.length;){if(n[s]==="\\"){c+=n[s++]+n[s++];continue}if(n[s]===")"){if(u--,u===0){s++;break}}else if(n[s]==="("&&(u++,n[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));c+=n[s++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(t));if(!c)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:c}),t=s;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}i(lc,"lexer");function ro(n,e){e===void 0&&(e={});for(var t=lc(n),r=e.prefixes,o=r===void 0?"./":r,s="[^".concat(pc(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=i(function(E){if(c<t.length&&t[c].type===E)return t[c++].value},"tryConsume"),p=i(function(E){var H=d(E);if(H!==void 0)return H;var G=t[c],V=G.type,C=G.index;throw new TypeError("Unexpected ".concat(V," at ").concat(C,", expected ").concat(E))},"mustConsume"),m=i(function(){for(var E="",H;H=d("CHAR")||d("ESCAPED_CHAR");)E+=H;return E},"consumeText");c<t.length;){var y=d("CHAR"),A=d("NAME"),P=d("PATTERN");if(A||P){var v=y||"";o.indexOf(v)===-1&&(l+=v,v=""),l&&(a.push(l),l=""),a.push({name:A||u++,prefix:v,suffix:"",pattern:P||s,modifier:d("MODIFIER")||""});continue}var N=y||d("ESCAPED_CHAR");if(N){l+=N;continue}l&&(a.push(l),l="");var k=d("OPEN");if(k){var v=m(),j=d("NAME")||"",q=d("PATTERN")||"",$=m();p("CLOSE"),a.push({name:j||(q?u++:""),pattern:j&&!q?s:q,prefix:v,suffix:$,modifier:d("MODIFIER")||""});continue}p("END")}return a}i(ro,"parse");function Gs(n,e){return dc(ro(n,e),e)}i(Gs,"compile");function dc(n,e){e===void 0&&(e={});var t=mc(e),r=e.encode,o=r===void 0?function(c){return c}:r,s=e.validate,a=s===void 0?!0:s,u=n.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var m=c?c[p.name]:void 0,y=p.modifier==="?"||p.modifier==="*",A=p.modifier==="*"||p.modifier==="+";if(Array.isArray(m)){if(!A)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(m.length===0){if(y)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var P=0;P<m.length;P++){var v=o(m[P],p);if(a&&!u[d].test(v))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(v,'"'));l+=p.prefix+v+p.suffix}continue}if(typeof m=="string"||typeof m=="number"){var v=o(String(m),p);if(a&&!u[d].test(v))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(v,'"'));l+=p.prefix+v+p.suffix;continue}if(!y){var N=A?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(N))}}return l}}i(dc,"tokensToFunction");function pc(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(pc,"escapeString");function mc(n){return n&&n.sensitive?"":"i"}i(mc,"flags");var gc=he("zuplo:runtime"),io=new TextEncoder,Vs={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"},fc=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],gt=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:o,region:s,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=r,this.service=o,this.region=s,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,t){let r=new so(Object.assign({url:e},t,this,t&&t.aws)),o=Object.assign({},t,await r.sign());return delete o.aws,{url:o.url.toString(),request:o}}async fetch(e,t){gc("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,t),a=Z.fetch(o,s);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new g("An unknown error occurred, ensure retries is not negative")}},so=class{static{i(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:r,body:o,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:m,appendSessionToken:y,allHeaders:A,singleEncode:P}){if(t==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let v,N;(!c||!l)&&([v,N]=hc(this.url,this.headers)),this.service=c||v||"",this.region=l||N||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=y||this.service==="iotdevicegateway",this.headers.delete("Host");let k=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),k.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&k.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(q=>A||!fc.includes(q)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(q=>q+":"+(q==="host"?this.url.host:(this.headers.get(q)||"").replace(/\s+/g," "))).join(`
57
+ `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!k.has("X-Amz-Expires")&&k.set("X-Amz-Expires","86400"),k.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),k.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),k.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");P||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=Ks(this.encodedPath);let j=new Set;this.encodedSearch=[...this.url.searchParams].filter(([q])=>{if(!q)return!1;if(this.service==="s3"){if(j.has(q))return!1;j.add(q)}return!0}).map(q=>q.map($=>Ks(encodeURIComponent($)))).sort(([q,$],[E,H])=>q<E?-1:q>E?1:$<H?-1:$>H?1:0).map(q=>q.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),t=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(t);if(!r){let o=await Kt("AWS4"+this.secretAccessKey,e),s=await Kt(o,this.region),a=await Kt(s,this.service);r=await Kt(a,"aws4_request"),this.cache.set(t,r)}return oo(await Kt(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,oo(await Ws(await this.canonicalString()))].join(`
58
58
  `)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
59
59
  `,this.signedHeaders,await this.hexBodyHash()].join(`
60
- `)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new A("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=oo(await Ws(this.body||""))}return e}};async function Kt(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?io.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,io.encode(e))}i(Kt,"hmac");async function Ws(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?io.encode(n):n)}i(Ws,"hash");function oo(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}i(oo,"buf2hex");function Ks(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(Ks,"encodeRfc3986");function hc(n,e){let{hostname:t,pathname:r}=n,o=t.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[s,a]=(o||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",s="s3";else if(s==="iot")t.startsWith("iot.")?s="execute-api":t.startsWith("data.jobs.iot.")?s="iot-jobs-data":s=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(s==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?s="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(s="autoscaling-plans")}else a==null&&s.startsWith("s3-")?(a=s.slice(3).replace(/^fips-|^external-1/,""),s="s3"):s.endsWith("-fips")?s=s.slice(0,-5):a&&/-\d$/.test(s)&&!/-\d$/.test(a)&&([s,a]=[a,s]);return s in Vs?[Vs[s],a]:[s,a]}i(hc,"guessServiceRegion");function yc(n){return n>64&&n<91?n-65:n>96&&n<123?n-71:n>47&&n<58?n+4:n===43?62:n===47?63:0}i(yc,"b64ToUint6");function Js(n,e){let t=n.replace(/[^A-Za-z0-9+/]/g,""),r=t.length,o=e?Math.ceil((r*3+1>>2)/e)*e:r*3+1>>2,s=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=yc(t.charCodeAt(d))<<6*(3-u),u===3||r-d===1){for(a=0;a<3&&l<o;)s[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return s}i(Js,"base64Decode");function An(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}i(An,"uint6ToB64");function Qs(n){let e=2,t="",r=n.length,o=0;for(let s=0;s<r;s++)e=s%3,o|=n[s]<<(16>>>e&24),(e===2||n.length-s===1)&&(t+=String.fromCodePoint(An(o>>>18&63),An(o>>>12&63),An(o>>>6&63),An(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}i(Qs,"base64Encode");function ft(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}i(ft,"numberToString");function bc(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=ft(Math.floor(t/60)),s=ft(t%60);return`${r}${o}${s}`}i(bc,"getCLFOffset");function ao(n=new Date){if(!(n instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],t=ft(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),s=ft(n.getHours()),a=ft(n.getMinutes()),u=ft(n.getSeconds()),c=bc(n);return`${t}/${r}/${o}:${s}:${a}:${u} ${c}`}i(ao,"toCLFDate");var Ys=he("zuplo:runtime"),wc="X-Amzn-Trace-Id",Rc="x-amzn-errortype",Xs=[],Pc=i(async(n,e,t)=>{let r=t;for await(let o of Xs)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),ve=class extends A{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(wc)??void 0,this.errorType=t.get(Rc)??void 0}},Ic={addSendingAwsLambdaEventHook:i(n=>{Xs.push(n)},"addSendingAwsLambdaEventHook")};async function Ec(n,e){g("handler.aws-lambda");let{accessKeyId:t,secretAccessKey:r,region:o,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!t)throw new m("awsAccessKeyId is not set in the handler options");if(!r)throw new m("secretAccessKey is not set in the handler options");if(!o)throw new m("region is not set in the handler options");if(!s)throw new m("functionName is not set in the handler options");let l=new gt({accessKeyId:t,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(Ys(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,h]=await Cc(n,{binaryMediaTypes:c}),{options:y}=e.route.handler,O;y&&typeof y=="object"&&"payloadFormatVersion"in y&&y.payloadFormatVersion==="2.0"?O=vc(n,e):O=await Tc(n,e,{useAwsResourcePathStyle:u}),Ys("Calling onSendingAwsLambdaEvent hook");let P=await Pc(n,e,O);P.body=p,P.isBase64Encoded=h;let v=await l.fetch(d,{body:JSON.stringify(P)});try{return xc(v)}catch(N){if(N instanceof ve){let k=y&&typeof y=="object"&&"returnAmazonTraceIdHeader"in y&&y.returnAmazonTraceIdHeader&&N.traceId?{AMZN_TRACE_ID_HEADER:N.traceId}:void 0;return x.internalServerError(n,e,void 0,k)}throw N}}i(Ec,"awsLambdaHandler");async function xc(n){let e;try{e=await n.json()}catch{throw new ve("Lambda response did not contain valid JSON",n.headers)}if(n.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new ve(e.message,n.headers):new ve(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new ve(e.errorMessage,n.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:n.status,headers:{"content-type":"application/json"}});let t=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new ve(`Response headers must be an object. Received ${typeof e.headers}`,n.headers);for(let[o,s]of Object.entries(e.headers))t.set(o,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new ve(`Response cookies must be an array. Received ${typeof e.cookies}`,n.headers);t.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new ve(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,n.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new ve("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new ve("Response was set to base64 encoded but body was not a string",n.headers);r=Js(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 ve(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,n.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:t,status:e.statusCode})}i(xc,"getResponse");async function Tc(n,e,{useAwsResourcePathStyle:t}){let r={},o={};n.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let s=n.query,a={};for(let[l,d]of Object.entries(s))a[l]=[d];let u=new URL(n.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:n.method,headers:r,multiValueHeaders:o,queryStringParameters:s,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:n.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:n.headers.get("CF-Connecting-IP"),user:null,userAgent:n.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:ao(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Oc(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}i(Tc,"buildEventVersion1");function vc(n,e){let t={};n.headers.forEach((s,a)=>{t[a]=s});let r=new URL(n.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:t,queryStringParameters:n.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:r.hostname,domainPrefix:null,http:{method:n.method,path:r.pathname,protocol:"HTTP/1.1",sourceIp:n.headers.get("CF-Connecting-IP"),userAgent:n.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:ao(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}i(vc,"buildEventVersion2");async function Cc(n,{binaryMediaTypes:e}){let t,r=!1,o=n.headers.get("content-type");if(n.method==="GET"||n.method==="HEAD")t=null;else if(e&&o&&Sc(e,o)){let s=await n.arrayBuffer();t=Qs(new Uint8Array(s)),r=!0}else t=await n.clone().text();return[t,r]}i(Cc,"getBodyResult");function Sc(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}i(Sc,"matchesContentType");function Oc(n,e=!1){if(!e)return n;let t=ro(n),r=Gs(n),o={};return t.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),r(o)}i(Oc,"getResourcePath");var Ac=[502,503,504];async function ht(n,e){if(Ac.includes(n.status)){let t=Q.getLogger(e),o=await n.clone().text(),s={};for(let[a,u]of n.headers)s[a]=u;t.warn(`BadGatewayResponse ${n.status}`,{status:n.status,statusText:n.statusText,body:o,headers:s})}}i(ht,"logBadGatewayResponses");var uo;function We(n){if(uo===void 0){let t=f.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),uo=t}return n.log[uo]}i(We,"getHandlerUserLogFunction");async function kc(n,e){g("handler.open-api");let t=f.instance.build.BUILD_ID,{buildAssetsUrl:r}=f.instance,o=e.route.handler.options,{openApiFilePath:s}=o;if(!s)throw new m("Open API Spec Handler must have 'openApiFilePath' specified");let a=Lc(s);if(!a.isValid)throw new m(a.error);let u;f.instance.isLocalDevelopment?u=`${r}/${s.substring(1)}`:u=`${r}/${t}${s.substring(1)}`;let c=await Z.fetch(u,{method:n.method,body:n.body,headers:n.headers});if(c.status!==200)return x.notFound(n,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return ht(l,e),l}i(kc,"openApiSpecHandler");var Lc=i(n=>n.startsWith("./")?n.startsWith("./config")?n.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function _c(n,e){g("handler.redirect");let t=e.route.handler.options;if(!t.location)throw new m("Redirect Handler must have 'location' specified");let r=t.status??302;return new Response(null,{status:r,headers:{location:t.location}})}i(_c,"redirectHandler");function Nc(n,e){let t=n.endsWith("/"),r=e.startsWith("/");return t&&r?`${n.substring(0,n.length-1)}${e}`:!t&&!r?`${n}/${e}`:`${n}${e}`}i(Nc,"join");async function Dc(n,e){g("handler.url-forward");let t=We(e),r=e.route.handler.options,o=r.forwardSearch!==!1;if(!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new m("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(n.url),u=r.__rewriteFunction(n,s),c=Nc(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();t(`URL Forwarding to '${l}'`);let p=await Z.fetch(l,{method:n.method,body:n.body,headers:n.headers}),h=Date.now()-d;return t(`URL Forward received response ${p.status} - ${p.statusText} in ${h}ms`),ht(p,e),p}i(Dc,"urlForwardHandler");var Mc=i((n,e)=>{let t=new URL(n),r=new URL(e);for(let[o,s]of r.searchParams.entries())t.searchParams.append(o,s);return t.toString()},"addQuery");async function qc(n,e){g("handler.url-rewrite");let t=We(e),r=e.route.handler.options,o=r.forwardSearch!==!1,s=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new m("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(n,a),c=o?Mc(u,n.url):u,l=Date.now();t(`URL Rewriting to '${c}'`);let d=await Z.fetch(c.toString(),{method:n.method,body:n.body,headers:n.headers,redirect:s?"follow":"manual"}),p=Date.now()-l;return t(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),ht(d,e),d}i(qc,"urlRewriteHandler");async function Uc(n,e){g("handler.websocket");let t=e.route.handler.options,r=We(e);if(!t||!t.rewritePattern)throw new m("WebSocket Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return x.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new m("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await Z.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let d=await c.text(),p=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${d}'`;throw new Error(p)}let l=Date.now()-u;return r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${l}ms`),new Response(null,{status:101,webSocket:c.webSocket})}i(Uc,"webSocketHandler");var co=i((n,e)=>n.map((r,o)=>{let s;if(typeof r.module=="object"&&(s=r.module[r.export]),!s||typeof s!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${o+1}, export name: ${r.export}`;throw new m(`${a} - Websocket policy must be a valid function (${u})`)}return s}),"getWebSocketPolicyFunctions"),ea=i(async(n,e,t,r,o,s)=>{let a=n.data;if(s&&s.length>0){let u=[...s];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,t,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function ta(n,e,t,r,o){n.addEventListener("close",()=>{e.close()}),n.addEventListener("error",s=>{r.log.error("WebSocket error: ",s),e.send(JSON.stringify(s))}),n.addEventListener("message",s=>{try{let u=i(async c=>{let l=await ea(c,n,e,t,r,o);l!==void 0&&e.send(l)},"innerPipeline")(s).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}i(ta,"wireUpListeners");async function Hc(n,e){g("handler.websocket-pipeline");let t=e.route.handler.options,r=We(e);if(!t||!t.rewritePattern)throw new m("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return x.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new m("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await Z.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let v=await c.text(),N=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${v}'`;throw new Error(N)}let l=new WebSocketPair,[d,p]=Object.values(l),h=Date.now()-u;r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${h}ms`);let y=c.webSocket;y.accept(),p.accept();let O=t.policies&&t.policies.inbound?co(t.policies.inbound,"inbound"):[],P=t.policies&&t.policies.outbound?co(t.policies.outbound,"outbound"):[];return ta(p,y,n,e,O),ta(y,p,n,e,P),new Response(null,{status:101,webSocket:d})}i(Hc,"webSocketPipelineHandler");var lo=class extends fe{constructor(t){super();this.options=t}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new po(this.options)}},po=class{static{i(this,"DynaTraceTransport")}constructor(e){g("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#r=f.instance.loggingEnvironmentType,this.#o=f.instance.loggingEnvironmentStage,this.#n=f.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:He(Ie(r)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#i=i(async e=>{if(e.length!==0)try{let t=await Z.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}});if(!t.ok){let r="";try{r=await t.text()}catch{}await le({level:"error",messages:[`Failed to send logs to Dynatrace: ${t.status} - ${t.statusText}`,r]})}}catch{await le({level:"error",messages:["Failed to connect to Dynatrace logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new Y("dyna-trace-log-transport",10,this.#i)};var mo=class extends fe{constructor(t){super();this.options=t}static{i(this,"LokiLoggingPlugin")}getTransport(){return new fo(this.options)}},go=class{static{i(this,"LokiStream")}constructor(e,t,r,o,s,a){this.level=e,this.environment=t,this.environmentType=r,this.environmentStage=o,this.requestId=a,this.job=s}job;level;environment;environmentType;environmentStage;requestId;equals=i(e=>this.level===e.level&&this.requestId===e.requestId,"equals")};function Zc(n,e){return btoa(`${n}:${e}`)}i(Zc,"createBasicDigest");var fo=class{static{i(this,"LokiTransport")}constructor(e){g("logging.loki"),this.#n=e.url,this.#r=Zc(e.username,e.password),this.#i=f.instance.loggingEnvironmentType,this.#s=f.instance.loggingEnvironmentStage,this.#o=f.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo"}#e;#t;#n;#r;#o;#i;#s;log(e,t){let r=new go(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(o=>{let s={stream:r,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:He(Ie(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(s)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=i(e=>{let t={streams:[]};return e.forEach(r=>{let o=t.streams.find(s=>s.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},t.streams.push(o)),o.values.push(this.#e>1?[r.nanoSecondEpoch,r.message,{requestId:r.requestId,rayId:r.rayId,atomicCounter:JSON.stringify(r.atomicCounter)}]:[r.nanoSecondEpoch,r.message])}),t},"#convertToLokiStreamsBatch");#u=i(async e=>{if(e.length===0)return;let t=this.#a(e);try{let r=await Z.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}});if(!r.ok){let o="";try{o=await r.text()}catch{}await le({level:"error",messages:[`Failed to send logs to Loki: ${r.status} - ${r.statusText}`,o]})}}catch{await le({level:"error",messages:["Failed to connect to Loki logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new Y("loki-log-transport",10,this.#u)};var ho=class extends fe{constructor(t){super();this.options=t}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new yo(this.options)}},yo=class{static{i(this,"SumoLogicTransport")}constructor(e){g("logging.sumologic"),this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=f.instance.loggingEnvironmentType,this.#r=f.instance.loggingEnvironmentStage,this.#t=f.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:He(Ie(r)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#s=i(async e=>{if(e.length===0)return;let t=e.map(o=>JSON.stringify(o)).join(`
61
- `),r=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&r.set("X-Sumo-Name",this.#i),this.#o&&r.set("X-Sumo-Category",this.#o);try{let o=await Z.fetch(this.#e,{method:"POST",body:t,headers:r});if(!o.ok){let s="";try{s=await o.text()}catch{}await le({level:"error",messages:[`Failed to send logs to Sumologic: ${o.status} - ${o.statusText}`,s]})}}catch{await le({level:"error",messages:["Failed to connect to Sumologic logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new Y("sumo-logic-log-transport",10,this.#s)};var $c="d3a5b78f823648f5b1df4fe269d41172",bo=class extends fe{constructor(t){super();this.options=t}static{i(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new wo(this.options)}},wo=class{static{i(this,"VMWareLogInsightTransport")}constructor(e){g("logging.vmware-loginsight");let t;try{t=new URL(e.url),t.pathname==="/"&&(t.pathname=`/api/v1/events/ingest/${e.agentId??$c}`)}catch{throw new m(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=t.toString(),this.#r=f.instance.loggingEnvironmentType,this.#o=f.instance.loggingEnvironmentStage,this.#n=f.instance.deploymentName,this.#i=e.onMessageSending,this.#t=e.textReplacements,e.fields&&(this.#s=Object.entries(e.fields).map(([r,o])=>({name:r,content:o})))}#e;#t;#n;#r;#o;#i;#s;log(e,t){let r=this.buildEntry(e,t);this.batcher.enqueue(r),t.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,t){let r=Ns(e.messages);this.#t?.forEach(s=>{r=r.replaceAll(s[0],s[1])});let o={timestamp:Date.now(),text:r,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#r},{name:"environment_stage",content:this.#o},{name:"log_source",content:e.logSource},{name:"atomic_counter",content:e.vectorClock}]};return e.rayId&&o.fields.push({name:"request_ray_id",content:e.rayId}),this.#n&&o.fields.push({name:"environment",content:this.#n}),this.#s&&o.fields.push(...this.#s),t.custom&&Object.entries(t.custom).forEach(([s,a])=>{let u=zr(a);u&&o.fields.push({name:s,content:u})}),this.#i&&(o=this.#i(o)),o}#a=i(async e=>{if(e.length!==0)try{let t=await Z.fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});if(!t.ok){let r="";try{r=await t.text()}catch{}await le({level:"error",messages:[`Failed to send logs to Log Insight: ${t.status} - ${t.statusText}`,r]})}}catch{await le({level:"error",messages:["Failed to connect to Log Insight logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new Y("vmware-log-insights-log-transport",10,this.#a)};var Ro=class extends fe{constructor(t){super();this.options=t}static{i(this,"AWSLoggingPlugin")}getTransport(){return new Po(this.options)}},Po=class{static{i(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new Y("aws-log-transport",10,async e=>{if(e.length===0)return;let t=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});try{let r=await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:t,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}});if(!r.ok){let o="";try{o=await r.text()}catch{}await le({level:"error",messages:[`Failed to send logs to AWS: ${r.status} - ${r.statusText}`,o]})}}catch{await le({level:"error",messages:["Failed to connect to AWS logging service. Check that the URL is correct."]})}});constructor({accessKeyId:e,logStreamName:t,logGroupName:r,secretAccessKey:o,region:s}){g("logging.aws"),this.awsClient=new gt({accessKeyId:e,secretAccessKey:o,service:"logs",region:s}),this.logGroupName=r,this.logStreamName=t,this.region=s,this.environmentType=f.instance.loggingEnvironmentType,this.environment=f.instance.deploymentName}log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:He(Ie(r)),severity:e.level,source:e.logSource,environment:this.environment,requestId:e.requestId,environmentType:this.environmentType,rayId:e.rayId===null?void 0:e.rayId})};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}};var Io=new WeakMap,Fc={tags:[]},Eo=class extends ze{constructor(t){super();this.options=t;g("metrics.datadog")}static{i(this,"DataDogMetricsPlugin")}getTransport(){return new xo(this.options)}static setContext(t,r){let o=Io.get(t);o||(o=Fc);let s=Object.assign({...o},r);Io.set(t,s)}},xo=class{static{i(this,"DataDogMetricsTransport")}#e;#t;#n;#r;#o;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://api.datadoghq.com/api/v2/series",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.#r=e.tags??[]}pushMetrics(e,t){this.#i===void 0&&(this.#i=new Y("data-dog-metrics-transport",10,this.dispatchFunction,Q.getLogger(t)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(Io.get(t)?.tags??[]);if(this.#o.country&&o.push(`country:${e.country}`),this.#o.httpMethod&&o.push(`httpMethod:${e.method}`),this.#o.statusCode&&o.push(`statusCode:${e.statusCode}`),this.#o.path){let s=e.systemRouteName||e.routePath;o.push(`path:${s}`)}this.#n.latency&&this.#i.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:r,value:e.durationMs}],tags:o}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:r,value:e.requestContentLength}],tags:o}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:r,value:e.responseContentLength}],tags:o}),t.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length===0)return;let t=JSON.stringify({series:e}),r=await Z.fetch(this.#t,{method:"POST",body:t,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new To(await r.text())},"dispatchFunction")},To=class n extends Error{static{i(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var vo=new WeakMap,jc={dimensions:[]},Co=class extends ze{constructor(t){super();this.options=t;g("metrics.dynatrace")}static{i(this,"DynatraceMetricsPlugin")}getTransport(){return new So(this.options)}static setContext(t,r){let o=vo.get(t);o||(o=jc);let s=Object.assign({...o},r);vo.set(t,s)}},So=class{static{i(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#n;#r=void 0;constructor(e){this.apiToken=e.apiToken,this.#e=e.url,this.#t=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#n=e.include??{},this.dimensions=e.dimensions??[]}pushMetrics(e,t){this.#r===void 0&&(this.#r=new Y("dynatrace-metrics-transport",10,this.dispatchFunction,Q.getLogger(t)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(vo.get(t)?.dimensions??[]);if(this.#n.country&&o.push(`country="${e.country}"`),this.#n.httpMethod&&o.push(`http_method="${e.method}"`),this.#n.statusCode&&o.push(`status_code="${e.statusCode}"`),this.#n.path){let a=e.systemRouteName||e.routePath;o.push(`path="${a}"`)}let s=o.join(",");this.#t.latency&&this.#r.enqueue(`zuplo.request.latency,${s} ${e.durationMs} ${r}`),this.#t.requestContentLength&&e.requestContentLength&&this.#r.enqueue(`zuplo.request.content_length,${s} ${e.requestContentLength} ${r}`),this.#t.responseContentLength&&e.responseContentLength&&this.#r.enqueue(`zuplo.response.content_length,${s} ${e.responseContentLength} ${r}`),t.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length===0)return;let t=e.join(`
62
- `),r=await Z.fetch(this.#e,{method:"POST",body:t,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new Oo(await r.text())},"dispatchFunction")},Oo=class n extends Error{static{i(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var Ao=class{static{i(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e,g("audit-logs.datastax")}#e;writeLogBatch=i(async e=>{await Promise.allSettled(e.map(async t=>{await Z.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(t)})}))},"writeLogBatch")};var ko=class extends qe{static{i(this,"AuditLogPlugin")}constructor(e,t){super(),this.#e=e,this.#t=t,g("audit-logs")}#e;#t;async initialize(e){new Lo(e,this.#e,this.#t)}},na=i(n=>{let e={};return n.forEach((t,r)=>{e[r]=t}),e},"serializableHeaders"),zc={requestFilter:i(async()=>!0,"requestFilter"),include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},Lo=class{static{i(this,"AuditPluginImpl")}constructor(e,t,r){this.#t=t;let o={...zc};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 Y("audit-log",10,this.#r)}#e;#t;#n;#r=i(async e=>{await this.#t.writeLogBatch(e)},"#dispatch");#o=i(async(e,t,r,o,s,a)=>{try{let u={timestamp:o,durationMs:s,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:t.url,method:t.method,headers:this.#e.include?.request?.headers?na(t.headers):void 0,body:this.#e.include?.request?.body?await t.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?na(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(u),r.waitUntil(this.#n.waitUntilFlushed())}catch(u){r.log.error(u)}},"#asyncPrepLogs");#i=i(async(e,t)=>{try{if(!await this.#e.requestFilter(e,t))return e;let o=new Date,s=Date.now(),a=e.clone();return t.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#o(d,a,t,o,l-s,c.user?.sub).catch(h=>{t.log.error(h)});t.waitUntil(p)}),e}catch(r){return t.log.error(r),e}},"#auditHook")};var _o=class extends Error{static{i(this,"StripeError")}message;type;raw;rawType;headers;requestId;code;doc_url;param;detail;statusCode;charge;decline_code;payment_method_type;payment_intent;payment_method;setup_intent;source;constructor(e={}){super(e.message),this.type=this.constructor.name,this.raw=e,this.rawType=e.type,this.code=e.code,this.doc_url=e.doc_url,this.param=e.param,this.detail=e.detail,this.headers=e.headers,this.requestId=e.requestId,this.statusCode=e.statusCode,this.message=e.message,this.charge=e.charge,this.decline_code=e.decline_code,this.payment_intent=e.payment_intent,this.payment_method=e.payment_method,this.payment_method_type=e.payment_method_type,this.setup_intent=e.setup_intent,this.source=e.source}},Me=class extends _o{static{i(this,"StripeSignatureVerificationError")}header;payload;constructor(e,t,r={}){super(r),this.header=e,this.payload=t}};var Bc="v1",Gc=300;async function ra(n,e,t,r=Gc,o){return await Wc(n,e,t,r,o),n instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(n)):JSON.parse(n)}i(ra,"constructEventAsync");function Vc(n,e){return`${e.timestamp}.${n}`}i(Vc,"makeHMACContent");async function Wc(n,e,t,r,o){let{decodedHeader:s,decodedPayload:a,details:u,suspectPayloadType:c}=Kc(n,e,Bc),l=/\s/.test(t),d=await Xc(Vc(a,u),t);return Jc(a,s,u,d,r,c,l,o)}i(Wc,"verifyHeaderAsync");function Kc(n,e,t){if(!n)throw new Me(e,n,{message:"No webhook payload was provided."});let r=typeof n!="string"&&!(n instanceof Uint8Array),o=new TextDecoder("utf8"),s=n instanceof Uint8Array?o.decode(n):n;if(Array.isArray(e))throw new Error("Unexpected: An array was passed as a header, which should not be possible for the stripe-signature header.");if(e==null||e=="")throw new Me(e,n,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=Qc(a,t);if(!u||u.timestamp===-1)throw new Me(a,s,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new Me(a,s,{message:"No signatures found with expected scheme"});return{decodedPayload:s,decodedHeader:a,details:u,suspectPayloadType:r}}i(Kc,"parseEventDetails");function Jc(n,e,t,r,o,s,a,u){let c=!!t.signatures.filter(h=>Yc(h,r)).length,l=`
60
+ `)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new S("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=oo(await Ws(this.body||""))}return e}};async function Kt(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?io.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,io.encode(e))}i(Kt,"hmac");async function Ws(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?io.encode(n):n)}i(Ws,"hash");function oo(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}i(oo,"buf2hex");function Ks(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(Ks,"encodeRfc3986");function hc(n,e){let{hostname:t,pathname:r}=n,o=t.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[s,a]=(o||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",s="s3";else if(s==="iot")t.startsWith("iot.")?s="execute-api":t.startsWith("data.jobs.iot.")?s="iot-jobs-data":s=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(s==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?s="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(s="autoscaling-plans")}else a==null&&s.startsWith("s3-")?(a=s.slice(3).replace(/^fips-|^external-1/,""),s="s3"):s.endsWith("-fips")?s=s.slice(0,-5):a&&/-\d$/.test(s)&&!/-\d$/.test(a)&&([s,a]=[a,s]);return s in Vs?[Vs[s],a]:[s,a]}i(hc,"guessServiceRegion");function yc(n){return n>64&&n<91?n-65:n>96&&n<123?n-71:n>47&&n<58?n+4:n===43?62:n===47?63:0}i(yc,"b64ToUint6");function Js(n,e){let t=n.replace(/[^A-Za-z0-9+/]/g,""),r=t.length,o=e?Math.ceil((r*3+1>>2)/e)*e:r*3+1>>2,s=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=yc(t.charCodeAt(d))<<6*(3-u),u===3||r-d===1){for(a=0;a<3&&l<o;)s[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return s}i(Js,"base64Decode");function An(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}i(An,"uint6ToB64");function Qs(n){let e=2,t="",r=n.length,o=0;for(let s=0;s<r;s++)e=s%3,o|=n[s]<<(16>>>e&24),(e===2||n.length-s===1)&&(t+=String.fromCodePoint(An(o>>>18&63),An(o>>>12&63),An(o>>>6&63),An(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}i(Qs,"base64Encode");function ft(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}i(ft,"numberToString");function bc(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=ft(Math.floor(t/60)),s=ft(t%60);return`${r}${o}${s}`}i(bc,"getCLFOffset");function ao(n=new Date){if(!(n instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],t=ft(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),s=ft(n.getHours()),a=ft(n.getMinutes()),u=ft(n.getSeconds()),c=bc(n);return`${t}/${r}/${o}:${s}:${a}:${u} ${c}`}i(ao,"toCLFDate");var Ys=he("zuplo:runtime"),wc="X-Amzn-Trace-Id",Rc="x-amzn-errortype",Xs=[],Pc=i(async(n,e,t)=>{let r=t;for await(let o of Xs)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),ve=class extends S{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(wc)??void 0,this.errorType=t.get(Rc)??void 0}},Ic={addSendingAwsLambdaEventHook:i(n=>{Xs.push(n)},"addSendingAwsLambdaEventHook")};async function Ec(n,e){f("handler.aws-lambda");let{accessKeyId:t,secretAccessKey:r,region:o,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!t)throw new g("awsAccessKeyId is not set in the handler options");if(!r)throw new g("secretAccessKey is not set in the handler options");if(!o)throw new g("region is not set in the handler options");if(!s)throw new g("functionName is not set in the handler options");let l=new gt({accessKeyId:t,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(Ys(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,m]=await Cc(n,{binaryMediaTypes:c}),{options:y}=e.route.handler,A;y&&typeof y=="object"&&"payloadFormatVersion"in y&&y.payloadFormatVersion==="2.0"?A=vc(n,e):A=await Tc(n,e,{useAwsResourcePathStyle:u}),Ys("Calling onSendingAwsLambdaEvent hook");let P=await Pc(n,e,A);P.body=p,P.isBase64Encoded=m;let v=await l.fetch(d,{body:JSON.stringify(P)});try{return xc(v)}catch(N){if(N instanceof ve){let k=y&&typeof y=="object"&&"returnAmazonTraceIdHeader"in y&&y.returnAmazonTraceIdHeader&&N.traceId?{AMZN_TRACE_ID_HEADER:N.traceId}:void 0;return x.internalServerError(n,e,void 0,k)}throw N}}i(Ec,"awsLambdaHandler");async function xc(n){let e;try{e=await n.json()}catch{throw new ve("Lambda response did not contain valid JSON",n.headers)}if(n.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new ve(e.message,n.headers):new ve(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new ve(e.errorMessage,n.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:n.status,headers:{"content-type":"application/json"}});let t=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new ve(`Response headers must be an object. Received ${typeof e.headers}`,n.headers);for(let[o,s]of Object.entries(e.headers))t.set(o,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new ve(`Response cookies must be an array. Received ${typeof e.cookies}`,n.headers);t.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new ve(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,n.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new ve("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new ve("Response was set to base64 encoded but body was not a string",n.headers);r=Js(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 ve(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,n.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:t,status:e.statusCode})}i(xc,"getResponse");async function Tc(n,e,{useAwsResourcePathStyle:t}){let r={},o={};n.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let s=n.query,a={};for(let[l,d]of Object.entries(s))a[l]=[d];let u=new URL(n.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:n.method,headers:r,multiValueHeaders:o,queryStringParameters:s,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:n.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:n.headers.get("CF-Connecting-IP"),user:null,userAgent:n.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:ao(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Sc(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}i(Tc,"buildEventVersion1");function vc(n,e){let t={};n.headers.forEach((s,a)=>{t[a]=s});let r=new URL(n.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:t,queryStringParameters:n.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:r.hostname,domainPrefix:null,http:{method:n.method,path:r.pathname,protocol:"HTTP/1.1",sourceIp:n.headers.get("CF-Connecting-IP"),userAgent:n.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:ao(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}i(vc,"buildEventVersion2");async function Cc(n,{binaryMediaTypes:e}){let t,r=!1,o=n.headers.get("content-type");if(n.method==="GET"||n.method==="HEAD")t=null;else if(e&&o&&Oc(e,o)){let s=await n.arrayBuffer();t=Qs(new Uint8Array(s)),r=!0}else t=await n.clone().text();return[t,r]}i(Cc,"getBodyResult");function Oc(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}i(Oc,"matchesContentType");function Sc(n,e=!1){if(!e)return n;let t=ro(n),r=Gs(n),o={};return t.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),r(o)}i(Sc,"getResourcePath");var Ac=[502,503,504];async function ht(n,e){if(Ac.includes(n.status)){let t=Q.getLogger(e),o=await n.clone().text(),s={};for(let[a,u]of n.headers)s[a]=u;t.warn(`BadGatewayResponse ${n.status}`,{status:n.status,statusText:n.statusText,body:o,headers:s})}}i(ht,"logBadGatewayResponses");var uo;function We(n){if(uo===void 0){let t=h.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),uo=t}return n.log[uo]}i(We,"getHandlerUserLogFunction");async function kc(n,e){f("handler.open-api");let t=h.instance.build.BUILD_ID,{buildAssetsUrl:r}=h.instance,o=e.route.handler.options,{openApiFilePath:s}=o;if(!s)throw new g("Open API Spec Handler must have 'openApiFilePath' specified");let a=Lc(s);if(!a.isValid)throw new g(a.error);let u;h.instance.isLocalDevelopment?u=`${r}/${s.substring(1)}`:u=`${r}/${t}${s.substring(1)}`;let c=await Z.fetch(u,{method:n.method,body:n.body,headers:n.headers});if(c.status!==200)return x.notFound(n,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return ht(l,e),l}i(kc,"openApiSpecHandler");var Lc=i(n=>n.startsWith("./")?n.startsWith("./config")?n.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function _c(n,e){f("handler.redirect");let t=e.route.handler.options;if(!t.location)throw new g("Redirect Handler must have 'location' specified");let r=t.status??302;return new Response(null,{status:r,headers:{location:t.location}})}i(_c,"redirectHandler");function Nc(n,e){let t=n.endsWith("/"),r=e.startsWith("/");return t&&r?`${n.substring(0,n.length-1)}${e}`:!t&&!r?`${n}/${e}`:`${n}${e}`}i(Nc,"join");async function Dc(n,e){f("handler.url-forward");let t=We(e),r=e.route.handler.options,o=r.forwardSearch!==!1;if(!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new g("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(n.url),u=r.__rewriteFunction(n,s),c=Nc(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();t(`URL Forwarding to '${l}'`);let p=await Z.fetch(l,{method:n.method,body:n.body,headers:n.headers}),m=Date.now()-d;return t(`URL Forward received response ${p.status} - ${p.statusText} in ${m}ms`),ht(p,e),p}i(Dc,"urlForwardHandler");var Mc=i((n,e)=>{let t=new URL(n),r=new URL(e);for(let[o,s]of r.searchParams.entries())t.searchParams.append(o,s);return t.toString()},"addQuery");async function qc(n,e){f("handler.url-rewrite");let t=We(e),r=e.route.handler.options,o=r.forwardSearch!==!1,s=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new g("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(n,a),c=o?Mc(u,n.url):u,l=Date.now();t(`URL Rewriting to '${c}'`);let d=await Z.fetch(c.toString(),{method:n.method,body:n.body,headers:n.headers,redirect:s?"follow":"manual"}),p=Date.now()-l;return t(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),ht(d,e),d}i(qc,"urlRewriteHandler");async function Hc(n,e){f("handler.websocket");let t=e.route.handler.options,r=We(e);if(!t||!t.rewritePattern)throw new g("WebSocket Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return x.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new g("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await Z.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let d=await c.text(),p=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${d}'`;throw new Error(p)}let l=Date.now()-u;return r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${l}ms`),new Response(null,{status:101,webSocket:c.webSocket})}i(Hc,"webSocketHandler");var co=i((n,e)=>n.map((r,o)=>{let s;if(typeof r.module=="object"&&(s=r.module[r.export]),!s||typeof s!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${o+1}, export name: ${r.export}`;throw new g(`${a} - Websocket policy must be a valid function (${u})`)}return s}),"getWebSocketPolicyFunctions"),ea=i(async(n,e,t,r,o,s)=>{let a=n.data;if(s&&s.length>0){let u=[...s];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,t,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function ta(n,e,t,r,o){n.addEventListener("close",()=>{e.close()}),n.addEventListener("error",s=>{r.log.error("WebSocket error: ",s),e.send(JSON.stringify(s))}),n.addEventListener("message",s=>{try{let u=i(async c=>{let l=await ea(c,n,e,t,r,o);l!==void 0&&e.send(l)},"innerPipeline")(s).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}i(ta,"wireUpListeners");async function Uc(n,e){f("handler.websocket-pipeline");let t=e.route.handler.options,r=We(e);if(!t||!t.rewritePattern)throw new g("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return x.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new g("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,s),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await Z.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let v=await c.text(),N=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${v}'`;throw new Error(N)}let l=new WebSocketPair,[d,p]=Object.values(l),m=Date.now()-u;r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${m}ms`);let y=c.webSocket;y.accept(),p.accept();let A=t.policies&&t.policies.inbound?co(t.policies.inbound,"inbound"):[],P=t.policies&&t.policies.outbound?co(t.policies.outbound,"outbound"):[];return ta(p,y,n,e,A),ta(y,p,n,e,P),new Response(null,{status:101,webSocket:d})}i(Uc,"webSocketPipelineHandler");var lo=class extends fe{constructor(t){super();this.options=t}static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new po(this.options)}},po=class{static{i(this,"DynaTraceTransport")}constructor(e){f("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#r=h.instance.loggingEnvironmentType,this.#o=h.instance.loggingEnvironmentStage,this.#n=h.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Ue(Ie(r)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#i=i(async e=>{if(e.length!==0)try{let t=await Z.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}});if(!t.ok){let r="";try{r=await t.text()}catch{}await le({level:"error",messages:[`Failed to send logs to Dynatrace: ${t.status} - ${t.statusText}`,r]})}}catch{await le({level:"error",messages:["Failed to connect to Dynatrace logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new Y("dyna-trace-log-transport",10,this.#i)};var mo=class extends fe{constructor(t){super();this.options=t}static{i(this,"LokiLoggingPlugin")}getTransport(){return new fo(this.options)}},go=class{static{i(this,"LokiStream")}constructor(e,t,r,o,s,a){this.level=e,this.environment=t,this.environmentType=r,this.environmentStage=o,this.requestId=a,this.job=s}job;level;environment;environmentType;environmentStage;requestId;equals=i(e=>this.level===e.level&&this.requestId===e.requestId,"equals")};function Zc(n,e){return btoa(`${n}:${e}`)}i(Zc,"createBasicDigest");var fo=class{static{i(this,"LokiTransport")}constructor(e){f("logging.loki"),this.#n=e.url,this.#r=Zc(e.username,e.password),this.#i=h.instance.loggingEnvironmentType,this.#s=h.instance.loggingEnvironmentStage,this.#o=h.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo"}#e;#t;#n;#r;#o;#i;#s;log(e,t){let r=new go(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(o=>{let s={stream:r,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:Ue(Ie(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(s)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=i(e=>{let t={streams:[]};return e.forEach(r=>{let o=t.streams.find(s=>s.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},t.streams.push(o)),o.values.push(this.#e>1?[r.nanoSecondEpoch,r.message,{requestId:r.requestId,rayId:r.rayId,atomicCounter:JSON.stringify(r.atomicCounter)}]:[r.nanoSecondEpoch,r.message])}),t},"#convertToLokiStreamsBatch");#u=i(async e=>{if(e.length===0)return;let t=this.#a(e);try{let r=await Z.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}});if(!r.ok){let o="";try{o=await r.text()}catch{}await le({level:"error",messages:[`Failed to send logs to Loki: ${r.status} - ${r.statusText}`,o]})}}catch{await le({level:"error",messages:["Failed to connect to Loki logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new Y("loki-log-transport",10,this.#u)};var ho=class extends fe{constructor(t){super();this.options=t}static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new yo(this.options)}},yo=class{static{i(this,"SumoLogicTransport")}constructor(e){f("logging.sumologic"),this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=h.instance.loggingEnvironmentType,this.#r=h.instance.loggingEnvironmentStage,this.#t=h.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Ue(Ie(r)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#s=i(async e=>{if(e.length===0)return;let t=e.map(o=>JSON.stringify(o)).join(`
61
+ `),r=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&r.set("X-Sumo-Name",this.#i),this.#o&&r.set("X-Sumo-Category",this.#o);try{let o=await Z.fetch(this.#e,{method:"POST",body:t,headers:r});if(!o.ok){let s="";try{s=await o.text()}catch{}await le({level:"error",messages:[`Failed to send logs to Sumologic: ${o.status} - ${o.statusText}`,s]})}}catch{await le({level:"error",messages:["Failed to connect to Sumologic logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new Y("sumo-logic-log-transport",10,this.#s)};var $c="d3a5b78f823648f5b1df4fe269d41172",bo=class extends fe{constructor(t){super();this.options=t}static{i(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new wo(this.options)}},wo=class{static{i(this,"VMWareLogInsightTransport")}constructor(e){f("logging.vmware-loginsight");let t;try{t=new URL(e.url),t.pathname==="/"&&(t.pathname=`/api/v1/events/ingest/${e.agentId??$c}`)}catch{throw new g(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=t.toString(),this.#r=h.instance.loggingEnvironmentType,this.#o=h.instance.loggingEnvironmentStage,this.#n=h.instance.deploymentName,this.#i=e.onMessageSending,this.#t=e.textReplacements,e.fields&&(this.#s=Object.entries(e.fields).map(([r,o])=>({name:r,content:o})))}#e;#t;#n;#r;#o;#i;#s;log(e,t){let r=this.buildEntry(e,t);this.batcher.enqueue(r),t.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,t){let r=Ns(e.messages);this.#t?.forEach(s=>{r=r.replaceAll(s[0],s[1])});let o={timestamp:Date.now(),text:r,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#r},{name:"environment_stage",content:this.#o},{name:"log_source",content:e.logSource},{name:"atomic_counter",content:e.vectorClock}]};return e.rayId&&o.fields.push({name:"request_ray_id",content:e.rayId}),this.#n&&o.fields.push({name:"environment",content:this.#n}),this.#s&&o.fields.push(...this.#s),t.custom&&Object.entries(t.custom).forEach(([s,a])=>{let u=zr(a);u&&o.fields.push({name:s,content:u})}),this.#i&&(o=this.#i(o)),o}#a=i(async e=>{if(e.length!==0)try{let t=await Z.fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});if(!t.ok){let r="";try{r=await t.text()}catch{}await le({level:"error",messages:[`Failed to send logs to Log Insight: ${t.status} - ${t.statusText}`,r]})}}catch{await le({level:"error",messages:["Failed to connect to Log Insight logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new Y("vmware-log-insights-log-transport",10,this.#a)};var Ro=class extends fe{constructor(t){super();this.options=t}static{i(this,"AWSLoggingPlugin")}getTransport(){return new Po(this.options)}},Po=class{static{i(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new Y("aws-log-transport",10,async e=>{if(e.length===0)return;let t=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});try{let r=await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:t,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}});if(!r.ok){let o="";try{o=await r.text()}catch{}await le({level:"error",messages:[`Failed to send logs to AWS: ${r.status} - ${r.statusText}`,o]})}}catch{await le({level:"error",messages:["Failed to connect to AWS logging service. Check that the URL is correct."]})}});constructor({accessKeyId:e,logStreamName:t,logGroupName:r,secretAccessKey:o,region:s}){f("logging.aws"),this.awsClient=new gt({accessKeyId:e,secretAccessKey:o,service:"logs",region:s}),this.logGroupName=r,this.logStreamName=t,this.region=s,this.environmentType=h.instance.loggingEnvironmentType,this.environment=h.instance.deploymentName}log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:Ue(Ie(r)),severity:e.level,source:e.logSource,environment:this.environment,requestId:e.requestId,environmentType:this.environmentType,rayId:e.rayId===null?void 0:e.rayId})};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}};var Io=new WeakMap,Fc={tags:[]},Eo=class extends ze{constructor(t){super();this.options=t;f("metrics.datadog")}static{i(this,"DataDogMetricsPlugin")}getTransport(){return new xo(this.options)}static setContext(t,r){let o=Io.get(t);o||(o=Fc);let s=Object.assign({...o},r);Io.set(t,s)}},xo=class{static{i(this,"DataDogMetricsTransport")}#e;#t;#n;#r;#o;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://api.datadoghq.com/api/v2/series",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.#r=e.tags??[]}pushMetrics(e,t){this.#i===void 0&&(this.#i=new Y("data-dog-metrics-transport",10,this.dispatchFunction,Q.getLogger(t)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(Io.get(t)?.tags??[]);if(this.#o.country&&o.push(`country:${e.country}`),this.#o.httpMethod&&o.push(`httpMethod:${e.method}`),this.#o.statusCode&&o.push(`statusCode:${e.statusCode}`),this.#o.path){let s=e.systemRouteName||e.routePath;o.push(`path:${s}`)}this.#n.latency&&this.#i.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:r,value:e.durationMs}],tags:o}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:r,value:e.requestContentLength}],tags:o}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:r,value:e.responseContentLength}],tags:o}),t.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length===0)return;let t=JSON.stringify({series:e}),r=await Z.fetch(this.#t,{method:"POST",body:t,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new To(await r.text())},"dispatchFunction")},To=class n extends Error{static{i(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var vo=new WeakMap,jc={dimensions:[]},Co=class extends ze{constructor(t){super();this.options=t;f("metrics.dynatrace")}static{i(this,"DynatraceMetricsPlugin")}getTransport(){return new Oo(this.options)}static setContext(t,r){let o=vo.get(t);o||(o=jc);let s=Object.assign({...o},r);vo.set(t,s)}},Oo=class{static{i(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#n;#r=void 0;constructor(e){this.apiToken=e.apiToken,this.#e=e.url,this.#t=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#n=e.include??{},this.dimensions=e.dimensions??[]}pushMetrics(e,t){this.#r===void 0&&(this.#r=new Y("dynatrace-metrics-transport",10,this.dispatchFunction,Q.getLogger(t)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(vo.get(t)?.dimensions??[]);if(this.#n.country&&o.push(`country="${e.country}"`),this.#n.httpMethod&&o.push(`http_method="${e.method}"`),this.#n.statusCode&&o.push(`status_code="${e.statusCode}"`),this.#n.path){let a=e.systemRouteName||e.routePath;o.push(`path="${a}"`)}let s=o.join(",");this.#t.latency&&this.#r.enqueue(`zuplo.request.latency,${s} ${e.durationMs} ${r}`),this.#t.requestContentLength&&e.requestContentLength&&this.#r.enqueue(`zuplo.request.content_length,${s} ${e.requestContentLength} ${r}`),this.#t.responseContentLength&&e.responseContentLength&&this.#r.enqueue(`zuplo.response.content_length,${s} ${e.responseContentLength} ${r}`),t.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length===0)return;let t=e.join(`
62
+ `),r=await Z.fetch(this.#e,{method:"POST",body:t,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new So(await r.text())},"dispatchFunction")},So=class n extends Error{static{i(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var Ao=class{static{i(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e,f("audit-logs.datastax")}#e;writeLogBatch=i(async e=>{await Promise.allSettled(e.map(async t=>{await Z.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(t)})}))},"writeLogBatch")};var ko=class extends qe{static{i(this,"AuditLogPlugin")}constructor(e,t){super(),this.#e=e,this.#t=t,f("audit-logs")}#e;#t;async initialize(e){new Lo(e,this.#e,this.#t)}},na=i(n=>{let e={};return n.forEach((t,r)=>{e[r]=t}),e},"serializableHeaders"),zc={requestFilter:i(async()=>!0,"requestFilter"),include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},Lo=class{static{i(this,"AuditPluginImpl")}constructor(e,t,r){this.#t=t;let o={...zc};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 Y("audit-log",10,this.#r)}#e;#t;#n;#r=i(async e=>{await this.#t.writeLogBatch(e)},"#dispatch");#o=i(async(e,t,r,o,s,a)=>{try{let u={timestamp:o,durationMs:s,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:t.url,method:t.method,headers:this.#e.include?.request?.headers?na(t.headers):void 0,body:this.#e.include?.request?.body?await t.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?na(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(u),r.waitUntil(this.#n.waitUntilFlushed())}catch(u){r.log.error(u)}},"#asyncPrepLogs");#i=i(async(e,t)=>{try{if(!await this.#e.requestFilter(e,t))return e;let o=new Date,s=Date.now(),a=e.clone();return t.addResponseSendingFinalHook(async(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#o(d,a,t,o,l-s,c.user?.sub).catch(m=>{t.log.error(m)});t.waitUntil(p)}),e}catch(r){return t.log.error(r),e}},"#auditHook")};var _o=class extends Error{static{i(this,"StripeError")}message;type;raw;rawType;headers;requestId;code;doc_url;param;detail;statusCode;charge;decline_code;payment_method_type;payment_intent;payment_method;setup_intent;source;constructor(e={}){super(e.message),this.type=this.constructor.name,this.raw=e,this.rawType=e.type,this.code=e.code,this.doc_url=e.doc_url,this.param=e.param,this.detail=e.detail,this.headers=e.headers,this.requestId=e.requestId,this.statusCode=e.statusCode,this.message=e.message,this.charge=e.charge,this.decline_code=e.decline_code,this.payment_intent=e.payment_intent,this.payment_method=e.payment_method,this.payment_method_type=e.payment_method_type,this.setup_intent=e.setup_intent,this.source=e.source}},Me=class extends _o{static{i(this,"StripeSignatureVerificationError")}header;payload;constructor(e,t,r={}){super(r),this.header=e,this.payload=t}};var Bc="v1",Gc=300;async function ra(n,e,t,r=Gc,o){return await Wc(n,e,t,r,o),n instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(n)):JSON.parse(n)}i(ra,"constructEventAsync");function Vc(n,e){return`${e.timestamp}.${n}`}i(Vc,"makeHMACContent");async function Wc(n,e,t,r,o){let{decodedHeader:s,decodedPayload:a,details:u,suspectPayloadType:c}=Kc(n,e,Bc),l=/\s/.test(t),d=await Xc(Vc(a,u),t);return Jc(a,s,u,d,r,c,l,o)}i(Wc,"verifyHeaderAsync");function Kc(n,e,t){if(!n)throw new Me(e,n,{message:"No webhook payload was provided."});let r=typeof n!="string"&&!(n instanceof Uint8Array),o=new TextDecoder("utf8"),s=n instanceof Uint8Array?o.decode(n):n;if(Array.isArray(e))throw new Error("Unexpected: An array was passed as a header, which should not be possible for the stripe-signature header.");if(e==null||e=="")throw new Me(e,n,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=Qc(a,t);if(!u||u.timestamp===-1)throw new Me(a,s,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new Me(a,s,{message:"No signatures found with expected scheme"});return{decodedPayload:s,decodedHeader:a,details:u,suspectPayloadType:r}}i(Kc,"parseEventDetails");function Jc(n,e,t,r,o,s,a,u){let c=!!t.signatures.filter(m=>Yc(m,r)).length,l=`
63
63
  Learn more about webhook signing and explore webhook integration examples for various frameworks at https://github.com/stripe/stripe-node#webhook-signing`,d=a?`
64
64
 
65
65
  Note: The provided signing secret contains whitespace. This often indicates an extra newline or space is in the value`:"";if(!c)throw s?new Me(e,n,{message:`Webhook payload must be provided as a string or a Buffer (https://nodejs.org/api/buffer.html) instance representing the _raw_ request body.Payload was provided as a parsed JavaScript object instead.
@@ -68,9 +68,9 @@ Signature verification is impossible without access to the original signed mater
68
68
  `+d}):new Me(e,n,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
69
69
  If a webhook request is being forwarded by a third-party tool, ensure that the exact request body, including JSON formatting and new line style, is preserved.
70
70
  `+l+`
71
- `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new Me(e,n,{message:"Timestamp outside the tolerance zone"});return!0}i(Jc,"validateComputedSignature");function Qc(n,e){return typeof n!="string"?null:n.split(",").reduce((t,r)=>{let o=r.split("=");return o[0]==="t"&&(t.timestamp=parseInt(o[1],10)),o[0]===e&&t.signatures.push(o[1]),t},{timestamp:-1,signatures:[]})}i(Qc,"parseHeader");function Yc(n,e){if(n.length!==e.length)return!1;let t=n.length,r=0;for(let o=0;o<t;++o)r|=n.charCodeAt(o)^e.charCodeAt(o);return r===0}i(Yc,"secureCompare");async function Xc(n,e){let t=new TextEncoder,r=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,t.encode(n)),s=new Uint8Array(o),a=new Array(s.length);for(let u=0;u<s.length;u++)a[u]=No[s[u]];return a.join("")}i(Xc,"computeHMACSignatureAsync");var No=new Array(256);for(let n=0;n<No.length;n++)No[n]=n.toString(16).padStart(2,"0");function K(n,e,t="policy",r){let o=`${t} '${e}'`;if(!nt(n))throw new m(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let s=i((c,l,d)=>{let p=n[c],h=r?`${r}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new m(`Value of '${h}' on ${o} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"&&Array.isArray(p))throw new m(`Value of '${h}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new m(`Value of '${h}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new m(`Value of '${h}' on ${o} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof p=="number"&&isNaN(p))throw new m(`Value of '${h}' on ${o} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=i((c,l)=>(s(c,l,!0),{optional:a,required:u}),"optional"),u=i((c,l)=>(s(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}i(K,"optionValidator");var Jt=class extends ae{static{i(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.stripe-webhook-verification")}async handler(e,t){K(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let r=e.headers.get("stripe-signature");try{let o=await e.clone().text();await ra(o,r,this.options.signingSecret)}catch(o){let s=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a,s.startsWith("No signatures found matching the expected signature for payload")&&(s="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",s),x.badRequest(e,t,{title:"Webhook Error",detail:s})}return e}};function oa(n){return n!==null&&typeof n=="object"&&"id"in n&&xe(n.id)&&"type"in n&&xe(n.type)}i(oa,"isStripeWebhookEvent");var el={getSubscription:i(async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await Z.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving subscription from Stripe API.";throw t.error(s,o),new A(s)}return o},"getSubscription"),getCustomer:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await Z.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer from Stripe API.";throw t.error(s,o),new A(s)}return o},"getCustomer"),getUpcomingInvoice:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await Z.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(s,o),new A(s)}return o},"getUpcomingInvoice")},kn=el;var Do="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",ia="My API Key";async function sa({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=f.instance,c=new URL(`/v1/buckets/${n}/consumers`,Do);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:ia,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await ye({retryDelayMs:5,retries:2,logger:Q.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),h=await p.json();if(p.status!==200){let y="Error creating API Key Consumer";throw a.log.error(y,h),new A(y)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(sa,"createConsumer");async function aa({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=f.instance,u=new URL(`/v1/buckets/${n}/consumers`,Do);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:ia,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await ye({retryDelayMs:5,retries:2,logger:Q.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let h="Error creating API Key Consumer";throw s.log.error(h,p),new A(h)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(aa,"createConsumerInvite");async function ua({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=f.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,Do);o.searchParams.set("with-api-key","true");let s=await ye({retryDelayMs:5,retries:2,logger:Q.getLogger(t)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new A(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(ua,"deleteConsumer");async function ca({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:r,meteringBucketId:o,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[t],customerKey:r,customerExternalId:a,metadata:c,trialEndDate:l?l.trialEndDate:void 0,trialStartDate:l?l.trialStartDate:void 0,trialEndStatus:l?l.trialEndStatus:void 0},{authApiJWT:p,meteringServiceUrl:h}=f.instance;if(!pt(p))throw new W("No Zuplo JWT token set.");let y=await ye({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${h}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!y.ok){let O=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,P,v="";try{P=await y.json(),v=P.detail??P.title}catch{P={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:y.status,detail:y.statusText}}throw n.log.error(O,P),new A(`${O} ${v}`)}n.log.info("Successfully created monetization subscription.",d)}i(ca,"createSubscription");async function yt({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=f.instance;if(!pt(o))throw new W("No Zuplo JWT token set.");let a=await ye({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${s}/internal/v1/metering/${t}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Unable to update monetization subscription with: '${JSON.stringify(r)}'.`,c,l="";try{c=await a.json(),l=c.detail??c.title}catch{c={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(u,c),new A(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}i(yt,"updateSubscription");async function bt({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=f.instance;if(!pt(o))throw new W("No Zuplo JWT token set.");let a=await ye({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${s}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":n.requestId},method:"GET"});if(!a.ok){let c=`Unable to retrieve the monetization subscription for Stripe subscription '${e}'.`,l,d="";try{l=await a.json(),d=l.detail??l.title}catch{l={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(c,l),new A(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(c),new A(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(c),new A(c)}return u.data[0]}i(bt,"getSubscription");var ie="Skipping since we're unable to process the webhook event.",Ke="Successfully processed the webhook event",Ee="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function Ln(n){return n.replaceAll("_","-")}i(Ln,"stripeStatusToMeteringStatus");function st(n){return new Date(n*1e3).toISOString()}i(st,"unixTimestampToISOString");async function Mo(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),x.ok(n,e,{title:ie,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),x.ok(n,e,{title:ie,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=t.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:ie,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==f.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),x.ok(n,e,{title:ie,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ee});let u=s.product,c,l,d;try{if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_email&&t.data.object.metadata.zuplo_created_by_sub)l=t.data.object.metadata.zuplo_created_by_email,d=t.data.object.metadata.zuplo_created_by_sub,c=await sa({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await kn.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),x.ok(n,e,{title:ie,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await aa({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}}catch(p){return e.log.warn(`Failed to create API Key Consumer. Error: ${p.message}`),x.ok(n,e,{title:ie,detail:p.message})}if(!c)return x.ok(n,e,{title:ie,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=Ln(t.data.object.status),h;l&&d&&(h={subscriber:{sub:d,email:l}});let y;t.data.object.trial_end!==null&&t.data.object.trial_start!==null&&t.data.object.trial_settings&&t.data.object.trial_settings.end_behavior&&(t.data.object.trial_settings.end_behavior.missing_payment_method==="cancel"||t.data.object.trial_settings.end_behavior.missing_payment_method==="pause")&&(y={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:st(t.data.object.trial_end),trialStartDate:st(t.data.object.trial_start)}),await ca({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:h,trial:y})}catch(p){return await ua({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),x.ok(n,e,{title:ie,detail:p.message})}return x.ok(n,e,{title:Ke})}i(Mo,"onCustomerSubscriptionCreated");async function qo(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),x.ok(n,e,{title:ie,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:ie,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==f.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),x.ok(n,e,{title:ie,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ee});try{let a=await bt({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});await yt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return x.ok(n,e,{title:ie,detail:`The event 'customer.subscription.deleted' could not be processed. ${a.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. `+Ee})}return x.ok(n,e,{title:Ke})}i(qo,"onCustomerSubscriptionDeleted");async function Uo(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to include '.data.object.id' as the subscription ID.`),x.ok(n,e,{title:ie,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:ie,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==f.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),x.ok(n,e,{title:ie,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ee});if(t.data.previous_attributes){let a=t.data.previous_attributes;if(a.status&&a.status!==t.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${t.id}'.`);let u=await bt({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=Ln(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=st(t.data.object.trial_end)),await yt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return x.ok(n,e,{title:ie,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ee})}return x.ok(n,e,{title:Ke})}if(a.plan&&a.plan.product!==t.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${t.id}'.`);let u=await bt({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await kn.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(h=>h.proration&&h.price.product===c),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${t.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await yt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return x.ok(n,e,{title:ie,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ee})}return x.ok(n,e,{title:Ke})}if((a.cancel_at||a.cancel_at===null)&&a.cancel_at!==t.data.object.cancel_at&&a.cancel_at_period_end&&a.cancel_at_period_end!==t.data.object.cancel_at_period_end&&(a.canceled_at||a.canceled_at===null)&&a.canceled_at!==t.data.object.canceled_at||a.cancellation_details&&(a.cancellation_details.comment||a.cancellation_details.comment===null||a.cancellation_details.feedback||a.cancellation_details.feedback===null||a.cancellation_details.reason||a.cancellation_details.reason===null)){try{e.log.debug(`Processing subscription cancellation details from Stripe event '${t.id}'.`);let u=await bt({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?st(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?st(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await yt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return x.ok(n,e,{title:ie,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ee})}return x.ok(n,e,{title:Ke})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),x.ok(n,e,{title:ie,detail:"This 'customer.subscription.updated' event could not be processed. The Stripe monetization plugin only supports update events for subscription plan changes or subscription status changes."+Ee})}i(Uo,"onCustomerSubscriptionUpdated");var la=class extends sn{constructor(t){super();this.options=t;g("monetization.stripe")}static{i(this,"StripeMonetizationPlugin")}registerRoutes(t,r){let o=i(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!f.instance.build.ACCOUNT_NAME)throw new W("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let h=this.options.primaryDataRegion??"us-central1";if(!tl(h))throw new m(`StripeMonetizationPlugin - The value '${h}' on the property 'primaryDataRegion' is invalid.`);let y=await c.json();if(!oa(y))return x.ok(c,l,{title:ie,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+Ee});switch(l.log.info(`Received Stripe webhook event of type '${y.type}' with ID '${y.id}'.`),y.type){case"customer.subscription.created":return await Mo(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await Uo(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await qo(c,l,y,{meteringBucketId:d});default:return x.ok(c,l,{title:ie,detail:`Event '${y.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ee})}},"stripeWebhookHandler"),s=Ts({inboundPolicies:[new Jt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});K(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new me({processors:[we,s],handler:o,gateway:r}),u=new ce({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function tl(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}i(tl,"isMetricsRegion");var pa=new WeakMap,da={},Ho=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){pa.set(e,t)}};async function nl(n,e,t,r){if(g("policy.inbound.amberflo-metering"),!t.statusCodes)throw new m(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Be(t.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=pa.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new A(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=rt(n.user,t.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??t.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??t.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(t.dimensions??{},a?.dimensions)},h=da[t.apiKey];if(!h){let y=t.apiKey,O=n.headers.get("zm-test-id")??"";h=new Y("amberflo-ingest-meter",10,async P=>{try{let v=t.url??"https://app.amberflo.io/ingest",N=await Z.fetch(v,{method:"POST",body:JSON.stringify(P),headers:{"content-type":"application/json","x-api-key":y,"zm-test-id":O}});N.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${N.status}: ${await N.text()}`)}catch(v){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${v.message}`),v}}),da[y]=h}h.enqueue(p),e.waitUntil(h.waitUntilFlushed())}}),n}i(nl,"AmberfloMeteringInboundPolicy");async function at(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(t)].map(o=>o.toString(16).padStart(2,"0")).join("")}i(at,"sha256");var ma=new Map;async function se(n,e,t){let r,o=`${n}-${e}`,s=ma.get(o);return s!==void 0?r=s:(r=`zuplo-policy-${await at(JSON.stringify({policyName:n,options:t}))}`,ma.set(n,r)),r}i(se,"getPolicyCacheName");var ga="key-metadata-cache-type";function rl(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}i(rl,"getKeyValue");async function Zo(n,e,t,r){if(g("policy.inbound.api-key"),!t.bucketName)if(Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:t.authHeader??"authorization",authScheme:t.authScheme??"Bearer",bucketName:t.bucketName,cacheTtlSeconds:t.cacheTtlSeconds??60,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:t.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new m(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let s=i(v=>o.allowUnauthenticatedRequests?n:x.unauthorized(n,e,{detail:v}),"unauthorizedResponse"),a=n.headers.get(o.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=rl(a,o);if(!u||u==="")return s("No key present");let c=await ol(u),l=await se(r,void 0,o),d=new re(l,e),p=await d.get(c);if(p&&p.isValid===!0)return n.user=p.user,n;if(p&&!p.isValid)return p.typeId!==ga&&Q.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let h={key:u},y=await ye({retryDelayMs:5,retries:2,logger:Q.getLogger(e)},`${f.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":f.instance.deploymentName??"unknown","User-Agent":f.instance.systemUserAgent},body:JSON.stringify(h)});if(y.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(y.status!==200){try{let v=await y.text(),N=JSON.parse(v);e.log.error("Unexpected response from key service",N)}catch{e.log.error("Invalid response from key service")}throw new A(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${y.status}`)}let O=await y.json(),P={isValid:!0,typeId:ga,user:{sub:O.name,data:O.metadata}};return n.user=P.user,d.put(c,P,o.cacheTtlSeconds),n}i(Zo,"ApiKeyInboundPolicy");async function ol(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(ol,"hashValue");var il=Zo;import{createRemoteJWKSet as al,jwtVerify as ha}from"jose";import{createLocalJWKSet as sl}from"jose";var $o=class{constructor(e,t,r){this.cache=t;if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.url=new URL(e.href),this.options={agent:r?.agent,headers:r?.headers},this.timeoutDuration=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this.cooldownDuration=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this.cacheMaxAge=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5}static{i(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,t){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,t)}catch(r){if(r instanceof Fo&&this.coolingDown()===!1)return await this.reload(),this.local(e,t);throw r}}async reload(){this.pendingFetch&&(this.pendingFetch=void 0);let e=new Headers(this.options.headers);e.has("User-Agent")||(e.set("User-Agent",f.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=sl(t),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(t=>{throw this.pendingFetch=void 0,t}),await this.pendingFetch}async fetchJwks(e,t,r){let o=await this.cache.get(this.url.href);if(o)return o;let s,a,u=!1;typeof AbortController=="function"&&(s=new AbortController,a=setTimeout(()=>{u=!0,s.abort()},t));let c=await Z.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new jo("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new wt("Expected 200 OK from the JSON Web Key Set HTTP response");try{let l=await c.json();return this.cache.put(this.url.href,l,this.cacheMaxAge),l}catch{throw new wt("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function fa(n,e,t){let r=new $o(n,e,t);return async(o,s)=>r.getKey(o,s)}i(fa,"createRemoteJWKSet");var wt=class extends A{static{i(this,"JWKSError")}},Fo=class extends wt{static{i(this,"JWKSNoMatchingKey")}},jo=class extends wt{static{i(this,"JWKSTimeout")}};var _n={},ul=i((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");if(!_n[r.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(s=r.useExperimentalInMemoryCache),s){let a=await se(n,void 0,r),u=new re(a,e);_n[r.jwkUrl]=fa(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else _n[r.jwkUrl]=al(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await ha(t,_n[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),cl=i(async(n,e)=>{let t;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);t=new Uint8Array(s)}else t=e.secret;let{payload:r}=await ha(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),Re=i(async(n,e,t,r)=>{g("policy.inbound.open-id-jwt-auth");let o=n.headers.get("Authorization"),s="bearer ",a=i(h=>x.unauthorized(n,e,{detail:h}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=t.jwkUrl?ul(r,e):cl,l=await i(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let h=o.substring(s.length);if(!h||h.length===0)return a("No bearer token on authorization header");try{return await u(h,t)}catch(y){let O=new URL(n.url);return"code"in y&&y.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${O.pathname} `,y):e.log.warn(`Invalid token on: ${n.method} ${O.pathname}`,y),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return t.allowUnauthenticatedRequests===!0?n:l;let d=t.subPropertyName??"sub",p=l[d];return p?(n.user={sub:p,data:l},n):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var ll=i(async(n,e,t,r)=>(g("policy.inbound.auth0-jwt-auth"),Re(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"Auth0JwtInboundPolicy");var Nn=class{constructor(e){this.options=e;this.authHeader=`Basic ${btoa(e.pdpUsername+":"+e.pdpPassword)}`,this.authorizationUrl=new URL("/authorize",e.pdpUrl).toString()}static{i(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(e){let t=await Z.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!t.ok)throw new Error(`Request to PDP service failed with response status ${t.status}.`);return await t.json()}};var zo=class n extends ae{static{i(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static#e;static setAuthAttributes(e,t){n.#e||(n.#e=new WeakMap),n.#e.set(e,{Request:t})}constructor(e,t){super(e,t),g("policy.inbound.axiomatics-authz"),K(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new Nn(e)}async handler(e,t){let r=i(a=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=new URL(e.url),s=n.#e?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1&&e.user){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(s,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(s,"Action",a)}if(this.options.includeDefaultResourceAttributes!==!1){let a=[];a.push({AttributeId:"request.protocol",Value:o.protocol.substring(0,o.protocol.length-1)}),a.push({AttributeId:"request.host",Value:o.host}),a.push({AttributeId:"request.pathname",Value:o.pathname}),Object.entries(e.params).forEach(([u,c])=>{a.push({AttributeId:`request.params.${u}`,Value:c})}),o.searchParams.forEach((u,c)=>{a.push({AttributeId:`request.query.${c}`,Value:u})}),this.addAttributesToCategory(s,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:s,context:t});try{t.log.debug("PDP Request",s);let a=await this.pdpService.makePdpRequest(s);return t.log.debug("PDP Response",a),a.Response.every(u=>u.Decision==="Permit")?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling PDP service`,a),x.internalServerError(e,t)}}populateOptionAttributes({optionName:e,authzRequestCategory:t,authzRequest:r,context:o}){let s=this.options[e];if(s){let a=[];s.forEach(u=>{u.value?a.push({AttributeId:u.attributeId,Value:u.value}):o.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${u.attributeId} has no value. If using a selector, check that the selector is correct.`)}),this.addAttributesToCategory(r,t,a)}}addAttributesToCategory(e,t,r){e.Request[t]||(e.Request[t]=[]),e.Request[t].length===0?e.Request[t].push({Attribute:[]}):e.Request[t][0].Attribute=e.Request[t][0].Attribute??[],e.Request[t][0].Attribute.push(...r)}};var dl=i(async(n,e,t)=>{g("policy.inbound.basic-auth");let r=n.headers.get("Authorization"),o="basic ",s=i(l=>x.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!r)return await s("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await s("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let h=d.substring(0,p),y=d.substring(p+1),O=t.accounts.find(P=>P.username===h&&P.password===y);return O||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return t.allowUnauthenticatedRequests?n:u;let c=u.username;return n.user={sub:c,data:u.data},n},"BasicAuthInboundPolicy");function Dn(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}i(Dn,"extractDateElements");function ya(n,e){return new Date(n,e+1,0).getDate()}i(ya,"getDaysInMonth");function Bo(n,e){return n<=e?e-n:6-n+e+1}i(Bo,"getDaysBetweenWeekdays");var Mn=class{static{i(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:r,days:o,months:s,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!t||t.size===0)throw new Error("There must be at least one allowed minute.");if(!r||r.size===0)throw new Error("There must be at least one allowed hour.");if(!s||s.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!o||o.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((c,l)=>c-l),this.minutes=Array.from(t).sort((c,l)=>c-l),this.hours=Array.from(r).sort((c,l)=>c-l),this.days=Array.from(o).sort((c,l)=>c-l),this.months=Array.from(s).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=i((c,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${c} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");u("seconds",this.seconds,{min:0,max:59}),u("minutes",this.minutes,{min:0,max:59}),u("hours",this.hours,{min:0,max:23}),u("days",this.days,{min:1,max:31}),u("months",this.months,{min:0,max:11}),u("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(c=>c).reverse(),minutes:this.minutes.map(c=>c).reverse(),hours:this.hours.map(c=>c).reverse(),days:this.days.map(c=>c).reverse(),months:this.months.map(c=>c).reverse(),weekdays:this.weekdays.map(c=>c).reverse()}}findAllowedHour(e,t){return e==="next"?this.hours.find(r=>r>=t):this.reversed.hours.find(r=>r<=t)}findAllowedMinute(e,t){return e==="next"?this.minutes.find(r=>r>=t):this.reversed.minutes.find(r=>r<=t)}findAllowedSecond(e,t){return e==="next"?this.seconds.find(r=>r>t):this.reversed.seconds.find(r=>r<t)}findAllowedTime(e,t){let r=this.findAllowedHour(e,t.hour);if(r!==void 0)if(r===t.hour){let o=this.findAllowedMinute(e,t.minute);if(o!==void 0)if(o===t.minute){let s=this.findAllowedSecond(e,t.second);if(s!==void 0)return{hour:r,minute:o,second:s};if(o=this.findAllowedMinute(e,e==="next"?t.minute+1:t.minute-1),o!==void 0)return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(r=this.findAllowedHour(e,e==="next"?t.hour+1:t.hour-1),r!==void 0)return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,t,r,o){if(o<1)throw new Error("startDay must not be smaller than 1.");let s=ya(t,r),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return o>s?e==="next"?void 0:s:o;let c;a&&(c=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),c!==void 0&&c>s&&(c=void 0));let l;if(u){let d=new Date(t,r,o).getDay(),p=e==="next"?this.weekdays.find(h=>h>=d)??this.weekdays[0]:this.reversed.weekdays.find(h=>h<=d)??this.reversed.weekdays[0];if(p!==void 0){let h=e==="next"?Bo(d,p):Bo(p,d);l=e==="next"?o+h:o-h,(l>s||l<1)&&(l=void 0)}}if(c!==void 0&&l!==void 0)return e==="next"?Math.min(c,l):Math.max(c,l);if(c!==void 0)return c;if(l!==void 0)return l}getNextDate(e=new Date){let t=Dn(e),r=t.year,o=this.months.findIndex(a=>a>=t.month);o===-1&&(o=0,r++);let s=this.months.length*5;for(let a=0;a<s;a++){let u=r+Math.floor((o+a)/this.months.length),c=this.months[(o+a)%this.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("next",u,c,l?t.day:1),p=l&&d===t.day;if(d!==void 0&&p){let h=this.findAllowedTime("next",t);if(h!==void 0)return new Date(u,c,d,h.hour,h.minute,h.second);d=this.findAllowedDayInMonth("next",u,c,d+1),p=!1}if(d!==void 0&&!p)return new Date(u,c,d,this.hours[0],this.minutes[0],this.seconds[0])}throw new Error("No valid next date was found.")}getNextDates(e,t){let r=[],o;for(let s=0;s<e;s++)o=this.getNextDate(o??t),r.push(o);return r}*getNextDatesIterator(e,t){let r;for(;;){if(r=this.getNextDate(e),e=r,t&&t.getTime()<r.getTime())return;yield r}}getPrevDate(e=new Date){let t=Dn(e),r=t.year,o=this.reversed.months.findIndex(a=>a<=t.month);o===-1&&(o=0,r--);let s=this.reversed.months.length*5;for(let a=0;a<s;a++){let u=r-Math.floor((o+a)/this.reversed.months.length),c=this.reversed.months[(o+a)%this.reversed.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("prev",u,c,l?t.day:31),p=l&&d===t.day;if(d!==void 0&&p){let h=this.findAllowedTime("prev",t);if(h!==void 0)return new Date(u,c,d,h.hour,h.minute,h.second);d>1&&(d=this.findAllowedDayInMonth("prev",u,c,d-1),p=!1)}if(d!==void 0&&!p)return new Date(u,c,d,this.reversed.hours[0],this.reversed.minutes[0],this.reversed.seconds[0])}throw new Error("No valid previous date was found.")}getPrevDates(e,t){let r=[],o;for(let s=0;s<e;s++)o=this.getPrevDate(o??t),r.push(o);return r}*getPrevDatesIterator(e,t){let r;for(;;){if(r=this.getPrevDate(e),e=r,t&&t.getTime()>r.getTime())return;yield r}}matchDate(e){let{second:t,minute:r,hour:o,day:s,month:a,weekday:u}=Dn(e);return this.seconds.indexOf(t)===-1||this.minutes.indexOf(r)===-1||this.hours.indexOf(o)===-1||this.months.indexOf(a)===-1?!1:this.days.length!==31&&this.weekdays.length!==7?this.days.indexOf(s)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(s)!==-1&&this.weekdays.indexOf(u)!==-1}};var pl={min:0,max:59},ml={min:0,max:59},gl={min:0,max:23},fl={min:1,max:31},hl={min:1,max:12,aliases:{jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"}},yl={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},bl={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 1 *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@hourly":"0 * * * *","@minutely":"* * * * *"};function ut(n,e){let t=new Set;if(n==="*"){for(let d=e.min;d<=e.max;d=d+1)t.add(d);return t}let r=n.split(",");if(r.length>1)return r.forEach(d=>{ut(d,e).forEach(h=>t.add(h))}),t;let o=i(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${n}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${n}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),s=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(s===null)return t.add(o(n)),t;let a=s[1]==="*"?e.min:o(s[3]),u=s[1]==="*"?e.max:o(s[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=s[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}i(ut,"parseElement");function Go(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=bl[n.toLowerCase()]??n;let e=n.split(" ");if(e.length<5||e.length>6)throw new Error("Invalid cron expression: expected 5 or 6 elements.");let t=e.length===6?e[0]:"0",r=e.length===6?e[1]:e[0],o=e.length===6?e[2]:e[1],s=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],u=e.length===6?e[5]:e[4];return new Mn({seconds:ut(t,pl),minutes:ut(r,ml),hours:ut(o,gl),days:ut(s,fl),months:new Set(Array.from(ut(a,hl)).map(c=>c-1)),weekdays:new Set(Array.from(ut(u,yl)).map(c=>c%7))})}i(Go,"parseCronExpression");var Vo=class extends ae{static{i(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),g("policy.inbound.brownout"),K(e,t).optional("problem","object"),e.problem&&K(e.problem,t,"policy","problem").optional("detail","string").optional("status","string").optional("title","string"),typeof e.cronSchedule!="string"&&!(typeof e.cronSchedule=="object"&&Array.isArray(e.cronSchedule)&&!e.cronSchedule.some(r=>typeof r!="string")))throw new m(`Value of 'cronSchedule' on policy '${t}' must be of type string or string[]. Received type ${typeof e.cronSchedule}.`);typeof this.options.cronSchedule=="string"?this.crons=[Go(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>Go(r))}async handler(e,t){let r=new Date;if(r.setSeconds(0),r.setMilliseconds(0),this.crons.some(s=>s.matchDate(r))){let s=x.getProblemFromStatus(this.options.problem?.status??400,{detail:"This API is performing a scheduled brownout in advance of its pending deprecation. Please upgrade to a later version.",...this.options.problem});return x.format(s,e,t)}return e}};var wl=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Rl(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Rl,"digestMessage");var Pl=i(async(n,e)=>{let t=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of n.headers.entries())t.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await Rl(JSON.stringify(r)),s=new URL(n.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(n.method.toUpperCase())&&n.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",n.method);let c=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function Il(n,e,t,r){g("policy.inbound.caching");let o=await se(r,t.cacheId,t),s=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Pl(n,t),c=await s.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=t.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(n.method.toUpperCase()))return;let h=t?.expirationSecondsTtl??60,y=new Response(p.body,p);wl.forEach(O=>y.headers.delete(O)),y.headers.set("cache-control",`s-maxage=${h}`),e.waitUntil(s.put(u,y))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}i(Il,"CachingInboundPolicy");var El=i(async(n,e,t,r)=>{if(g("policy.inbound.change-method"),!t.method)throw new m(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new te(n,{method:t.method})},"ChangeMethodInboundPolicy");var xl=i(async(n,e,t)=>{g("policy.inbound.clear-headers");let r=[...t.exclude??[]],o=new Headers;return r.forEach(a=>{let u=n.headers.get(a);u&&o.set(a,u)}),new te(n,{headers:o})},"ClearHeadersInboundPolicy");var Tl=i(async(n,e,t,r)=>{g("policy.outbound.clear-headers");let o=[...r.exclude??[]],s=new Headers;return o.forEach(u=>{let c=n.headers.get(u);c&&s.set(u,c)}),new Response(n.body,{headers:s,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var vl=i(async(n,e,t,r)=>{g("policy.inbound.clerk-jwt-auth");let o=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),s=new URL(o);return s.pathname="/.well-known/jwks.json",Re(n,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var Cl=i(async(n,e,t,r)=>{if(g("policy.inbound.cognito-jwt-auth"),!t.userPoolId)throw new m("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new m("region must be set in the options for CognitoJwtInboundPolicy");return Re(n,e,{issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,jwkUrl:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var qn=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},Wo=class extends qn{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Ko=class extends qn{static{i(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function Sl(n,e){if(ys(n))throw new Wo(e)}i(Sl,"throwIfUndefinedOrNull");function ba(n,e){if(Sl(n,e),!xe(n))throw new Ko(e,"string")}i(ba,"throwIfNotString");var Jo=class{static{i(this,"InMemoryRateLimitClient")}keyValueStore;constructor(){this.keyValueStore=new Map}getCountAndUpdateExpiry(e,t){let o=Math.floor(t*60),s=Date.now()+o*1e3,a=this.keyValueStore.get(e);a?Date.now()>a.expiresAt?this.keyValueStore.set(e,{value:1,expiresAt:s}):this.keyValueStore.set(e,{value:a.value+1,expiresAt:a.expiresAt}):this.keyValueStore.set(e,{value:1,expiresAt:s});let u=this.keyValueStore.get(e);return Promise.resolve({count:u.value,ttlSeconds:Math.round((u.expiresAt-Date.now())/1e3)})}multiIncrement(e,t){throw new Error("In memory complex rate limits are not currently supported.")}multiCount(e,t){throw new Error("In memory complex rate limits are not currently supported.")}setQuota(e,t,r){throw new Error("In memory quotas are not currently supported.")}getQuota(e,t){throw new Error("In memory quotas are not currently supported.")}isEnabled(){return!0}},Qo=class{constructor(e,t,r,o){this.clientUrl=e;this.clientAuthToken=t;this.deploymentName=r;this.userAgent=o}static{i(this,"RemoteRateLimitClient")}static instance;isEnabled(){return this.clientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:t,method:r,requestId:o}){ba(e,"url");let s=await Z.fetch(`${this.clientUrl}${e}`,{method:r,body:t,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=s.headers.get("Content-Type")?.includes("application/json")?await s.json():await s.text();if(s.ok)return a;throw s.status===401?new W("Rate limiting service failed with 401: Unauthorized"):new W(`Rate limiting service failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}async multiCount(e,t){return(await this.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async multiIncrement(e,t){return(await this.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async getCountAndUpdateExpiry(e,t,r){let o=Math.floor(t*60);return await this.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:o,key:e}),requestId:r})}async getQuota(e,t){let r=await at(e);return await this.fetch({url:`/quota/${r}`,method:"GET",requestId:t})}async setQuota(e,t,r){let o=await at(e);await this.fetch({url:`/quota/${o}`,method:"POST",body:JSON.stringify(t),requestId:r})}},Je;function Qe(n,e){if(Je)return Je;if(!f.instance.authApiJWT)return e.info("Using in-memory rate limit client for local development."),Je=new Jo,Je;let{authApiJWT:t,redisURL:r}=f.instance;if(!xe(r))throw new W(`RateLimitClient used in policy '${n}' - rate limit service URL not configured`);if(!xe(t))throw new W(`RateLimitClient used in policy '${n}' - service authentication not configured`);if(r&&(Je=new Qo(r,t,f.instance.deploymentName??"unknown",f.instance.systemUserAgent)),!Je||!Je.isEnabled())throw new W(`RateLimitClient used in policy '${n}' - no remote rate limiting service enabled`);return Je}i(Qe,"getRateLimitClient");var Ol=i(n=>{let e=n.headers.get("x-real-ip")??n.headers.get("true-client-ip")??n.headers.get("cf-connecting-ip");if(e)return e;let t=n.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP");function Rt(n,e){return{function:_l(e,"RateLimitInboundPolicy",n),user:kl,ip:Al,all:Ll}[e.rateLimitBy??"ip"]}i(Rt,"getRateLimitByFunctions");var Al=i(async n=>({key:`ip-${Ol(n)}`}),"getIP"),kl=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),Ll=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll");function _l(n,e,t){let r;if(n.rateLimitBy==="function"){if(!n.identifier)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=n.identifier.module[n.identifier.export],!r||typeof r!="function")throw new m(`${e} '${t}' - Custom rate limit function must be a valid function`)}return i(async(s,a,u)=>{let c=await r(s,a,u);if(!c||typeof c!="object"){let l=`${e} '${u}' - Custom rate limit function must return a valid object.`;throw a.log.error(l),new A(l)}if(!("key"in c)){let l=`${e} '${u}' - Custom rate limit function must return a valid key property.`;throw a.log.error(l,c),new A(l)}if(typeof c.key!="string"){let l=`${e} '${u}' - Custom rate limit function must return a valid key property of type string. Received type '${typeof c.key}'`;throw a.log.error(l),new A(l)}return c},"outerFunction")}i(_l,"wrapUserFunction");var Pt="Retry-After";var wa=he("zuplo:policies:ComplexRateLimitInboundPolicy"),Yo=Symbol("complex-rate-limit-counters"),Xo=class n extends ae{static{i(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let r=oe.get(e,Yo)??{};Object.assign(r,t),oe.set(e,Yo,t)}static getIncrements(e){return oe.get(e,Yo)??{}}constructor(e,t){super(e,t),g("policy.inbound.complex-rate-limit-inbound"),K(e,t).required("rateLimitBy","string").required("timeWindowMinutes","number").required("limits","object").optional("headerMode","string").optional("throwOnFailure","boolean").optional("mode","string").optional("identifier","object"),e.identifier&&K(e.identifier,t,"policy","identifier").required("export","string").required("module","object");for(let[r,o]of Object.entries(e.limits))if(typeof o!="number")throw new m(`ComplexRateLimitInboundPolicy '${this.policyName}' - The value of the limits must be numbers. The limit ${r} is set to type '${typeof e}'.`)}async handler(e,t){let r=Date.now(),o=Q.getLogger(t),s=Qe(this.policyName,o),a=i((c,l)=>{if(this.options.throwOnFailure)throw new W(c,{cause:l});o.error(c,l)},"throwOrLog"),u=i((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[Pt]=l.toString()),x.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l=await Rt(this.policyName,this.options)(e,t,this.policyName),d=f.instance.isTestMode||f.instance.isWorkingCopy?f.instance.build.BUILD_ID:"",p=Object.assign({},this.options.limits,l.limits),h=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;t.addResponseSendingFinalHook(async()=>{try{let v=n.getIncrements(t);wa(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(v)}`);let N=Object.entries(p).map(([j])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${j}`,ttlSeconds:h,increment:v[j]??0})),k=s.multiIncrement(N,t.requestId);t.waitUntil(k),await k}catch(v){o.error(v),t.log.error(v)}});let y=Object.entries(p).map(([v,N])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${v}`,ttlSeconds:h,limit:N})),O=await s.multiCount(y,t.requestId);return Nl(O,y).length>0?u(this.options.headerMode??"retry-after",h):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-r;wa(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function Nl(n,e){let t=[];for(let r of n){let o=e.find(s=>s.key===r.key)?.limit||0;r.count>=o&&t.push(r)}return t}i(Nl,"findOverLimits");var Dl=i(async(n,e,t,r)=>{if(g("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new m(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=ge.instance,s=Ht(t.policies,o?.routeData.policies);return Zr(s)(n,e)},"CompositeInboundPolicy");var Ml=i(async(n,e,t,r,o)=>{if(g("policy.outbound.composite"),!r.policies||r.policies.length===0)throw new m(`CompositeOutboundPolicy '${o}' must have valid policies defined`);let s=ge.instance,a=Zt(r.policies,s?.routeData.policies);return $r(a)(n,e,t)},"CompositeOutboundPolicy");var ql=i(async(n,e,t,r)=>{g("policy.inbound.curity-phantom-token-auth");let o=n.headers.get("Authorization");if(!o)return x.unauthorized(n,e,{detail:"No authorization header"});let s=Ul(o);if(!s)return x.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await se(r,void 0,t),u=new re(a,e),c=await u.get(s);if(!c){let l=await Z.fetch(t.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${t.clientId}:${t.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(s,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),x.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):x.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function Ul(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(Ul,"getToken");var Hl=i(async(n,e,t,r)=>(g("policy.inbound.firebase-jwt-auth"),K(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),Re(n,e,{issuer:`https://securetoken.google.com/${t.projectId}`,audience:t.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var Zl=i(async(n,e,t)=>{g("policy.inbound.form-data-to-json");let r="application/x-www-form-urlencoded",o="multipart/form-data",s=n.headers.get("content-type")?.toLowerCase();if(!s||![o,r].includes(s))return t&&t.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):n;let a=await n.formData();if(t&&t.optionalHoneypotName&&a.get(t.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(n.headers);return c.set("content-type","application/json"),c.delete("content-length"),new te(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var It="__unknown__",$l=i(async(n,e,t,r)=>{g("policy.inbound.geo-filter");let o={allow:{countries:xt(t.allow?.countries,"allow.countries",r),regionCodes:xt(t.allow?.regionCodes,"allow.regionCode",r),asns:xt(t.allow?.asns,"allow.asOrganization",r)},block:{countries:xt(t.block?.countries,"block.countries",r),regionCodes:xt(t.block?.regionCodes,"block.regionCode",r),asns:xt(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??It,a=e.incomingRequestProperties.regionCode?.toLowerCase()??It,u=e.incomingRequestProperties.asn?.toString()??It,c=o.ignoreUnknown&&s===It,l=o.ignoreUnknown&&a===It,d=o.ignoreUnknown&&u===It,p=o.allow.countries,h=o.allow.regionCodes,y=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||h.length>0&&!h.includes(a)&&!l||y.length>0&&!y.includes(u)&&!d)return Et(n,e,r,s,a,u);let O=o.block.countries,P=o.block.regionCodes,v=o.block.asns;return O.length>0&&O.includes(s)&&!c||P.length>0&&P.includes(a)&&!l||v.length>0&&v.includes(u)&&!d?Et(n,e,r,s,a,u):n},"GeoFilterInboundPolicy");function Et(n,e,t,r,o,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${s}')`),x.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:s}})}i(Et,"blockedResponse");function xt(n,e,t){if(typeof n=="string")return n.split(",").map(r=>r.trim().toLowerCase());if(typeof n>"u")return[];if(Array.isArray(n))return n.map(r=>r.trim().toLowerCase());throw new m(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}i(xt,"toLowerStringArray");var Fl=i(async(n,e,t)=>{g("policy.inbound.jwt-scope-validation");let r=n.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(r,t.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var jl=i(async(n,e,t,r)=>{g("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return ei(r,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(o),a=[];if(s.length===0)return ei(r,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(h=>{a.push({responseName:u,contentName:l,exampleName:h,exampleValue:d[h]})})})}),a=a.filter(u=>!(t.responsePrefixFilter&&!u.responseName.startsWith(t.responsePrefixFilter)||t.contentType&&u.contentName!==t.contentType||t.exampleName&&u.exampleName!==t.exampleName)),t.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return Ra(a[u])}else return a.length>0?Ra(a[0]):ei(r,n,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function Ra(n){let e=JSON.stringify(n.exampleValue,null,2),t=new Headers;switch(t.set("Content-Type",n.contentName),n.responseName){case"1XX":return new Response(e,{status:100,headers:t});case"2XX":return new Response(e,{status:200,headers:t});case"3XX":return new Response(e,{status:300,headers:t});case"4XX":return new Response(e,{status:400,headers:t});case"5XX":case"default":return new Response(e,{status:500,headers:t});default:return new Response(e,{status:Number(n.responseName),headers:t})}}i(Ra,"generateResponse");var ei=i((n,e,t,r)=>{let o=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${r}`;return x.internalServerError(e,t,{detail:o})},"getProblemDetailResponse");var zl="Incoming",Bl={logRequestBody:!0,logResponseBody:!0};function Pa(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}i(Pa,"headersToObject");function Ia(){return new Date().toISOString()}i(Ia,"timestamp");var ti=new WeakMap,Gl={};function Vl(n,e){let t=ti.get(n);t||(t=Gl);let r=Object.assign({...t},e);ti.set(n,r)}i(Vl,"setMoesifContext");async function Ea(n,e){let t=n.headers.get("content-type");if(t&&t.indexOf("json")!==-1)try{return await n.clone().json()}catch(o){e.log.error(o)}let r=await n.clone().text();return e.log.debug({textBody:r}),r}i(Ea,"readBody");var Wl={},ni;function xa(){if(!ni)throw new A("Invalid State - no _lastLogger");return ni}i(xa,"getLastLogger");function Kl(n){let e=Wl[n];return e||(e=new Y("moesif-inbound",100,async t=>{let r=JSON.stringify(t);xa().debug("posting",r);let o=await Z.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||xa().error({status:o.status,body:await o.text()})})),e}i(Kl,"getDispatcher");async function Jl(n,e,t,r){g("policy.inbound.moesif-analytics"),ni=e.log;let o=Ia(),s=Object.assign(Bl,t);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await Ea(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Kl(s.applicationId),d=n.headers.get("true-client-ip"),p=ti.get(e)??{},h={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Pa(n.headers)},y=s.logResponseBody?await Ea(u,e):void 0,O={time:Ia(),status:u.status,headers:Pa(u.headers),body:y},P={request:h,response:O,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:zl};l.enqueue(P),e.waitUntil(l.waitUntilFlushed())}),n}i(Jl,"MoesifInboundPolicy");async function Ta(n,e,t,r){let o=Q.getLogger(n),{authApiJWT:s,meteringServiceUrl:a}=f.instance,u;try{let l=await Z.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription`,l)}let c=u&&u.data&&u.data.length>0?u.data:void 0;return c&&c.length>1?c.sort((d,p)=>d.createdOn>p.createdOn?-1:1)[0]:c&&c[0]}i(Ta,"loadSubscription");async function va(n,e,t,r,o){let{authApiJWT:s,meteringServiceUrl:a}=f.instance,u=Q.getLogger(n);try{let c=await Z.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`,c)}}i(va,"consumeSubcriptionQuotas");var Ql=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function Un(n,e){try{let t=[];for(let r in n)typeof n[r]!="number"&&!(Number.isInteger(n[r])&&/^-?\d+$/.test(n[r].toString()))&&t.push(r);if(t.length>0)throw new m(t.length>1?`The values found in these properties are not integers : ${t.join(", ")}`:`The value in property '${t[0]}' is not an integer`)}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}i(Un,"validateMeters");function Ca(n,e){if(n)try{if(n.length===0)throw new m("Must set valid subscription statuses");let t=ot(n),r=[];for(let o of t)Ql.has(o)||r.push(o);if(r.length>0)throw new m(`Found the following invalid statuses: ${r.join(", ")}`);return n}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}i(Ca,"parseAllowedSubscriptionStatuses");function Sa(n,e){let t={},r={};for(let o in e)n.hasOwnProperty(o)?t[o]=e[o]:r[o]=e[o];return{metersInSubscription:t,metersNotInSubscription:r}}i(Sa,"compareMeters");var ri=class extends ae{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return oe.get(e,At)}static setMeters(e,t){Un(t,"setMeters");let r=oe.get(e,kt)??{};Object.assign(r,t),oe.set(e,kt,r)}constructor(e,t){super(e,t),g("policy.inbound.monetization")}async handler(e,t){K(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let r=this.options.allowRequestsOverQuota??!1,o=Be(this.options.meterOnStatusCodes),s=oe.get(t,kt),a={...this.options.meters,...s};Un(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=Ca(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(P,v,N)=>{let k=oe.get(N,At);if((this.options.allowRequestsWithoutSubscription??!1)&&!k){N.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let q=oe.get(N,kt),$={...this.options.meters,...q};if(Un($,this.policyName),o.includes(P.status)&&k&&$){N.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${k.id}' with meters '${JSON.stringify($)} on response status '${P.status}'`);let{metersInSubscription:E,metersNotInSubscription:U}=Sa(k.meters,$);if(U&&Object.keys(U).length>0){let G=Object.keys(U);N.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${G}'`)}await va(N,k.id,this.policyName,this.options.bucketId,E)}});let l=e.user;if(!l)return u?e:x.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await Ta(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:x.unauthorized(e,t,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return t.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),x.unauthorized(e,t,{detail:"No valid subscription found"});c.includes(p.status)&&(t.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),oe.set(t,At,p));let h=oe.get(t,At);if(!h)return u?e:(t.log.warn("Subscription is not available for user"),x.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(h&&Object.keys(h.meters).length===0)return t.log.error(`Quota is not set up for subscription '${h.id}'`),x.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let O=Object.keys(a).filter(P=>!Object.keys(h.meters).includes(P));if(O.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${O.join(", ")}`),x.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${O.join(", ")}`,title:"Quota Exceeded"});for(let P of Object.keys(a))if(h.meters[P].available<=0&&!r)return x.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${P}'`,title:"Quota Exceeded"});return e}};async function Hn(n,e){let t=new URLSearchParams({client_id:n.clientId,client_secret:n.clientSecret,grant_type:"client_credentials"});n.scope&&t.append("scope",n.scope),n.audience&&t.append("audience",n.audience);let r=await ye({retries:n.retries?.maxRetries??3,retryDelayMs:n.retries?.delayMs??10},n.tokenEndpointUrl,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let s=await r.text();e.log.error(`Error getting token from identity provider. Status: ${r.status}`,s)}catch{}throw new A("Error getting token from identity provider.")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new A("Response returned from identity provider is not in the expected format.")}i(Hn,"getClientCredentialsAccessToken");var Tt=class extends Error{constructor(t,r,o){super(r,o);this.code=t}static{i(this,"OpenFGAError")}},Zn=class{static{i(this,"BaseOpenFGAClient")}apiUrl;storeId;authorizationModelId;constructor(e){this.apiUrl=e.apiUrl,this.storeId=e.storeId,this.authorizationModelId=e.authorizationModelId}getStoreId(e={},t=!1){let r=e?.storeId||this.storeId;if(!t&&!r)throw new Error("storeId is required");return r}getAuthorizationModelId(e={}){return e?.authorizationModelId||this.authorizationModelId}async get(e,t){return this.fetch(e,"GET",t)}async put(e,t,r){return this.fetch(e,"PUT",r,t)}post(e,t,r){return this.fetch(e,"POST",r,t)}async fetch(e,t,r,o){let s=new Headers(r.headers||{});s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.set("User-Agent",f.instance.systemUserAgent);let a=`${this.apiUrl}${e}`,u=new Request(a,{method:t,headers:s,body:o?JSON.stringify(o):void 0}),c=await Z.fetch(u);if(c.status!==200){let l;try{l=await c.json()}catch{}throw!l||!l.code||!l.message?new Tt("unknown",`Unknown error. Status: ${c.status}`):new Tt(l.code,l.message)}return c.json()}};function Qt(n,e,t){!n[e]&&t&&(n[e]=t)}i(Qt,"setHeaderIfNotSet");var Oa="X-OpenFGA-Client-Method",Aa="X-OpenFGA-Client-Bulk-Request-Id",Yt=class extends Zn{static{i(this,"OpenFGAClient")}async check(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/check`,{tuple_key:{user:e.user,relation:e.relation,object:e.object},context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]},authorization_model_id:this.getAuthorizationModelId(t)},t)}async batchCheck(e,t={}){let{headers:r={}}=t;return Qt(r,Oa,"BatchCheck"),Qt(r,Aa,crypto.randomUUID()),{responses:await Promise.all(e.map(async s=>this.check(s,Object.assign({},t,r)).then(a=>(a._request=s,a)).catch(a=>{if(a instanceof Tt)throw a;return{allowed:void 0,error:a,_request:s}})))}}async expand(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/expand`,{authorization_model_id:this.getAuthorizationModelId(t),tuple_key:e},t)}async listObjects(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-objects`,{authorization_model_id:this.getAuthorizationModelId(t),user:e.user,relation:e.relation,type:e.type,context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]}},t)}async listRelations(e,t={}){let{user:r,object:o,relations:s,contextualTuples:a,context:u}=e,{headers:c={}}=t;if(Qt(c,Oa,"ListRelations"),Qt(c,Aa,crypto.randomUUID()),!s?.length)throw new Error("When calling listRelations, at least one relation must be passed in the relations field");let l=await this.batchCheck(s.map(p=>({user:r,relation:p,object:o,contextualTuples:a,context:u})),Object.assign({},t,c)),d=l.responses.find(p=>p.error);if(d)throw d.error;return{relations:l.responses.filter(p=>p.allowed).map(p=>p._request.relation)}}async listUsers(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-users`,{authorization_model_id:this.getAuthorizationModelId(t),relation:e.relation,object:e.object,user_filters:e.user_filters,context:e.context,contextual_tuples:e.contextualTuples||[]},t)}};var ka=Symbol("openfga-authz-context-data"),vt=class extends ae{static{i(this,"BaseOpenFGAAuthZInboundPolicy")}client;authorizer;cache;static setContextChecks(e,t){let r=Array.isArray(t)?t:[t];oe.set(e,ka,r)}constructor(e,t){if(super(e,t),K(e,t).required("apiUrl","string").optional("storeId","string").optional("authorizationModelId","string"),!e.credentials)throw new m(`${this.policyType} '${this.policyName}' - The 'credentials' option is required.`);if(e.credentials.method==="client-credentials")K(e.credentials,t).required("clientId","string").required("clientSecret","string").required("oauthTokenEndpointUrl","string").optional("apiAudience","string");else if(e.credentials.method==="api-token")K(e.credentials,t).required("token","string").optional("headerName","string").optional("headerValuePrefix","string");else if(e.credentials.method==="header")K(e.credentials,t).optional("headerName","string");else if(e.credentials.method!=="none")throw new m(`${this.policyType} '${this.policyName}' - The 'credentials.type' option is invalid. It must be set to either 'none', 'api-token', 'client-credentials', or 'header'.`);this.authorizer=this.getAuthorizer(e.credentials),this.client=new Yt({apiUrl:e.apiUrl,storeId:e.storeId,authorizationModelId:e.authorizationModelId})}async handler(e,t){if(!this.cache){let a=await se(this.policyName,void 0,this.options);this.cache=new re(a,t)}let r=i(a=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=oe.get(t,ka);if(!o||o.length===0)throw new A(`${this.policyType} '${this.policyName}' - No checks found in the context.`);let s=await this.authorizer(e,t);try{t.log.debug("OpenFGA checks",o);let a=await this.client.batchCheck(o,{headers:s});return t.log.debug("OpenFGA Response",a),a.responses.every(u=>u.allowed)?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling OpenFGA service`,a),x.internalServerError(e,t)}}getAuthorizer(e){if(e.method==="none")return async()=>({});if(e.method==="header")return async t=>{let r=e.headerName??"Authorization",o=t.headers.get(r);if(!o)throw new W(`${this.policyType} '${this.policyName}' - The header '${r}' is missing.`);return{[r]:o}};if(e.method==="api-token")return async()=>({[e.headerName??"Authorization"]:`${e.headerValuePrefix??"Bearer "} ${e.token}`});if(e.method==="client-credentials")return async(t,r)=>{let o=await this.cache?.get("client_credentials_token");if(o)return{Authorization:`Bearer ${o}`};let s=await Hn({tokenEndpointUrl:e.oauthTokenEndpointUrl,clientId:e.clientId,clientSecret:e.clientSecret,audience:e.apiAudience},r);return this.cache?.put("client_credentials_token",s.access_token,s.expires_in),{Authorization:`Bearer ${s.access_token}`}};throw new A("Invalid state for credentials method is not valid. This should not happen.")}};var La=["us1","eu1","au1"],oi=class extends vt{static{i(this,"OktaFGAAuthZInboundPolicy")}constructor(e,t){if(!La.includes(e.region))throw new m(`OktaFGAAuthZInboundPolicy '${t}' - The 'region' option is invalid. Must be one of ${La.join(", ")}.`);let r={...e,apiUrl:`https://api.${e.region}.fga.dev`,credentials:{method:"client-credentials",oauthTokenEndpointUrl:"https://fga.us.auth0.com/oauth/token",clientId:e.credentials.clientId,clientSecret:e.credentials.clientSecret,apiAudience:`https://api.${e.region}.fga.dev/`}};super(r,t),g("policy.inbound.oktafga-authz")}};var Yl=i(async(n,e,t,r)=>(g("policy.inbound.okta-jwt-auth"),Re(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"OktaJwtInboundPolicy");var ii=class extends vt{static{i(this,"OpenFGAAuthZInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.openfga-authz")}};import{importSPKI as Xl}from"jose";var si,ed=i(async(n,e,t,r)=>{if(g("policy.inbound.propel-auth-jwt-auth"),!si)try{si=await Xl(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return Re(n,e,{issuer:t.authUrl,secret:si,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var ai="quota-inbound-policy-f307056c-8c00-4f2c-b4ac-c0ac7d04eca0",_a="quota-usage-2017e968-4de8-4a63-8951-1e423df0d64b";var ui=class n extends ae{static{i(this,"QuotaInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.quota")}async handler(e,t){let r=this.options.debug??!1;t.log.debug({debug:r}),K(this.options,this.policyName).required("period","string").required("quotaBy","string").optional("quotaAnchorMode","string").optional("allowances","object"),n.setMeters(t,{requests:1});let o=Q.getLogger(t);try{let s=td(this.options,this.policyName),a=s.functions.getAnchorDate(e,t,this.policyName),u=s.functions.getQuotaDetail(e,t,this.policyName),[c,l]=await Promise.all([a,u]),d=nd(l.key,this.policyName);r&&t.log.debug(`QuotaInboundPolicy: key - '${d}'`);let p=Qe(this.policyName,o),h=await p.getQuota(d,t.requestId);n.#e(t,this.policyName,h),r&&t.log.debug("QuotaInboundPolicy: quotaResult",h),c&&new Date(h.anchorDate)!==c&&t.log.warn(`QuotaInboundPolicy '${this.policyName}' provided anchorDate ('${c}') did not match the stored, immutable anchorDate ('${h.anchorDate}')`);let y=Object.assign({},s.defaultAllowances);Object.assign(y,l.allowances);let O=[],P="";if(Object.entries(y).forEach(([v,N])=>{r&&(P+=`${v} - allowed: ${N} value: ${h.meters[v]??0}
72
- `),(h.meters[v]??0)>=N&&O.push(v)}),r&&t.log.debug("QuotaInboundPolicy: debugTable",P),O.length>0)return x.tooManyRequests(e,t,{detail:`Quota exceeded for meters '${O.join(", ")}'`});t.addResponseSendingFinalHook(async(v,N,k)=>{if(r&&k.log.debug(`QuotaInboundPolicy: backend response - ${v.status}: ${v.statusText}`),!s.quotaOnStatusCodes.includes(v.status))return;let j=oe.get(k,ai),q={config:{period:s.period,anchorDate:c?.toISOString()??""},increments:j};r&&k.log.debug("QuotaInboundPolicy: setQuotaDetails",q);let $=p.setQuota(d,q,k.requestId);k.waitUntil($)})}catch(s){o.error(s),t.log.error(s)}return e}static setMeters(e,t){let r=oe.get(e,ai)??{};Object.assign(r,t),oe.set(e,ai,r)}static getUsage(e,t){let r=oe.get(e,`${_a}-${t}`);if(r===void 0)throw new A(`QuotaInboundPolicy.getUsage was called for policy named '${t}' but the policy itself has not yet executed.`);return r}static#e(e,t,r){oe.set(e,`${_a}-${t}`,r)}};function td(n,e){let t=i(async s=>({key:`user-1385b4e8-800f-488e-b089-c197544e5801-${s.user?.sub}`,allowances:n.allowances??{}}),"getQuotaDetail"),r=i(async()=>{},"getAnchorDate");if(n.quotaBy==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getQuotaDetailExport===void 0)throw new m(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getQuotaDetailExport' is required when 'quotaBy' is 'function'`);t=n.identifier.module[n.identifier.getQuotaDetailExport]}if(n.quotaAnchorMode==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getAnchorDateExport===void 0)throw new m(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getAnchorDateExport' is required when 'quotaAnchorMode' is 'function'`);r=n.identifier.module[n.identifier.getAnchorDateExport]}return{period:n.period,quotaBy:n.quotaBy??"user",quotaAnchorMode:n.quotaAnchorMode??"first-api-call",quotaOnStatusCodes:Be(n.quotaOnStatusCodes??"200-299"),defaultAllowances:Object.assign({},n.allowances),functions:{getQuotaDetail:t,getAnchorDate:r}}}i(td,"validateAndParseOptions");function nd(n,e){return encodeURIComponent(`${e}-${n}`)}i(nd,"processKey");var Na=he("zuplo:policies:RateLimitInboundPolicy"),Da=i(async(n,e,t,r)=>{let o=Q.getLogger(e),s=i(($,E)=>{let U={};return(!$||$==="retry-after")&&(U[Pt]=E.toString()),x.tooManyRequests(n,e,void 0,U)},"rateLimited"),u=await Rt(r,t)(n,e,r),c=u.key,l=u.requestsAllowed??t.requestsAllowed,d=u.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",h=Qe(r,o),O=`rate-limit${f.instance.isTestMode?f.instance.build.BUILD_ID:""}/${r}/${c}`,P=await se(r,void 0,t),v=new re(P,e),N=h.getCountAndUpdateExpiry(O,d,e.requestId),k;i(async()=>{let $=await N;if($.count>l){let E=Date.now()+$.ttlSeconds*1e3;v.put(O,E,$.ttlSeconds),Na(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${O}' (async mode)`),k=s(p,$.ttlSeconds)}},"asyncCheck")();let q=await v.get(O);if(q!==void 0&&q>Date.now()){Na(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${O}' (async mode)`);let $=Math.round((q-Date.now())/1e3);return s(p,$)}return e.addResponseSendingHook(async $=>k??$),n},"AsyncRateLimitInboundPolicyImpl");var Ma=he("zuplo:policies:RateLimitInboundPolicy"),rd="strict",qa=i(async(n,e,t,r)=>{if(g("policy.inbound.rate-limit"),(t.mode??rd)==="async")return Da(n,e,t,r);let s=Date.now(),a=Q.getLogger(e),u=i((l,d)=>{if(t.throwOnFailure)throw new W(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[Pt]=d.toString()),x.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await Rt(r,t)(n,e,r),p=d.key,h=d.requestsAllowed??t.requestsAllowed,y=d.timeWindowMinutes??t.timeWindowMinutes,O=t.headerMode??"retry-after",P=Qe(r,a),N=`rate-limit${f.instance.isTestMode||f.instance.isWorkingCopy?f.instance.build.BUILD_ID:""}/${r}/${p}`,k=await P.getCountAndUpdateExpiry(N,y,e.requestId);return k.count>h?(Ma(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${N}' (strict mode)`),c(O,k.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-s;Ma(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var ci;function Ua(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}i(Ua,"headersToNameValuePairs");function od(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}i(od,"queryToNameValueParis");function id(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}i(id,"parseIntOrUndefined");var Ha={};async function sd(n,e,t,r){g("policy.inbound.readme-metrics");let o=new Date,s=Date.now();return ci||(ci={name:"zuplo",version:f.instance.build.ZUPLO_VERSION,comment:`zuplo/${f.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?rt(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?rt(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:f.instance.isWorkingCopy||f.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:ci,entries:[{startedDateTime:o.toISOString(),time:Date.now()-s,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:Ua(n.headers),queryString:od(n.query)},response:{status:a.status,statusText:a.statusText,headers:Ua(a.headers),content:{size:id(n.headers.get("content-length"))}}}]}}},d=Ha[t.apiKey];if(!d){let p=t.apiKey;d=new Y("readme-metering-inbound-policy",10,async h=>{try{let y=t.url??"https://metrics.readme.io/request",O=await Z.fetch(y,{method:"POST",body:JSON.stringify(h),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});O.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${O.status}: '${await O.text()}'`)}catch(y){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${y.message}'`),y}}),Ha[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}i(sd,"ReadmeMetricsInboundPolicy");var ad=i(async(n,e,t,r)=>{g("policy.inbound.remove-headers");let o=t?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new m(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let s=new Headers(n.headers);return o.forEach(u=>{s.delete(u)}),new te(n,{headers:s})},"RemoveHeadersInboundPolicy");var ud=i(async(n,e,t,r,o)=>{g("policy.outbound.remove-headers");let s=r?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new m(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(n.headers);return s.forEach(c=>{a.delete(c)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var cd=i(async(n,e,t,r)=>{g("policy.inbound.remove-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length===0)throw new m(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let s=new URL(n.url);return o.forEach(u=>{s.searchParams.delete(u)}),new te(s.toString(),n)},"RemoveQueryParamsInboundPolicy");var ld=i(async(n,e,t,r)=>{g("policy.outbound.replace-string");let o=await n.text(),s=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(s,r.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var Za=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),dd=i(async(n,e,t)=>{g("policy.inbound.request-size-limit");let r=t.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(n.method))return n;let o=n.headers.get("content-length"),s=o!==null?parseInt(o):void 0;return s&&!isNaN(s)&&s>t.maxSizeInBytes?Za():s&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?Za():n},"RequestSizeLimitInboundPolicy");var Ct=i(n=>{let e=n.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),St=i((n,e,t,r,o)=>{let s=[],a=!0,u=[];return n.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,s.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=Bn(t,r,o,c.name),p=ge.instance.schemaValidator[d],h=p(e[c.name]),y=li(p.errors);h||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${y.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),Ae=i((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),ke=i(n=>n==="log-only"||n==="reject-and-log","shouldLog"),Le=i(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),li=i(n=>n?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function $a(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(y){let O=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,P=x.badRequest(e,n,{detail:`${O}, see errors property for more details`,errors:`${y}`});if(ke(t.validateBody)&&Ae(n,t.logLevel??"info",O,[r],y),Le(t.validateBody))return P}if(!e.headers.get("Content-Type")){let y=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,O=x.badRequest(e,n,{detail:y});return ke(t.validateBody)&&Ae(n,t.logLevel??"info",y,[r],[y]),Le(t.validateBody)?O:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=Gn(n.route.path,e.method,o),u=ge.instance.schemaValidator[a];if(!u){let y=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,O=x.badRequest(e,n,{detail:y});return ke(t.validateBody)&&Ae(n,t.logLevel??"info",y,[r],[y]),Le(t.validateBody)?O:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=li(l),h=x.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(ke(t.validateBody)&&Ae(n,t.logLevel??"info",d,[r],p),Le(t.validateBody))return h}i($a,"handleBodyValidation");function Fa(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Ct(n),s=St(o.filter(a=>a.location==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=x.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:s.errors});if(ke(t.validateHeaders)&&Ae(n,t.logLevel??"info",a,s.invalidValues,s.errors),Le(t.validateHeaders))return u}}i(Fa,"handleHeadersValidation");function ja(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=Ct(n),o=St(r.filter(s=>s.location==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let s="Path parameters validation failed",a=x.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(ke(t.validatePathParameters)&&Ae(n,t.logLevel??"info",s,o.invalidValues,o.errors),Le(t.validatePathParameters))return a}}i(ja,"handlePathParameterValidation");function za(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=Ct(n),o=St(r.filter(s=>s.location==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let s="Query parameters validation failed",a=x.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(ke(t.validateQueryParameters)&&Ae(n,t.logLevel??"info",s,o.invalidValues,o.errors),Le(t.validateQueryParameters))return a}}i(za,"handleQueryParameterValidation");var Ba=i(async(n,e,t)=>{g("policy.inbound.request-validation");let r=za(e,n,t);if(r!==void 0||(r=ja(e,n,t),r!==void 0)||(r=Fa(e,n,t),r!==void 0))return r;let o=await $a(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),pd=Ba;var md=i(async(n,e,t,r)=>{if(g("policy.inbound.require-origin"),t.origins===void 0||t.origins.length===0)throw new m(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof t.origins=="string"?t.origins.split(","):t.origins;o=o.map(a=>a.trim());let s=n.headers.get("origin");if(!s||!o.includes(s)){let a=t.failureDetail??"Forbidden";return x.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var gd=i(async(n,e,t)=>(g("policy.inbound.set-body"),new te(n,{body:t.body})),"SetBodyInboundPolicy");var fd=i(async(n,e,t,r)=>{g("policy.inbound.set-headers");let o=t.headers;if(!o||!Array.isArray(o)||o.length==0)throw new m(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let s=new Headers(n.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.has(u.name)||c)&&s.set(u.name,u.value)}),new te(n,{headers:s})},"SetHeadersInboundPolicy");var hd=i(async(n,e,t,r,o)=>{g("policy.outbound.set-headers");let s=r.headers;if(!s||!Array.isArray(s)||s.length==0)throw new m(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return s.forEach(c=>{if(!c.name||c.name.length===0)throw new m(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"SetHeadersOutboundPolicy");var yd=i(async(n,e,t,r)=>{g("policy.inbound.set-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length==0)throw new m(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let s=new URL(n.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.searchParams.has(u.name)||c)&&s.searchParams.set(u.name,u.value)}),new te(s.toString(),n)},"SetQueryParamsInboundPolicy");var bd=i(async(n,e,t,r,o)=>{if(g("policy.outbound.set-status"),!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(n.body,{headers:n.headers,status:r.status,statusText:r.statusText??n.statusText})},"SetStatusOutboundPolicy");var wd=i(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),Rd=i(async(n,e,t,r)=>{if(g("policy.inbound.sleep"),!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new m(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await wd(t.sleepInMs),n},"SleepInboundPolicy");var Pd=i(async(n,e,t,r)=>{g("policy.inbound.supabase-jwt-auth"),K(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},s=await Re(n,e,o,r);if(s instanceof Response)return s;if(!(s instanceof te))throw new W("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return s;let u=n.user?.data.app_metadata;if(!u)throw new A(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?x.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var Id=i(async(n,e,t,r)=>{g("policy.inbound.upstream-azure-ad-service-auth"),K(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await se(r,void 0,t),s=new re(o,e),a=await s.get(r);if(!a){let u=await Ed(t,e);s.put(r,u.access_token,u.expires_in-(t.expirationOffsetSeconds??300)),a=u.access_token}return n.headers.set("Authorization",`Bearer ${a}`),n},"UpstreamAzureAdServiceAuthInboundPolicy");async function Ed(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await ye({retries:n.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${n.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let s=await r.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new A("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new A("Response returned from Azure AD is not in the expected format.")}i(Ed,"getAccessToken");var Ga="https://accounts.google.com/o/oauth2/token",di,xd=i(async(n,e,t,r)=>{g("policy.inbound.upstream-firebase-admin-auth"),K(t,r).required("serviceAccountJson","string"),di||(di=await Te.init(t.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},s=await se(r,void 0,t),a=new re(s,e),u=await a.get(r);if(!u){let c=await Ne({serviceAccount:di,audience:Ga,payload:o}),l=await wn(Ga,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new A("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var Td="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",vd=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],pi,Cd=i(async(n,e,t,r)=>{if(g("policy.inbound.upstream-firebase-user-auth"),K(t,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!t.userId&&!t.userIdPropertyPath)throw new m(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof t.developerClaims<"u"){for(let p in t.developerClaims)if(Object.prototype.hasOwnProperty.call(t.developerClaims,p)){if(vd.indexOf(p)!==-1)throw new m(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}pi||(pi=await Te.init(t.serviceAccountJson));let s=t.userId;if(!s&&!t.userIdPropertyPath){if(!n.user)throw new A("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new A(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=rt(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new A(`Unable to determine user from for the policy ${r}`);let a=await se(r,void 0,t),u=new re(a,e),c={uid:s,claims:o},l=await at(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await Ne({serviceAccount:pi,audience:Td,payload:c}),h=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,y=await qs(h,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!y.idToken)throw new A("Invalid token response from Firebase");d=y.idToken,u.put(l,d,(y.expiresIn?parseInt(y.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var Xt=class{static{i(this,"ZuploServices")}static async getIDToken(e,t){let r=new re("0c13603a-a19f-4f03-a04a-50aa393f7ffa-zuplo-tokens",e),o=await se("zuplo-token",void 0,t),s=await r.get(o);if(s)return s;let{authClientId:a,authClientSecret:u,developerApiUrl:c,zuploClientAuthBucketId:l}=f.instance;if(!a||!u)throw new A("Zuplo service authentication is not enabled for this deployment. Contact support assistance.");let d=await Hn({tokenEndpointUrl:`${c}/v1/client-auth/${l}/oauth/token`,clientId:a,clientSecret:u,audience:t?.audience},e);return r.put(o,d.access_token,d.expires_in-300),d.access_token}};var Va="service-account-id-token",mi=class extends ae{static{i(this,"UpstreamGcpFederatedAuthInboundPolicy")}cacheName;normalizedWorkloadIdentityProvider;constructor(e,t){super(e,t),g("policy.inbound.upstream-gcp-federated-auth"),K(e,t).required("audience","string").required("serviceAccountEmail","string").required("workloadIdentityProvider","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number").optional("useMemoryCacheOnly","boolean").optional("tokenLifetime","number"),e.workloadIdentityProvider.startsWith("https://iam.googleapis.com/")?this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider.replace("https://iam.googleapis.com/",""):this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider}async handler(e,t){this.cacheName||(this.cacheName=await se(this.policyName,void 0,this.options));let r;this.options.useMemoryCacheOnly?r=new Fe(this.cacheName):r=new re(this.cacheName,t);let o=await r.get(Va);if(!o){let s=`https://iam.googleapis.com/${this.normalizedWorkloadIdentityProvider}`,a=await Xt.getIDToken(t,{audience:s}),u=await Ds(this.normalizedWorkloadIdentityProvider,a,{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!u.access_token||!u.expires_in)throw new A("Invalid token response from GCP");let c=u.access_token,l=await Ms({serviceAccountEmailOrIdentifier:this.options.serviceAccountEmail,audience:this.options.audience,accessToken:c},{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!l.token)throw new A("Invalid token response from GCP");o=l.token,r.put(Va,c,3600-(this.options.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${o}`),e}};var gi,Sd=i(async(n,e,t,r)=>{g("policy.inbound.upstream-gcp-jwt"),K(t,r).required("audience","string").required("serviceAccountJson","string"),gi||(gi=await Te.init(t.serviceAccountJson));let o=await Ne({serviceAccount:gi,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var Wa="https://www.googleapis.com/oauth2/v4/token",fi,Od=i(async(n,e,t,r)=>{g("policy.inbound.upstream-gcp-service-auth"),K(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),fi||(fi=await Te.init(t.serviceAccountJson));let o={};if(t.scopes&&t.audience)throw new m("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let c=ot(t.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof m?new m(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}t.audience&&(o.target_audience=`${t.audience}`);let s=await se(r,void 0,t),a;t.useMemoryCacheOnly?a=new Fe(s):a=new re(s,e);let u=await a.get(r);if(!u){let c=await Ne({serviceAccount:fi,audience:Wa,payload:o}),l=await wn(Wa,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new A("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new A("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var Ad=i(async(n,e,t)=>{g("policy.inbound.validate-json-schema");let r=n.clone(),o;try{o=await r.json()}catch{return x.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator.default(o))return n;let{errors:a}=t.validator.default;if(!a)throw new W("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return x.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var Ka=i(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=i((P,v)=>e(P,"name",{value:v,configurable:!0}),"__name"),o=i((P,v)=>i(function(){return v||(0,P[t(P)[0]])((v={exports:{}}).exports,v),v.exports},"__require"),"__commonJS"),s=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(P){var v={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:i(function(k,j){return j},"tagValueProcessor"),attributeValueProcessor:i(function(k,j){return j},"attributeValueProcessor"),stopNodes:[],alwaysCreateTextNode:!1,isArray:i(()=>!1,"isArray"),commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:i(function(k,j,q){return k},"updateTag")},N=r(function(k){return Object.assign({},v,k)},"buildOptions");P.buildOptions=N,P.defaultOptions=v}}),a=o({"node_modules/fast-xml-parser/src/util.js"(P){"use strict";var v=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",N=v+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",k="["+v+"]["+N+"]*",j=new RegExp("^"+k+"$"),q=r(function(E,U){let G=[],V=U.exec(E);for(;V;){let C=[];C.startIndex=U.lastIndex-V[0].length;let T=V.length;for(let H=0;H<T;H++)C.push(V[H]);G.push(C),V=U.exec(E)}return G},"getAllMatches"),$=r(function(E){let U=j.exec(E);return!(U===null||typeof U>"u")},"isName");P.isExist=function(E){return typeof E<"u"},P.isEmptyObject=function(E){return Object.keys(E).length===0},P.merge=function(E,U,G){if(U){let V=Object.keys(U),C=V.length;for(let T=0;T<C;T++)G==="strict"?E[V[T]]=[U[V[T]]]:E[V[T]]=U[V[T]]}},P.getValue=function(E){return P.isExist(E)?E:""},P.isName=$,P.getAllMatches=q,P.nameRegexp=k}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(P,v){"use strict";var N=class{static{i(this,"XmlNode")}static{r(this,"XmlNode")}constructor(k){this.tagname=k,this.child=[],this[":@"]={}}add(k,j){k==="__proto__"&&(k="#__proto__"),this.child.push({[k]:j})}addChild(k){k.tagname==="__proto__"&&(k.tagname="#__proto__"),k[":@"]&&Object.keys(k[":@"]).length>0?this.child.push({[k.tagname]:k.child,":@":k[":@"]}):this.child.push({[k.tagname]:k.child})}};v.exports=N}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(P,v){var N=a();function k(C,T){let H={};if(C[T+3]==="O"&&C[T+4]==="C"&&C[T+5]==="T"&&C[T+6]==="Y"&&C[T+7]==="P"&&C[T+8]==="E"){T=T+9;let de=1,J=!1,X=!1,Ce="";for(;T<C.length;T++)if(C[T]==="<"&&!X){if(J&&$(C,T))T+=7,[entityName,val,T]=j(C,T+1),val.indexOf("&")===-1&&(H[V(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(J&&E(C,T))T+=8;else if(J&&U(C,T))T+=8;else if(J&&G(C,T))T+=9;else if(q)X=!0;else throw new Error("Invalid DOCTYPE");de++,Ce=""}else if(C[T]===">"){if(X?C[T-1]==="-"&&C[T-2]==="-"&&(X=!1,de--):de--,de===0)break}else C[T]==="["?J=!0:Ce+=C[T];if(de!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:H,i:T}}i(k,"readDocType"),r(k,"readDocType");function j(C,T){let H="";for(;T<C.length&&C[T]!=="'"&&C[T]!=='"';T++)H+=C[T];if(H=H.trim(),H.indexOf(" ")!==-1)throw new Error("External entites are not supported");let de=C[T++],J="";for(;T<C.length&&C[T]!==de;T++)J+=C[T];return[H,J,T]}i(j,"readEntityExp"),r(j,"readEntityExp");function q(C,T){return C[T+1]==="!"&&C[T+2]==="-"&&C[T+3]==="-"}i(q,"isComment"),r(q,"isComment");function $(C,T){return C[T+1]==="!"&&C[T+2]==="E"&&C[T+3]==="N"&&C[T+4]==="T"&&C[T+5]==="I"&&C[T+6]==="T"&&C[T+7]==="Y"}i($,"isEntity"),r($,"isEntity");function E(C,T){return C[T+1]==="!"&&C[T+2]==="E"&&C[T+3]==="L"&&C[T+4]==="E"&&C[T+5]==="M"&&C[T+6]==="E"&&C[T+7]==="N"&&C[T+8]==="T"}i(E,"isElement"),r(E,"isElement");function U(C,T){return C[T+1]==="!"&&C[T+2]==="A"&&C[T+3]==="T"&&C[T+4]==="T"&&C[T+5]==="L"&&C[T+6]==="I"&&C[T+7]==="S"&&C[T+8]==="T"}i(U,"isAttlist"),r(U,"isAttlist");function G(C,T){return C[T+1]==="!"&&C[T+2]==="N"&&C[T+3]==="O"&&C[T+4]==="T"&&C[T+5]==="A"&&C[T+6]==="T"&&C[T+7]==="I"&&C[T+8]==="O"&&C[T+9]==="N"}i(G,"isNotation"),r(G,"isNotation");function V(C){if(N.isName(C))return C;throw new Error(`Invalid entity name ${C}`)}i(V,"validateEntityName"),r(V,"validateEntityName"),v.exports=k}}),l=o({"../../node_modules/strnum/strnum.js"(P,v){var N=/^[-+]?0x[a-fA-F0-9]+$/,k=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var j={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function q(E,U={}){if(U=Object.assign({},j,U),!E||typeof E!="string")return E;let G=E.trim();if(U.skipLike!==void 0&&U.skipLike.test(G))return E;if(U.hex&&N.test(G))return Number.parseInt(G,16);{let V=k.exec(G);if(V){let C=V[1],T=V[2],H=$(V[3]),de=V[4]||V[6];if(!U.leadingZeros&&T.length>0&&C&&G[2]!==".")return E;if(!U.leadingZeros&&T.length>0&&!C&&G[1]!==".")return E;{let J=Number(G),X=""+J;return X.search(/[eE]/)!==-1||de?U.eNotation?J:E:G.indexOf(".")!==-1?X==="0"&&H===""||X===H||C&&X==="-"+H?J:E:T?H===X||C+H===X?J:E:G===X||G===C+X?J:E}}else return E}}i(q,"toNumber"),r(q,"toNumber");function $(E){return E&&E.indexOf(".")!==-1&&(E=E.replace(/0+$/,""),E==="."?E="0":E[0]==="."?E="0"+E:E[E.length-1]==="."&&(E=E.substr(0,E.length-1))),E}i($,"trimZeros"),r($,"trimZeros"),v.exports=q}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(P,v){"use strict";var N=a(),k=u(),j=c(),q=l(),$=class{static{i(this,"OrderedObjParser")}static{r(this,"OrderedObjParser")}constructor(R){this.options=R,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:i((I,L)=>String.fromCharCode(Number.parseInt(L,10)),"val")},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:i((I,L)=>String.fromCharCode(Number.parseInt(L,16)),"val")}},this.addExternalEntities=E,this.parseXml=T,this.parseTextData=U,this.resolveNameSpace=G,this.buildAttributesMap=C,this.isItStopNode=X,this.replaceEntitiesValue=de,this.readStopNodeData=B,this.saveTextToParentTag=J,this.addChild=H}};function E(R){let I=Object.keys(R);for(let L=0;L<I.length;L++){let z=I[L];this.lastEntities[z]={regex:new RegExp("&"+z+";","g"),val:R[z]}}}i(E,"addExternalEntities"),r(E,"addExternalEntities");function U(R,I,L,z,_,D,ee){if(R!==void 0&&(this.options.trimValues&&!z&&(R=R.trim()),R.length>0)){ee||(R=this.replaceEntitiesValue(R));let F=this.options.tagValueProcessor(I,R,L,_,D);return F==null?R:typeof F!=typeof R||F!==R?F:this.options.trimValues?pe(R,this.options.parseTagValue,this.options.numberParseOptions):R.trim()===R?pe(R,this.options.parseTagValue,this.options.numberParseOptions):R}}i(U,"parseTextData"),r(U,"parseTextData");function G(R){if(this.options.removeNSPrefix){let I=R.split(":"),L=R.charAt(0)==="/"?"/":"";if(I[0]==="xmlns")return"";I.length===2&&(R=L+I[1])}return R}i(G,"resolveNameSpace"),r(G,"resolveNameSpace");var V=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function C(R,I,L){if(!this.options.ignoreAttributes&&typeof R=="string"){let z=N.getAllMatches(R,V),_=z.length,D={};for(let ee=0;ee<_;ee++){let F=this.resolveNameSpace(z[ee][1]),M=z[ee][4],ue=this.options.attributeNamePrefix+F;if(F.length)if(this.options.transformAttributeName&&(ue=this.options.transformAttributeName(ue)),ue==="__proto__"&&(ue="#__proto__"),M!==void 0){this.options.trimValues&&(M=M.trim()),M=this.replaceEntitiesValue(M);let ne=this.options.attributeValueProcessor(F,M,I);ne==null?D[ue]=M:typeof ne!=typeof M||ne!==M?D[ue]=ne:D[ue]=pe(M,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(D[ue]=!0)}if(!Object.keys(D).length)return;if(this.options.attributesGroupName){let ee={};return ee[this.options.attributesGroupName]=D,ee}return D}}i(C,"buildAttributesMap"),r(C,"buildAttributesMap");var T=r(function(R){R=R.replace(/\r\n?/g,`
73
- `);let I=new k("!xml"),L=I,z="",_="";for(let D=0;D<R.length;D++)if(R[D]==="<")if(R[D+1]==="/"){let F=b(R,">",D,"Closing Tag is not closed."),M=R.substring(D+2,F).trim();if(this.options.removeNSPrefix){let Oe=M.indexOf(":");Oe!==-1&&(M=M.substr(Oe+1))}this.options.transformTagName&&(M=this.options.transformTagName(M)),L&&(z=this.saveTextToParentTag(z,L,_));let ue=_.substring(_.lastIndexOf(".")+1);if(M&&this.options.unpairedTags.indexOf(M)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${M}>`);let ne=0;ue&&this.options.unpairedTags.indexOf(ue)!==-1?(ne=_.lastIndexOf(".",_.lastIndexOf(".")-1),this.tagsNodeStack.pop()):ne=_.lastIndexOf("."),_=_.substring(0,ne),L=this.tagsNodeStack.pop(),z="",D=F}else if(R[D+1]==="?"){let F=S(R,D,!1,"?>");if(!F)throw new Error("Pi Tag is not closed.");if(z=this.saveTextToParentTag(z,L,_),!(this.options.ignoreDeclaration&&F.tagName==="?xml"||this.options.ignorePiTags)){let M=new k(F.tagName);M.add(this.options.textNodeName,""),F.tagName!==F.tagExp&&F.attrExpPresent&&(M[":@"]=this.buildAttributesMap(F.tagExp,_,F.tagName)),this.addChild(L,M,_)}D=F.closeIndex+1}else if(R.substr(D+1,3)==="!--"){let F=b(R,"-->",D+4,"Comment is not closed.");if(this.options.commentPropName){let M=R.substring(D+4,F-2);z=this.saveTextToParentTag(z,L,_),L.add(this.options.commentPropName,[{[this.options.textNodeName]:M}])}D=F}else if(R.substr(D+1,2)==="!D"){let F=j(R,D);this.docTypeEntities=F.entities,D=F.i}else if(R.substr(D+1,2)==="!["){let F=b(R,"]]>",D,"CDATA is not closed.")-2,M=R.substring(D+9,F);z=this.saveTextToParentTag(z,L,_);let ue=this.parseTextData(M,L.tagname,_,!0,!1,!0,!0);ue==null&&(ue=""),this.options.cdataPropName?L.add(this.options.cdataPropName,[{[this.options.textNodeName]:M}]):L.add(this.options.textNodeName,ue),D=F+2}else{let F=S(R,D,this.options.removeNSPrefix),M=F.tagName,ue=F.rawTagName,ne=F.tagExp,Oe=F.attrExpPresent,Ei=F.closeIndex;this.options.transformTagName&&(M=this.options.transformTagName(M)),L&&z&&L.tagname!=="!xml"&&(z=this.saveTextToParentTag(z,L,_,!1));let xi=L;if(xi&&this.options.unpairedTags.indexOf(xi.tagname)!==-1&&(L=this.tagsNodeStack.pop(),_=_.substring(0,_.lastIndexOf("."))),M!==I.tagname&&(_+=_?"."+M:M),this.isItStopNode(this.options.stopNodes,_,M)){let Se="";if(ne.length>0&&ne.lastIndexOf("/")===ne.length-1)D=F.closeIndex;else if(this.options.unpairedTags.indexOf(M)!==-1)D=F.closeIndex;else{let zn=this.readStopNodeData(R,ue,Ei+1);if(!zn)throw new Error(`Unexpected end of ${ue}`);D=zn.i,Se=zn.tagContent}let jn=new k(M);M!==ne&&Oe&&(jn[":@"]=this.buildAttributesMap(ne,_,M)),Se&&(Se=this.parseTextData(Se,M,_,!0,Oe,!0,!0)),_=_.substr(0,_.lastIndexOf(".")),jn.add(this.options.textNodeName,Se),this.addChild(L,jn,_)}else{if(ne.length>0&&ne.lastIndexOf("/")===ne.length-1){M[M.length-1]==="/"?(M=M.substr(0,M.length-1),_=_.substr(0,_.length-1),ne=M):ne=ne.substr(0,ne.length-1),this.options.transformTagName&&(M=this.options.transformTagName(M));let Se=new k(M);M!==ne&&Oe&&(Se[":@"]=this.buildAttributesMap(ne,_,M)),this.addChild(L,Se,_),_=_.substr(0,_.lastIndexOf("."))}else{let Se=new k(M);this.tagsNodeStack.push(L),M!==ne&&Oe&&(Se[":@"]=this.buildAttributesMap(ne,_,M)),this.addChild(L,Se,_),L=Se}z="",D=Ei}}else z+=R[D];return I.child},"parseXml");function H(R,I,L){let z=this.options.updateTag(I.tagname,L,I[":@"]);z===!1||(typeof z=="string"&&(I.tagname=z),R.addChild(I))}i(H,"addChild"),r(H,"addChild");var de=r(function(R){if(this.options.processEntities){for(let I in this.docTypeEntities){let L=this.docTypeEntities[I];R=R.replace(L.regx,L.val)}for(let I in this.lastEntities){let L=this.lastEntities[I];R=R.replace(L.regex,L.val)}if(this.options.htmlEntities)for(let I in this.htmlEntities){let L=this.htmlEntities[I];R=R.replace(L.regex,L.val)}R=R.replace(this.ampEntity.regex,this.ampEntity.val)}return R},"replaceEntitiesValue");function J(R,I,L,z){return R&&(z===void 0&&(z=Object.keys(I.child).length===0),R=this.parseTextData(R,I.tagname,L,!1,I[":@"]?Object.keys(I[":@"]).length!==0:!1,z),R!==void 0&&R!==""&&I.add(this.options.textNodeName,R),R=""),R}i(J,"saveTextToParentTag"),r(J,"saveTextToParentTag");function X(R,I,L){let z="*."+L;for(let _ in R){let D=R[_];if(z===D||I===D)return!0}return!1}i(X,"isItStopNode"),r(X,"isItStopNode");function Ce(R,I,L=">"){let z,_="";for(let D=I;D<R.length;D++){let ee=R[D];if(z)ee===z&&(z="");else if(ee==='"'||ee==="'")z=ee;else if(ee===L[0])if(L[1]){if(R[D+1]===L[1])return{data:_,index:D}}else return{data:_,index:D};else ee===" "&&(ee=" ");_+=ee}}i(Ce,"tagExpWithClosingIndex"),r(Ce,"tagExpWithClosingIndex");function b(R,I,L,z){let _=R.indexOf(I,L);if(_===-1)throw new Error(z);return _+I.length-1}i(b,"findClosingIndex"),r(b,"findClosingIndex");function S(R,I,L,z=">"){let _=Ce(R,I+1,z);if(!_)return;let D=_.data,ee=_.index,F=D.search(/\s/),M=D,ue=!0;F!==-1&&(M=D.substring(0,F),D=D.substring(F+1).trimStart());let ne=M;if(L){let Oe=M.indexOf(":");Oe!==-1&&(M=M.substr(Oe+1),ue=M!==_.data.substr(Oe+1))}return{tagName:M,tagExp:D,closeIndex:ee,attrExpPresent:ue,rawTagName:ne}}i(S,"readTagExp"),r(S,"readTagExp");function B(R,I,L){let z=L,_=1;for(;L<R.length;L++)if(R[L]==="<")if(R[L+1]==="/"){let D=b(R,">",L,`${I} is not closed`);if(R.substring(L+2,D).trim()===I&&(_--,_===0))return{tagContent:R.substring(z,L),i:D};L=D}else if(R[L+1]==="?")L=b(R,"?>",L+1,"StopNode is not closed.");else if(R.substr(L+1,3)==="!--")L=b(R,"-->",L+3,"StopNode is not closed.");else if(R.substr(L+1,2)==="![")L=b(R,"]]>",L,"StopNode is not closed.")-2;else{let D=S(R,L,">");D&&((D&&D.tagName)===I&&D.tagExp[D.tagExp.length-1]!=="/"&&_++,L=D.closeIndex)}}i(B,"readStopNodeData"),r(B,"readStopNodeData");function pe(R,I,L){if(I&&typeof R=="string"){let z=R.trim();return z==="true"?!0:z==="false"?!1:q(R,L)}else return N.isExist(R)?R:""}i(pe,"parseValue"),r(pe,"parseValue"),v.exports=$}}),p=o({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(P){"use strict";function v($,E){return N($,E)}i(v,"prettify"),r(v,"prettify");function N($,E,U){let G,V={};for(let C=0;C<$.length;C++){let T=$[C],H=k(T),de="";if(U===void 0?de=H:de=U+"."+H,H===E.textNodeName)G===void 0?G=T[H]:G+=""+T[H];else{if(H===void 0)continue;if(T[H]){let J=N(T[H],E,de),X=q(J,E);T[":@"]?j(J,T[":@"],de,E):Object.keys(J).length===1&&J[E.textNodeName]!==void 0&&!E.alwaysCreateTextNode?J=J[E.textNodeName]:Object.keys(J).length===0&&(E.alwaysCreateTextNode?J[E.textNodeName]="":J=""),V[H]!==void 0&&V.hasOwnProperty(H)?(Array.isArray(V[H])||(V[H]=[V[H]]),V[H].push(J)):E.isArray(H,de,X)?V[H]=[J]:V[H]=J}}}return typeof G=="string"?G.length>0&&(V[E.textNodeName]=G):G!==void 0&&(V[E.textNodeName]=G),V}i(N,"compress"),r(N,"compress");function k($){let E=Object.keys($);for(let U=0;U<E.length;U++){let G=E[U];if(G!==":@")return G}}i(k,"propName"),r(k,"propName");function j($,E,U,G){if(E){let V=Object.keys(E),C=V.length;for(let T=0;T<C;T++){let H=V[T];G.isArray(H,U+"."+H,!0,!0)?$[H]=[E[H]]:$[H]=E[H]}}}i(j,"assignAttributes"),r(j,"assignAttributes");function q($,E){let{textNodeName:U}=E,G=Object.keys($).length;return!!(G===0||G===1&&($[U]||typeof $[U]=="boolean"||$[U]===0))}i(q,"isLeafTag"),r(q,"isLeafTag"),P.prettify=v}}),h=o({"node_modules/fast-xml-parser/src/validator.js"(P){"use strict";var v=a(),N={allowBooleanAttributes:!1,unpairedTags:[]};P.validate=function(b,S){S=Object.assign({},N,S);let B=[],pe=!1,R=!1;b[0]==="\uFEFF"&&(b=b.substr(1));for(let I=0;I<b.length;I++)if(b[I]==="<"&&b[I+1]==="?"){if(I+=2,I=j(b,I),I.err)return I}else if(b[I]==="<"){let L=I;if(I++,b[I]==="!"){I=q(b,I);continue}else{let z=!1;b[I]==="/"&&(z=!0,I++);let _="";for(;I<b.length&&b[I]!==">"&&b[I]!==" "&&b[I]!==" "&&b[I]!==`
74
- `&&b[I]!=="\r";I++)_+=b[I];if(_=_.trim(),_[_.length-1]==="/"&&(_=_.substring(0,_.length-1),I--),!J(_)){let F;return _.trim().length===0?F="Invalid space after '<'.":F="Tag '"+_+"' is an invalid name.",H("InvalidTag",F,X(b,I))}let D=U(b,I);if(D===!1)return H("InvalidAttr","Attributes for '"+_+"' have open quote.",X(b,I));let ee=D.value;if(I=D.index,ee[ee.length-1]==="/"){let F=I-ee.length;ee=ee.substring(0,ee.length-1);let M=V(ee,S);if(M===!0)pe=!0;else return H(M.err.code,M.err.msg,X(b,F+M.err.line))}else if(z)if(D.tagClosed){if(ee.trim().length>0)return H("InvalidTag","Closing tag '"+_+"' can't have attributes or invalid starting.",X(b,L));{let F=B.pop();if(_!==F.tagName){let M=X(b,F.tagStartPos);return H("InvalidTag","Expected closing tag '"+F.tagName+"' (opened in line "+M.line+", col "+M.col+") instead of closing tag '"+_+"'.",X(b,L))}B.length==0&&(R=!0)}}else return H("InvalidTag","Closing tag '"+_+"' doesn't have proper closing.",X(b,I));else{let F=V(ee,S);if(F!==!0)return H(F.err.code,F.err.msg,X(b,I-ee.length+F.err.line));if(R===!0)return H("InvalidXml","Multiple possible root nodes found.",X(b,I));S.unpairedTags.indexOf(_)!==-1||B.push({tagName:_,tagStartPos:L}),pe=!0}for(I++;I<b.length;I++)if(b[I]==="<")if(b[I+1]==="!"){I++,I=q(b,I);continue}else if(b[I+1]==="?"){if(I=j(b,++I),I.err)return I}else break;else if(b[I]==="&"){let F=T(b,I);if(F==-1)return H("InvalidChar","char '&' is not expected.",X(b,I));I=F}else if(R===!0&&!k(b[I]))return H("InvalidXml","Extra text at the end",X(b,I));b[I]==="<"&&I--}}else{if(k(b[I]))continue;return H("InvalidChar","char '"+b[I]+"' is not expected.",X(b,I))}if(pe){if(B.length==1)return H("InvalidTag","Unclosed tag '"+B[0].tagName+"'.",X(b,B[0].tagStartPos));if(B.length>0)return H("InvalidXml","Invalid '"+JSON.stringify(B.map(I=>I.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return H("InvalidXml","Start tag expected.",1);return!0};function k(b){return b===" "||b===" "||b===`
75
- `||b==="\r"}i(k,"isWhiteSpace"),r(k,"isWhiteSpace");function j(b,S){let B=S;for(;S<b.length;S++)if(b[S]=="?"||b[S]==" "){let pe=b.substr(B,S-B);if(S>5&&pe==="xml")return H("InvalidXml","XML declaration allowed only at the start of the document.",X(b,S));if(b[S]=="?"&&b[S+1]==">"){S++;break}else continue}return S}i(j,"readPI"),r(j,"readPI");function q(b,S){if(b.length>S+5&&b[S+1]==="-"&&b[S+2]==="-"){for(S+=3;S<b.length;S++)if(b[S]==="-"&&b[S+1]==="-"&&b[S+2]===">"){S+=2;break}}else if(b.length>S+8&&b[S+1]==="D"&&b[S+2]==="O"&&b[S+3]==="C"&&b[S+4]==="T"&&b[S+5]==="Y"&&b[S+6]==="P"&&b[S+7]==="E"){let B=1;for(S+=8;S<b.length;S++)if(b[S]==="<")B++;else if(b[S]===">"&&(B--,B===0))break}else if(b.length>S+9&&b[S+1]==="["&&b[S+2]==="C"&&b[S+3]==="D"&&b[S+4]==="A"&&b[S+5]==="T"&&b[S+6]==="A"&&b[S+7]==="["){for(S+=8;S<b.length;S++)if(b[S]==="]"&&b[S+1]==="]"&&b[S+2]===">"){S+=2;break}}return S}i(q,"readCommentAndCDATA"),r(q,"readCommentAndCDATA");var $='"',E="'";function U(b,S){let B="",pe="",R=!1;for(;S<b.length;S++){if(b[S]===$||b[S]===E)pe===""?pe=b[S]:pe!==b[S]||(pe="");else if(b[S]===">"&&pe===""){R=!0;break}B+=b[S]}return pe!==""?!1:{value:B,index:S,tagClosed:R}}i(U,"readAttributeStr"),r(U,"readAttributeStr");var G=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function V(b,S){let B=v.getAllMatches(b,G),pe={};for(let R=0;R<B.length;R++){if(B[R][1].length===0)return H("InvalidAttr","Attribute '"+B[R][2]+"' has no space in starting.",Ce(B[R]));if(B[R][3]!==void 0&&B[R][4]===void 0)return H("InvalidAttr","Attribute '"+B[R][2]+"' is without value.",Ce(B[R]));if(B[R][3]===void 0&&!S.allowBooleanAttributes)return H("InvalidAttr","boolean attribute '"+B[R][2]+"' is not allowed.",Ce(B[R]));let I=B[R][2];if(!de(I))return H("InvalidAttr","Attribute '"+I+"' is an invalid name.",Ce(B[R]));if(!pe.hasOwnProperty(I))pe[I]=1;else return H("InvalidAttr","Attribute '"+I+"' is repeated.",Ce(B[R]))}return!0}i(V,"validateAttributeString"),r(V,"validateAttributeString");function C(b,S){let B=/\d/;for(b[S]==="x"&&(S++,B=/[\da-fA-F]/);S<b.length;S++){if(b[S]===";")return S;if(!b[S].match(B))break}return-1}i(C,"validateNumberAmpersand"),r(C,"validateNumberAmpersand");function T(b,S){if(S++,b[S]===";")return-1;if(b[S]==="#")return S++,C(b,S);let B=0;for(;S<b.length;S++,B++)if(!(b[S].match(/\w/)&&B<20)){if(b[S]===";")break;return-1}return S}i(T,"validateAmpersand"),r(T,"validateAmpersand");function H(b,S,B){return{err:{code:b,msg:S,line:B.line||B,col:B.col}}}i(H,"getErrorObject"),r(H,"getErrorObject");function de(b){return v.isName(b)}i(de,"validateAttrName"),r(de,"validateAttrName");function J(b){return v.isName(b)}i(J,"validateTagName"),r(J,"validateTagName");function X(b,S){let B=b.substring(0,S).split(/\r?\n/);return{line:B.length,col:B[B.length-1].length+1}}i(X,"getLineNumberForPosition"),r(X,"getLineNumberForPosition");function Ce(b){return b.startIndex+b[1].length}i(Ce,"getPositionFromMatch"),r(Ce,"getPositionFromMatch")}}),y=o({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(P,v){var{buildOptions:N}=s(),k=d(),{prettify:j}=p(),q=h(),$=class{static{i(this,"XMLParser")}static{r(this,"XMLParser")}constructor(E){this.externalEntities={},this.options=N(E)}parse(E,U){if(typeof E!="string")if(E.toString)E=E.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(U){U===!0&&(U={});let C=q.validate(E,U);if(C!==!0)throw Error(`${C.err.msg}:${C.err.line}:${C.err.col}`)}let G=new k(this.options);G.addExternalEntities(this.externalEntities);let V=G.parseXml(E);return this.options.preserveOrder||V===void 0?V:j(V,this.options)}addEntity(E,U){if(U.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(E.indexOf("&")!==-1||E.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(U==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[E]=U}};v.exports=$}});let O=y();return new O(n)},"getXmlParser");var hi=class extends Ge{static{i(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),g("policy.outbound.xml-to-json"),K(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=e.parseOnStatusCodes?Be(e.parseOnStatusCodes):void 0,this.parser=Ka({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,t,r){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let o;try{let u=await e.text();o=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw r.log.error(c,u),new A(c)}let s=new Headers(e.headers);return s.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:s})}};var yi=class{static{i(this,"ServiceProviderImpl")}services=new Map;addService(e,t){if(this.services.get(e))throw new W(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,t)}getService(e){return this.services.get(e)}};var bi=class{static{i(this,"BackgroundDispatcher")}#e;constructor(e,t){if(!t||t.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new Y(t.name??"",t.msDelay,e)}enqueue=i(e=>{this.#e.enqueue(e),Cn().waitUntil(this.#e.waitUntilFlushed())},"enqueue")};var Ja=10,Qa=3e4,wi=class{static{i(this,"BackgroundLoader")}#e=new Map;#t;#n;#r;#o;#i={};constructor(e,t){if(typeof t=="number"){let r=t;this.#n=r*1e3,this.#o=Qa,this.#r=Ja}else{let r=t;this.#n=r.ttlSeconds*1e3,this.#o=r.loaderTimeoutSeconds?r.loaderTimeoutSeconds*1e3:Qa,this.#r=Ja}this.#t=e}#s(e){return e.expiry<=new Date}#a(e){let t=this.#i[e];return!(t===void 0||t===0)}#u(e){let t=this.#e.get(e);if(t&&!this.#s(t))return t.data}async get(e){let t=this.#u(e);if(t)return this.#l(e),t;if(this.#a(e))try{await kd(()=>this.#u(e)!==void 0||!this.#a,this.#o+this.#r+1,this.#r);let r=this.#u(e);if(r)return r}catch{}return this.#c(e)}#l(e){if(!this.#a(e)){let t=this.#c(e);Cn().waitUntil(t)}}async#c(e){try{this.#i[e]===void 0&&(this.#i[e]=0),this.#i[e]++;let t=await Promise.race([this.#t(e),scheduler.wait(this.#o)]);if(t===void 0)throw new Error(`BackgroundLoader: Loader timed out after ${this.#o} ms.`);return this.#e.set(e,{data:t,expiry:new Date(Date.now()+this.#n)}),t}finally{this.#i[e]--}}};async function kd(n,e,t){let r=Date.now();for(;!n();){let o=Date.now()-r;if(o>e)throw new Error(`BackgroundLoader: Timeout waiting for an on-going loader after ${o} ms.`);await scheduler.wait(t)}}i(kd,"waitUntilTrue");var Ri=["sha-1","sha-256","sha-384","sha-512"],$n=class{static{i(this,"BaseCryptoBeta")}};var Pi=class extends $n{static{i(this,"WorkerCryptoBeta")}async digest(e,t){if(!Ri.includes(e.toLowerCase()))throw new A(`Algorithm ${e} is not supported. Try using ${Ri.join(", ")}`);let r=new TextEncoder().encode(t),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var Fn=class{constructor(e){this.context=e}static{i(this,"BaseKeyValueStore")}};var Ii=class extends Fn{static{i(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let t=f.instance.runtime.ZUPLO_KV;if(!t)throw new nn("The Key Value Store feature is not enabled for this project.");this.#e=t,g("platform.kv-store")}put(e,t,r){if(typeof e!="string")throw new m("value must be of type string");return this.#e.put(e,t,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,t){return this.#e.get(e,{type:"text",cacheTtl:t?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};export{Ro as AWSLoggingPlugin,nl as AmberfloMeteringInboundPolicy,Ho as AmberfloMeteringPolicy,il as ApiAuthKeyInboundPolicy,Zo as ApiKeyInboundPolicy,Ao as AuditLogDataStaxProvider,ko as AuditLogPlugin,ll as Auth0JwtInboundPolicy,Ic as AwsLambdaHandlerExtensions,zo as AxiomaticsAuthZInboundPolicy,bi as BackgroundDispatcher,wi as BackgroundLoader,dl as BasicAuthInboundPolicy,qa as BasicRateLimitInboundPolicy,Y as BatchDispatch,Vo as BrownoutInboundPolicy,Il as CachingInboundPolicy,El as ChangeMethodInboundPolicy,xl as ClearHeadersInboundPolicy,Tl as ClearHeadersOutboundPolicy,vl as ClerkJwtInboundPolicy,Cl as CognitoJwtInboundPolicy,Xo as ComplexRateLimitInboundPolicy,Dl as CompositeInboundPolicy,Ml as CompositeOutboundPolicy,m as ConfigurationError,xr as ContentTypes,oe as ContextData,Pi as CryptoBeta,ql as CurityPhantomTokenInboundPolicy,Qr as DataDogLoggingPlugin,Eo as DataDogMetricsPlugin,lo as DynaTraceLoggingPlugin,Co as DynatraceMetricsPlugin,Hl as FirebaseJwtInboundPolicy,Zl as FormDataToJsonInboundPolicy,$l as GeoFilterInboundPolicy,Gr as GoogleCloudLoggingPlugin,no as Handler,x as HttpProblems,ln as HttpStatusCode,ae as InboundPolicy,Fl as JWTScopeValidationInboundPolicy,Ii as KeyValueStore,mo as LokiLoggingPlugin,Vt as LookupResult,re as MemoryZoneReadThroughCache,jl as MockApiInboundPolicy,Jl as MoesifInboundPolicy,ri as MonetizationInboundPolicy,oi as OktaFGAAuthZInboundPolicy,Yl as OktaJwtInboundPolicy,ii as OpenFGAAuthZInboundPolicy,Re as OpenIdJwtInboundPolicy,Ge as OutboundPolicy,tt as ProblemResponseFormatter,ed as PropelAuthJwtInboundPolicy,ui as QuotaInboundPolicy,qa as RateLimitInboundPolicy,sd as ReadmeMetricsInboundPolicy,ad as RemoveHeadersInboundPolicy,ud as RemoveHeadersOutboundPolicy,cd as RemoveQueryParamsInboundPolicy,ld as ReplaceStringOutboundPolicy,dd as RequestSizeLimitInboundPolicy,Ba as RequestValidationInboundPolicy,md as RequireOriginInboundPolicy,Dt as ResponseSendingEvent,Mt as ResponseSentEvent,Wt as Router,A as RuntimeError,on as SYSTEM_LOGGER,pd as SchemaBasedRequestValidation,_e as SemanticAttributes,yi as ServiceProviderImpl,gd as SetBodyInboundPolicy,fd as SetHeadersInboundPolicy,hd as SetHeadersOutboundPolicy,yd as SetQueryParamsInboundPolicy,bd as SetStatusOutboundPolicy,Rd as SleepInboundPolicy,la as StripeMonetizationPlugin,Jt as StripeWebhookVerificationInboundPolicy,ho as SumoLogicLoggingPlugin,Pd as SupabaseJwtInboundPolicy,Ze as SystemRouteName,Lt as TelemetryPlugin,Id as UpstreamAzureAdServiceAuthInboundPolicy,xd as UpstreamFirebaseAdminAuthInboundPolicy,Cd as UpstreamFirebaseUserAuthInboundPolicy,mi as UpstreamGcpFederatedAuthInboundPolicy,Sd as UpstreamGcpJwtInboundPolicy,Od as UpstreamGcpServiceAuthInboundPolicy,bo as VMWareLogInsightLoggingPlugin,Ad as ValidateJsonSchemaInbound,hi as XmlToJsonOutboundPolicy,Ot as ZoneCache,te as ZuploRequest,Xt as ZuploServices,Ec as awsLambdaHandler,Pe as environment,Bn as getIdForParameterSchema,Xa as getIdForRefSchema,Gn as getIdForRequestBodySchema,Ya as getRawOperationDataIdentifierName,vr as httpStatuses,kc as openApiSpecHandler,_c as redirectHandler,eu as sanitizedIdentifierName,Tr as serialize,Vl as setMoesifContext,g as trackFeature,Dc as urlForwardHandler,qc as urlRewriteHandler,Uc as webSocketHandler,Hc as webSocketPipelineHandler};
71
+ `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new Me(e,n,{message:"Timestamp outside the tolerance zone"});return!0}i(Jc,"validateComputedSignature");function Qc(n,e){return typeof n!="string"?null:n.split(",").reduce((t,r)=>{let o=r.split("=");return o[0]==="t"&&(t.timestamp=parseInt(o[1],10)),o[0]===e&&t.signatures.push(o[1]),t},{timestamp:-1,signatures:[]})}i(Qc,"parseHeader");function Yc(n,e){if(n.length!==e.length)return!1;let t=n.length,r=0;for(let o=0;o<t;++o)r|=n.charCodeAt(o)^e.charCodeAt(o);return r===0}i(Yc,"secureCompare");async function Xc(n,e){let t=new TextEncoder,r=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,t.encode(n)),s=new Uint8Array(o),a=new Array(s.length);for(let u=0;u<s.length;u++)a[u]=No[s[u]];return a.join("")}i(Xc,"computeHMACSignatureAsync");var No=new Array(256);for(let n=0;n<No.length;n++)No[n]=n.toString(16).padStart(2,"0");function K(n,e,t="policy",r){let o=`${t} '${e}'`;if(!nt(n))throw new g(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let s=i((c,l,d)=>{let p=n[c],m=r?`${r}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new g(`Value of '${m}' on ${o} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"&&Array.isArray(p))throw new g(`Value of '${m}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new g(`Value of '${m}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new g(`Value of '${m}' on ${o} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof p=="number"&&isNaN(p))throw new g(`Value of '${m}' on ${o} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=i((c,l)=>(s(c,l,!0),{optional:a,required:u}),"optional"),u=i((c,l)=>(s(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}i(K,"optionValidator");var Jt=class extends ae{static{i(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),f("policy.inbound.stripe-webhook-verification")}async handler(e,t){K(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let r=e.headers.get("stripe-signature");try{let o=await e.clone().text();await ra(o,r,this.options.signingSecret)}catch(o){let s=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a,s.startsWith("No signatures found matching the expected signature for payload")&&(s="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",s),x.badRequest(e,t,{title:"Webhook Error",detail:s})}return e}};function oa(n){return n!==null&&typeof n=="object"&&"id"in n&&xe(n.id)&&"type"in n&&xe(n.type)}i(oa,"isStripeWebhookEvent");var el={getSubscription:i(async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await Z.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving subscription from Stripe API.";throw t.error(s,o),new S(s)}return o},"getSubscription"),getCustomer:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await Z.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer from Stripe API.";throw t.error(s,o),new S(s)}return o},"getCustomer"),getUpcomingInvoice:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await Z.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(s,o),new S(s)}return o},"getUpcomingInvoice")},kn=el;var Do="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",ia="My API Key";async function sa({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=h.instance,c=new URL(`/v1/buckets/${n}/consumers`,Do);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:ia,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await ye({retryDelayMs:5,retries:2,logger:Q.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),m=await p.json();if(p.status!==200){let y="Error creating API Key Consumer";throw a.log.error(y,m),new S(y)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(sa,"createConsumer");async function aa({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=h.instance,u=new URL(`/v1/buckets/${n}/consumers`,Do);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:ia,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await ye({retryDelayMs:5,retries:2,logger:Q.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let m="Error creating API Key Consumer";throw s.log.error(m,p),new S(m)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(aa,"createConsumerInvite");async function ua({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=h.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,Do);o.searchParams.set("with-api-key","true");let s=await ye({retryDelayMs:5,retries:2,logger:Q.getLogger(t)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new S(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(ua,"deleteConsumer");async function ca({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:r,meteringBucketId:o,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[t],customerKey:r,customerExternalId:a,metadata:c,trialEndDate:l?l.trialEndDate:void 0,trialStartDate:l?l.trialStartDate:void 0,trialEndStatus:l?l.trialEndStatus:void 0},{authApiJWT:p,meteringServiceUrl:m}=h.instance;if(!pt(p))throw new W("No Zuplo JWT token set.");let y=await ye({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${m}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!y.ok){let A=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,P,v="";try{P=await y.json(),v=P.detail??P.title}catch{P={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:y.status,detail:y.statusText}}throw n.log.error(A,P),new S(`${A} ${v}`)}n.log.info("Successfully created monetization subscription.",d)}i(ca,"createSubscription");async function yt({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=h.instance;if(!pt(o))throw new W("No Zuplo JWT token set.");let a=await ye({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${s}/internal/v1/metering/${t}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Unable to update monetization subscription with: '${JSON.stringify(r)}'.`,c,l="";try{c=await a.json(),l=c.detail??c.title}catch{c={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(u,c),new S(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}i(yt,"updateSubscription");async function bt({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=h.instance;if(!pt(o))throw new W("No Zuplo JWT token set.");let a=await ye({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${s}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":n.requestId},method:"GET"});if(!a.ok){let c=`Unable to retrieve the monetization subscription for Stripe subscription '${e}'.`,l,d="";try{l=await a.json(),d=l.detail??l.title}catch{l={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(c,l),new S(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(c),new S(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(c),new S(c)}return u.data[0]}i(bt,"getSubscription");var ie="Skipping since we're unable to process the webhook event.",Ke="Successfully processed the webhook event",Ee="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function Ln(n){return n.replaceAll("_","-")}i(Ln,"stripeStatusToMeteringStatus");function st(n){return new Date(n*1e3).toISOString()}i(st,"unixTimestampToISOString");async function Mo(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),x.ok(n,e,{title:ie,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),x.ok(n,e,{title:ie,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=t.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:ie,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==h.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),x.ok(n,e,{title:ie,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ee});let u=s.product,c,l,d;try{if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_email&&t.data.object.metadata.zuplo_created_by_sub)l=t.data.object.metadata.zuplo_created_by_email,d=t.data.object.metadata.zuplo_created_by_sub,c=await sa({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await kn.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),x.ok(n,e,{title:ie,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await aa({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}}catch(p){return e.log.warn(`Failed to create API Key Consumer. Error: ${p.message}`),x.ok(n,e,{title:ie,detail:p.message})}if(!c)return x.ok(n,e,{title:ie,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=Ln(t.data.object.status),m;l&&d&&(m={subscriber:{sub:d,email:l}});let y;t.data.object.trial_end!==null&&t.data.object.trial_start!==null&&t.data.object.trial_settings&&t.data.object.trial_settings.end_behavior&&(t.data.object.trial_settings.end_behavior.missing_payment_method==="cancel"||t.data.object.trial_settings.end_behavior.missing_payment_method==="pause")&&(y={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:st(t.data.object.trial_end),trialStartDate:st(t.data.object.trial_start)}),await ca({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:m,trial:y})}catch(p){return await ua({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),x.ok(n,e,{title:ie,detail:p.message})}return x.ok(n,e,{title:Ke})}i(Mo,"onCustomerSubscriptionCreated");async function qo(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),x.ok(n,e,{title:ie,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:ie,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==h.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),x.ok(n,e,{title:ie,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ee});try{let a=await bt({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});await yt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return x.ok(n,e,{title:ie,detail:`The event 'customer.subscription.deleted' could not be processed. ${a.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. `+Ee})}return x.ok(n,e,{title:Ke})}i(qo,"onCustomerSubscriptionDeleted");async function Ho(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to include '.data.object.id' as the subscription ID.`),x.ok(n,e,{title:ie,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:ie,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==h.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),x.ok(n,e,{title:ie,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ee});if(t.data.previous_attributes){let a=t.data.previous_attributes;if(a.status&&a.status!==t.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${t.id}'.`);let u=await bt({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=Ln(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=st(t.data.object.trial_end)),await yt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return x.ok(n,e,{title:ie,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ee})}return x.ok(n,e,{title:Ke})}if(a.plan&&a.plan.product!==t.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${t.id}'.`);let u=await bt({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await kn.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(m=>m.proration&&m.price.product===c),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${t.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await yt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return x.ok(n,e,{title:ie,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ee})}return x.ok(n,e,{title:Ke})}if((a.cancel_at||a.cancel_at===null)&&a.cancel_at!==t.data.object.cancel_at&&a.cancel_at_period_end&&a.cancel_at_period_end!==t.data.object.cancel_at_period_end&&(a.canceled_at||a.canceled_at===null)&&a.canceled_at!==t.data.object.canceled_at||a.cancellation_details&&(a.cancellation_details.comment||a.cancellation_details.comment===null||a.cancellation_details.feedback||a.cancellation_details.feedback===null||a.cancellation_details.reason||a.cancellation_details.reason===null)){try{e.log.debug(`Processing subscription cancellation details from Stripe event '${t.id}'.`);let u=await bt({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?st(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?st(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await yt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return x.ok(n,e,{title:ie,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ee})}return x.ok(n,e,{title:Ke})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),x.ok(n,e,{title:ie,detail:"This 'customer.subscription.updated' event could not be processed. The Stripe monetization plugin only supports update events for subscription plan changes or subscription status changes."+Ee})}i(Ho,"onCustomerSubscriptionUpdated");var la=class extends sn{constructor(t){super();this.options=t;f("monetization.stripe")}static{i(this,"StripeMonetizationPlugin")}registerRoutes(t,r){let o=i(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new g("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!h.instance.build.ACCOUNT_NAME)throw new W("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let m=this.options.primaryDataRegion??"us-central1";if(!tl(m))throw new g(`StripeMonetizationPlugin - The value '${m}' on the property 'primaryDataRegion' is invalid.`);let y=await c.json();if(!oa(y))return x.ok(c,l,{title:ie,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+Ee});switch(l.log.info(`Received Stripe webhook event of type '${y.type}' with ID '${y.id}'.`),y.type){case"customer.subscription.created":return await Mo(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await Ho(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await qo(c,l,y,{meteringBucketId:d});default:return x.ok(c,l,{title:ie,detail:`Event '${y.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ee})}},"stripeWebhookHandler"),s=Ts({inboundPolicies:[new Jt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});K(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new me({processors:[we,s],handler:o,gateway:r}),u=new ce({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function tl(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}i(tl,"isMetricsRegion");var pa=new WeakMap,da={},Uo=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){pa.set(e,t)}};async function nl(n,e,t,r){if(f("policy.inbound.amberflo-metering"),!t.statusCodes)throw new g(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Be(t.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=pa.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new S(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=rt(n.user,t.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??t.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??t.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(t.dimensions??{},a?.dimensions)},m=da[t.apiKey];if(!m){let y=t.apiKey,A=n.headers.get("zm-test-id")??"";m=new Y("amberflo-ingest-meter",10,async P=>{try{let v=t.url??"https://app.amberflo.io/ingest",N=await Z.fetch(v,{method:"POST",body:JSON.stringify(P),headers:{"content-type":"application/json","x-api-key":y,"zm-test-id":A}});N.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${N.status}: ${await N.text()}`)}catch(v){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${v.message}`),v}}),da[y]=m}m.enqueue(p),e.waitUntil(m.waitUntilFlushed())}}),n}i(nl,"AmberfloMeteringInboundPolicy");async function at(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(t)].map(o=>o.toString(16).padStart(2,"0")).join("")}i(at,"sha256");var ma=new Map;async function se(n,e,t){let r,o=`${n}-${e}`,s=ma.get(o);return s!==void 0?r=s:(r=`zuplo-policy-${await at(JSON.stringify({policyName:n,options:t}))}`,ma.set(n,r)),r}i(se,"getPolicyCacheName");var ga="key-metadata-cache-type";function rl(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}i(rl,"getKeyValue");async function Zo(n,e,t,r){if(f("policy.inbound.api-key"),!t.bucketName)if(Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new g(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:t.authHeader??"authorization",authScheme:t.authScheme??"Bearer",bucketName:t.bucketName,cacheTtlSeconds:t.cacheTtlSeconds??60,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:t.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new g(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let s=i(v=>o.allowUnauthenticatedRequests?n:x.unauthorized(n,e,{detail:v}),"unauthorizedResponse"),a=n.headers.get(o.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=rl(a,o);if(!u||u==="")return s("No key present");let c=await ol(u),l=await se(r,void 0,o),d=new re(l,e),p=await d.get(c);if(p&&p.isValid===!0)return n.user=p.user,n;if(p&&!p.isValid)return p.typeId!==ga&&Q.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let m={key:u},y=await ye({retryDelayMs:5,retries:2,logger:Q.getLogger(e)},`${h.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":h.instance.deploymentName??"unknown","User-Agent":h.instance.systemUserAgent},body:JSON.stringify(m)});if(y.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(y.status!==200){try{let v=await y.text(),N=JSON.parse(v);e.log.error("Unexpected response from key service",N)}catch{e.log.error("Invalid response from key service")}throw new S(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${y.status}`)}let A=await y.json(),P={isValid:!0,typeId:ga,user:{sub:A.name,data:A.metadata}};return n.user=P.user,d.put(c,P,o.cacheTtlSeconds),n}i(Zo,"ApiKeyInboundPolicy");async function ol(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(ol,"hashValue");var il=Zo;import{createRemoteJWKSet as al,jwtVerify as ha}from"jose";import{createLocalJWKSet as sl}from"jose";var $o=class{constructor(e,t,r){this.cache=t;if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.url=new URL(e.href),this.options={agent:r?.agent,headers:r?.headers},this.timeoutDuration=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this.cooldownDuration=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this.cacheMaxAge=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5}static{i(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,t){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,t)}catch(r){if(r instanceof Fo&&this.coolingDown()===!1)return await this.reload(),this.local(e,t);throw r}}async reload(){this.pendingFetch&&(this.pendingFetch=void 0);let e=new Headers(this.options.headers);e.has("User-Agent")||(e.set("User-Agent",h.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=sl(t),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(t=>{throw this.pendingFetch=void 0,t}),await this.pendingFetch}async fetchJwks(e,t,r){let o=await this.cache.get(this.url.href);if(o)return o;let s,a,u=!1;typeof AbortController=="function"&&(s=new AbortController,a=setTimeout(()=>{u=!0,s.abort()},t));let c=await Z.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new jo("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new wt("Expected 200 OK from the JSON Web Key Set HTTP response");try{let l=await c.json();return this.cache.put(this.url.href,l,this.cacheMaxAge),l}catch{throw new wt("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function fa(n,e,t){let r=new $o(n,e,t);return async(o,s)=>r.getKey(o,s)}i(fa,"createRemoteJWKSet");var wt=class extends S{static{i(this,"JWKSError")}},Fo=class extends wt{static{i(this,"JWKSNoMatchingKey")}},jo=class extends wt{static{i(this,"JWKSTimeout")}};var _n={},ul=i((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new g("Invalid State - jwkUrl not set");if(!_n[r.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(s=r.useExperimentalInMemoryCache),s){let a=await se(n,void 0,r),u=new re(a,e);_n[r.jwkUrl]=fa(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else _n[r.jwkUrl]=al(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await ha(t,_n[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),cl=i(async(n,e)=>{let t;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);t=new Uint8Array(s)}else t=e.secret;let{payload:r}=await ha(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),Re=i(async(n,e,t,r)=>{f("policy.inbound.open-id-jwt-auth");let o=n.headers.get("Authorization"),s="bearer ",a=i(m=>x.unauthorized(n,e,{detail:m}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new g(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new g(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=t.jwkUrl?ul(r,e):cl,l=await i(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let m=o.substring(s.length);if(!m||m.length===0)return a("No bearer token on authorization header");try{return await u(m,t)}catch(y){let A=new URL(n.url);return"code"in y&&y.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${A.pathname} `,y):e.log.warn(`Invalid token on: ${n.method} ${A.pathname}`,y),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return t.allowUnauthenticatedRequests===!0?n:l;let d=t.subPropertyName??"sub",p=l[d];return p?(n.user={sub:p,data:l},n):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var ll=i(async(n,e,t,r)=>(f("policy.inbound.auth0-jwt-auth"),Re(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"Auth0JwtInboundPolicy");var Nn=class{constructor(e){this.options=e;this.authHeader=`Basic ${btoa(e.pdpUsername+":"+e.pdpPassword)}`,this.authorizationUrl=new URL("/authorize",e.pdpUrl).toString()}static{i(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(e){let t=await Z.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!t.ok)throw new Error(`Request to PDP service failed with response status ${t.status}.`);return await t.json()}};var zo=class n extends ae{static{i(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static#e;static setAuthAttributes(e,t){n.#e||(n.#e=new WeakMap),n.#e.set(e,{Request:t})}constructor(e,t){super(e,t),f("policy.inbound.axiomatics-authz"),K(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new Nn(e)}async handler(e,t){let r=i(a=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=new URL(e.url),s=n.#e?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1&&e.user){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(s,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(s,"Action",a)}if(this.options.includeDefaultResourceAttributes!==!1){let a=[];a.push({AttributeId:"request.protocol",Value:o.protocol.substring(0,o.protocol.length-1)}),a.push({AttributeId:"request.host",Value:o.host}),a.push({AttributeId:"request.pathname",Value:o.pathname}),Object.entries(e.params).forEach(([u,c])=>{a.push({AttributeId:`request.params.${u}`,Value:c})}),o.searchParams.forEach((u,c)=>{a.push({AttributeId:`request.query.${c}`,Value:u})}),this.addAttributesToCategory(s,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:s,context:t});try{t.log.debug("PDP Request",s);let a=await this.pdpService.makePdpRequest(s);return t.log.debug("PDP Response",a),a.Response.every(u=>u.Decision==="Permit")?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling PDP service`,a),x.internalServerError(e,t)}}populateOptionAttributes({optionName:e,authzRequestCategory:t,authzRequest:r,context:o}){let s=this.options[e];if(s){let a=[];s.forEach(u=>{u.value?a.push({AttributeId:u.attributeId,Value:u.value}):o.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${u.attributeId} has no value. If using a selector, check that the selector is correct.`)}),this.addAttributesToCategory(r,t,a)}}addAttributesToCategory(e,t,r){e.Request[t]||(e.Request[t]=[]),e.Request[t].length===0?e.Request[t].push({Attribute:[]}):e.Request[t][0].Attribute=e.Request[t][0].Attribute??[],e.Request[t][0].Attribute.push(...r)}};var dl=i(async(n,e,t)=>{f("policy.inbound.basic-auth");let r=n.headers.get("Authorization"),o="basic ",s=i(l=>x.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!r)return await s("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await s("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let m=d.substring(0,p),y=d.substring(p+1),A=t.accounts.find(P=>P.username===m&&P.password===y);return A||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return t.allowUnauthenticatedRequests?n:u;let c=u.username;return n.user={sub:c,data:u.data},n},"BasicAuthInboundPolicy");function Dn(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}i(Dn,"extractDateElements");function ya(n,e){return new Date(n,e+1,0).getDate()}i(ya,"getDaysInMonth");function Bo(n,e){return n<=e?e-n:6-n+e+1}i(Bo,"getDaysBetweenWeekdays");var Mn=class{static{i(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:r,days:o,months:s,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!t||t.size===0)throw new Error("There must be at least one allowed minute.");if(!r||r.size===0)throw new Error("There must be at least one allowed hour.");if(!s||s.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!o||o.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((c,l)=>c-l),this.minutes=Array.from(t).sort((c,l)=>c-l),this.hours=Array.from(r).sort((c,l)=>c-l),this.days=Array.from(o).sort((c,l)=>c-l),this.months=Array.from(s).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=i((c,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${c} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");u("seconds",this.seconds,{min:0,max:59}),u("minutes",this.minutes,{min:0,max:59}),u("hours",this.hours,{min:0,max:23}),u("days",this.days,{min:1,max:31}),u("months",this.months,{min:0,max:11}),u("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(c=>c).reverse(),minutes:this.minutes.map(c=>c).reverse(),hours:this.hours.map(c=>c).reverse(),days:this.days.map(c=>c).reverse(),months:this.months.map(c=>c).reverse(),weekdays:this.weekdays.map(c=>c).reverse()}}findAllowedHour(e,t){return e==="next"?this.hours.find(r=>r>=t):this.reversed.hours.find(r=>r<=t)}findAllowedMinute(e,t){return e==="next"?this.minutes.find(r=>r>=t):this.reversed.minutes.find(r=>r<=t)}findAllowedSecond(e,t){return e==="next"?this.seconds.find(r=>r>t):this.reversed.seconds.find(r=>r<t)}findAllowedTime(e,t){let r=this.findAllowedHour(e,t.hour);if(r!==void 0)if(r===t.hour){let o=this.findAllowedMinute(e,t.minute);if(o!==void 0)if(o===t.minute){let s=this.findAllowedSecond(e,t.second);if(s!==void 0)return{hour:r,minute:o,second:s};if(o=this.findAllowedMinute(e,e==="next"?t.minute+1:t.minute-1),o!==void 0)return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(r=this.findAllowedHour(e,e==="next"?t.hour+1:t.hour-1),r!==void 0)return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,t,r,o){if(o<1)throw new Error("startDay must not be smaller than 1.");let s=ya(t,r),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return o>s?e==="next"?void 0:s:o;let c;a&&(c=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),c!==void 0&&c>s&&(c=void 0));let l;if(u){let d=new Date(t,r,o).getDay(),p=e==="next"?this.weekdays.find(m=>m>=d)??this.weekdays[0]:this.reversed.weekdays.find(m=>m<=d)??this.reversed.weekdays[0];if(p!==void 0){let m=e==="next"?Bo(d,p):Bo(p,d);l=e==="next"?o+m:o-m,(l>s||l<1)&&(l=void 0)}}if(c!==void 0&&l!==void 0)return e==="next"?Math.min(c,l):Math.max(c,l);if(c!==void 0)return c;if(l!==void 0)return l}getNextDate(e=new Date){let t=Dn(e),r=t.year,o=this.months.findIndex(a=>a>=t.month);o===-1&&(o=0,r++);let s=this.months.length*5;for(let a=0;a<s;a++){let u=r+Math.floor((o+a)/this.months.length),c=this.months[(o+a)%this.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("next",u,c,l?t.day:1),p=l&&d===t.day;if(d!==void 0&&p){let m=this.findAllowedTime("next",t);if(m!==void 0)return new Date(u,c,d,m.hour,m.minute,m.second);d=this.findAllowedDayInMonth("next",u,c,d+1),p=!1}if(d!==void 0&&!p)return new Date(u,c,d,this.hours[0],this.minutes[0],this.seconds[0])}throw new Error("No valid next date was found.")}getNextDates(e,t){let r=[],o;for(let s=0;s<e;s++)o=this.getNextDate(o??t),r.push(o);return r}*getNextDatesIterator(e,t){let r;for(;;){if(r=this.getNextDate(e),e=r,t&&t.getTime()<r.getTime())return;yield r}}getPrevDate(e=new Date){let t=Dn(e),r=t.year,o=this.reversed.months.findIndex(a=>a<=t.month);o===-1&&(o=0,r--);let s=this.reversed.months.length*5;for(let a=0;a<s;a++){let u=r-Math.floor((o+a)/this.reversed.months.length),c=this.reversed.months[(o+a)%this.reversed.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("prev",u,c,l?t.day:31),p=l&&d===t.day;if(d!==void 0&&p){let m=this.findAllowedTime("prev",t);if(m!==void 0)return new Date(u,c,d,m.hour,m.minute,m.second);d>1&&(d=this.findAllowedDayInMonth("prev",u,c,d-1),p=!1)}if(d!==void 0&&!p)return new Date(u,c,d,this.reversed.hours[0],this.reversed.minutes[0],this.reversed.seconds[0])}throw new Error("No valid previous date was found.")}getPrevDates(e,t){let r=[],o;for(let s=0;s<e;s++)o=this.getPrevDate(o??t),r.push(o);return r}*getPrevDatesIterator(e,t){let r;for(;;){if(r=this.getPrevDate(e),e=r,t&&t.getTime()>r.getTime())return;yield r}}matchDate(e){let{second:t,minute:r,hour:o,day:s,month:a,weekday:u}=Dn(e);return this.seconds.indexOf(t)===-1||this.minutes.indexOf(r)===-1||this.hours.indexOf(o)===-1||this.months.indexOf(a)===-1?!1:this.days.length!==31&&this.weekdays.length!==7?this.days.indexOf(s)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(s)!==-1&&this.weekdays.indexOf(u)!==-1}};var pl={min:0,max:59},ml={min:0,max:59},gl={min:0,max:23},fl={min:1,max:31},hl={min:1,max:12,aliases:{jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"}},yl={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},bl={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 1 *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@hourly":"0 * * * *","@minutely":"* * * * *"};function ut(n,e){let t=new Set;if(n==="*"){for(let d=e.min;d<=e.max;d=d+1)t.add(d);return t}let r=n.split(",");if(r.length>1)return r.forEach(d=>{ut(d,e).forEach(m=>t.add(m))}),t;let o=i(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${n}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${n}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),s=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(s===null)return t.add(o(n)),t;let a=s[1]==="*"?e.min:o(s[3]),u=s[1]==="*"?e.max:o(s[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=s[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}i(ut,"parseElement");function Go(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=bl[n.toLowerCase()]??n;let e=n.split(" ");if(e.length<5||e.length>6)throw new Error("Invalid cron expression: expected 5 or 6 elements.");let t=e.length===6?e[0]:"0",r=e.length===6?e[1]:e[0],o=e.length===6?e[2]:e[1],s=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],u=e.length===6?e[5]:e[4];return new Mn({seconds:ut(t,pl),minutes:ut(r,ml),hours:ut(o,gl),days:ut(s,fl),months:new Set(Array.from(ut(a,hl)).map(c=>c-1)),weekdays:new Set(Array.from(ut(u,yl)).map(c=>c%7))})}i(Go,"parseCronExpression");var Vo=class extends ae{static{i(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),f("policy.inbound.brownout"),K(e,t).optional("problem","object"),e.problem&&K(e.problem,t,"policy","problem").optional("detail","string").optional("status","string").optional("title","string"),typeof e.cronSchedule!="string"&&!(typeof e.cronSchedule=="object"&&Array.isArray(e.cronSchedule)&&!e.cronSchedule.some(r=>typeof r!="string")))throw new g(`Value of 'cronSchedule' on policy '${t}' must be of type string or string[]. Received type ${typeof e.cronSchedule}.`);typeof this.options.cronSchedule=="string"?this.crons=[Go(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>Go(r))}async handler(e,t){let r=new Date;if(r.setSeconds(0),r.setMilliseconds(0),this.crons.some(s=>s.matchDate(r))){let s=x.getProblemFromStatus(this.options.problem?.status??400,{detail:"This API is performing a scheduled brownout in advance of its pending deprecation. Please upgrade to a later version.",...this.options.problem});return x.format(s,e,t)}return e}};var wl=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Rl(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Rl,"digestMessage");var Pl=i(async(n,e)=>{let t=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of n.headers.entries())t.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await Rl(JSON.stringify(r)),s=new URL(n.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(n.method.toUpperCase())&&n.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",n.method);let c=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function Il(n,e,t,r){f("policy.inbound.caching");let o=await se(r,t.cacheId,t),s=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Pl(n,t),c=await s.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=t.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(n.method.toUpperCase()))return;let m=t?.expirationSecondsTtl??60,y=new Response(p.body,p);wl.forEach(A=>y.headers.delete(A)),y.headers.set("cache-control",`s-maxage=${m}`),e.waitUntil(s.put(u,y))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}i(Il,"CachingInboundPolicy");var El=i(async(n,e,t,r)=>{if(f("policy.inbound.change-method"),!t.method)throw new g(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new te(n,{method:t.method})},"ChangeMethodInboundPolicy");var xl=i(async(n,e,t)=>{f("policy.inbound.clear-headers");let r=[...t.exclude??[]],o=new Headers;return r.forEach(a=>{let u=n.headers.get(a);u&&o.set(a,u)}),new te(n,{headers:o})},"ClearHeadersInboundPolicy");var Tl=i(async(n,e,t,r)=>{f("policy.outbound.clear-headers");let o=[...r.exclude??[]],s=new Headers;return o.forEach(u=>{let c=n.headers.get(u);c&&s.set(u,c)}),new Response(n.body,{headers:s,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var vl=i(async(n,e,t,r)=>{f("policy.inbound.clerk-jwt-auth");let o=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),s=new URL(o);return s.pathname="/.well-known/jwks.json",Re(n,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var Cl=i(async(n,e,t,r)=>{if(f("policy.inbound.cognito-jwt-auth"),!t.userPoolId)throw new g("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new g("region must be set in the options for CognitoJwtInboundPolicy");return Re(n,e,{issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,jwkUrl:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var qn=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},Wo=class extends qn{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Ko=class extends qn{static{i(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function Ol(n,e){if(ys(n))throw new Wo(e)}i(Ol,"throwIfUndefinedOrNull");function ba(n,e){if(Ol(n,e),!xe(n))throw new Ko(e,"string")}i(ba,"throwIfNotString");var Jo=class{static{i(this,"InMemoryRateLimitClient")}keyValueStore;constructor(){this.keyValueStore=new Map}getCountAndUpdateExpiry(e,t){let o=Math.floor(t*60),s=Date.now()+o*1e3,a=this.keyValueStore.get(e);a?Date.now()>a.expiresAt?this.keyValueStore.set(e,{value:1,expiresAt:s}):this.keyValueStore.set(e,{value:a.value+1,expiresAt:a.expiresAt}):this.keyValueStore.set(e,{value:1,expiresAt:s});let u=this.keyValueStore.get(e);return Promise.resolve({count:u.value,ttlSeconds:Math.round((u.expiresAt-Date.now())/1e3)})}multiIncrement(e,t){throw new Error("In memory complex rate limits are not currently supported.")}multiCount(e,t){throw new Error("In memory complex rate limits are not currently supported.")}setQuota(e,t,r){throw new Error("In memory quotas are not currently supported.")}getQuota(e,t){throw new Error("In memory quotas are not currently supported.")}isEnabled(){return!0}},Qo=class{constructor(e,t,r,o){this.clientUrl=e;this.clientAuthToken=t;this.deploymentName=r;this.userAgent=o}static{i(this,"RemoteRateLimitClient")}static instance;isEnabled(){return this.clientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:t,method:r,requestId:o}){ba(e,"url");let s=await Z.fetch(`${this.clientUrl}${e}`,{method:r,body:t,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=s.headers.get("Content-Type")?.includes("application/json")?await s.json():await s.text();if(s.ok)return a;throw s.status===401?new W("Rate limiting service failed with 401: Unauthorized"):new W(`Rate limiting service failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}async multiCount(e,t){return(await this.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async multiIncrement(e,t){return(await this.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async getCountAndUpdateExpiry(e,t,r){let o=Math.floor(t*60);return await this.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:o,key:e}),requestId:r})}async getQuota(e,t){let r=await at(e);return await this.fetch({url:`/quota/${r}`,method:"GET",requestId:t})}async setQuota(e,t,r){let o=await at(e);await this.fetch({url:`/quota/${o}`,method:"POST",body:JSON.stringify(t),requestId:r})}},Je;function Qe(n,e){if(Je)return Je;if(!h.instance.authApiJWT)return e.info("Using in-memory rate limit client for local development."),Je=new Jo,Je;let{authApiJWT:t,redisURL:r}=h.instance;if(!xe(r))throw new W(`RateLimitClient used in policy '${n}' - rate limit service URL not configured`);if(!xe(t))throw new W(`RateLimitClient used in policy '${n}' - service authentication not configured`);if(r&&(Je=new Qo(r,t,h.instance.deploymentName??"unknown",h.instance.systemUserAgent)),!Je||!Je.isEnabled())throw new W(`RateLimitClient used in policy '${n}' - no remote rate limiting service enabled`);return Je}i(Qe,"getRateLimitClient");var Sl=i(n=>{let e=n.headers.get("x-real-ip")??n.headers.get("true-client-ip")??n.headers.get("cf-connecting-ip");if(e)return e;let t=n.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP");function Rt(n,e){return{function:_l(e,"RateLimitInboundPolicy",n),user:kl,ip:Al,all:Ll}[e.rateLimitBy??"ip"]}i(Rt,"getRateLimitByFunctions");var Al=i(async n=>({key:`ip-${Sl(n)}`}),"getIP"),kl=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),Ll=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll");function _l(n,e,t){let r;if(n.rateLimitBy==="function"){if(!n.identifier)throw new g(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new g(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new g(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=n.identifier.module[n.identifier.export],!r||typeof r!="function")throw new g(`${e} '${t}' - Custom rate limit function must be a valid function`)}return i(async(s,a,u)=>{let c=await r(s,a,u);if(!c||typeof c!="object"){let l=`${e} '${u}' - Custom rate limit function must return a valid object.`;throw a.log.error(l),new S(l)}if(!("key"in c)){let l=`${e} '${u}' - Custom rate limit function must return a valid key property.`;throw a.log.error(l,c),new S(l)}if(typeof c.key!="string"){let l=`${e} '${u}' - Custom rate limit function must return a valid key property of type string. Received type '${typeof c.key}'`;throw a.log.error(l),new S(l)}return c},"outerFunction")}i(_l,"wrapUserFunction");var Pt="Retry-After";var wa=he("zuplo:policies:ComplexRateLimitInboundPolicy"),Yo=Symbol("complex-rate-limit-counters"),Xo=class n extends ae{static{i(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let r=oe.get(e,Yo)??{};Object.assign(r,t),oe.set(e,Yo,t)}static getIncrements(e){return oe.get(e,Yo)??{}}constructor(e,t){super(e,t),f("policy.inbound.complex-rate-limit-inbound"),K(e,t).required("rateLimitBy","string").required("timeWindowMinutes","number").required("limits","object").optional("headerMode","string").optional("throwOnFailure","boolean").optional("mode","string").optional("identifier","object"),e.identifier&&K(e.identifier,t,"policy","identifier").required("export","string").required("module","object");for(let[r,o]of Object.entries(e.limits))if(typeof o!="number")throw new g(`ComplexRateLimitInboundPolicy '${this.policyName}' - The value of the limits must be numbers. The limit ${r} is set to type '${typeof e}'.`)}async handler(e,t){let r=Date.now(),o=Q.getLogger(t),s=Qe(this.policyName,o),a=i((c,l)=>{if(this.options.throwOnFailure)throw new W(c,{cause:l});o.error(c,l)},"throwOrLog"),u=i((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[Pt]=l.toString()),x.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l=await Rt(this.policyName,this.options)(e,t,this.policyName),d=h.instance.isTestMode||h.instance.isWorkingCopy?h.instance.build.BUILD_ID:"",p=Object.assign({},this.options.limits,l.limits),m=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;t.addResponseSendingFinalHook(async()=>{try{let v=n.getIncrements(t);wa(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(v)}`);let N=Object.entries(p).map(([j])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${j}`,ttlSeconds:m,increment:v[j]??0})),k=s.multiIncrement(N,t.requestId);t.waitUntil(k),await k}catch(v){o.error(v),t.log.error(v)}});let y=Object.entries(p).map(([v,N])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${v}`,ttlSeconds:m,limit:N})),A=await s.multiCount(y,t.requestId);return Nl(A,y).length>0?u(this.options.headerMode??"retry-after",m):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-r;wa(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function Nl(n,e){let t=[];for(let r of n){let o=e.find(s=>s.key===r.key)?.limit||0;r.count>=o&&t.push(r)}return t}i(Nl,"findOverLimits");var Dl=i(async(n,e,t,r)=>{if(f("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new g(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=ge.instance,s=Ut(t.policies,o?.routeData.policies);return Zr(s)(n,e)},"CompositeInboundPolicy");var Ml=i(async(n,e,t,r,o)=>{if(f("policy.outbound.composite"),!r.policies||r.policies.length===0)throw new g(`CompositeOutboundPolicy '${o}' must have valid policies defined`);let s=ge.instance,a=Zt(r.policies,s?.routeData.policies);return $r(a)(n,e,t)},"CompositeOutboundPolicy");var ql=i(async(n,e,t,r)=>{f("policy.inbound.curity-phantom-token-auth");let o=n.headers.get("Authorization");if(!o)return x.unauthorized(n,e,{detail:"No authorization header"});let s=Hl(o);if(!s)return x.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await se(r,void 0,t),u=new re(a,e),c=await u.get(s);if(!c){let l=await Z.fetch(t.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${t.clientId}:${t.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(s,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),x.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):x.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function Hl(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(Hl,"getToken");var Ul=i(async(n,e,t,r)=>(f("policy.inbound.firebase-jwt-auth"),K(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),Re(n,e,{issuer:`https://securetoken.google.com/${t.projectId}`,audience:t.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var Zl=i(async(n,e,t)=>{f("policy.inbound.form-data-to-json");let r="application/x-www-form-urlencoded",o="multipart/form-data",s=n.headers.get("content-type")?.toLowerCase();if(!s||![o,r].includes(s))return t&&t.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):n;let a=await n.formData();if(t&&t.optionalHoneypotName&&a.get(t.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(n.headers);return c.set("content-type","application/json"),c.delete("content-length"),new te(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var It="__unknown__",$l=i(async(n,e,t,r)=>{f("policy.inbound.geo-filter");let o={allow:{countries:xt(t.allow?.countries,"allow.countries",r),regionCodes:xt(t.allow?.regionCodes,"allow.regionCode",r),asns:xt(t.allow?.asns,"allow.asOrganization",r)},block:{countries:xt(t.block?.countries,"block.countries",r),regionCodes:xt(t.block?.regionCodes,"block.regionCode",r),asns:xt(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??It,a=e.incomingRequestProperties.regionCode?.toLowerCase()??It,u=e.incomingRequestProperties.asn?.toString()??It,c=o.ignoreUnknown&&s===It,l=o.ignoreUnknown&&a===It,d=o.ignoreUnknown&&u===It,p=o.allow.countries,m=o.allow.regionCodes,y=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||m.length>0&&!m.includes(a)&&!l||y.length>0&&!y.includes(u)&&!d)return Et(n,e,r,s,a,u);let A=o.block.countries,P=o.block.regionCodes,v=o.block.asns;return A.length>0&&A.includes(s)&&!c||P.length>0&&P.includes(a)&&!l||v.length>0&&v.includes(u)&&!d?Et(n,e,r,s,a,u):n},"GeoFilterInboundPolicy");function Et(n,e,t,r,o,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${s}')`),x.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:s}})}i(Et,"blockedResponse");function xt(n,e,t){if(typeof n=="string")return n.split(",").map(r=>r.trim().toLowerCase());if(typeof n>"u")return[];if(Array.isArray(n))return n.map(r=>r.trim().toLowerCase());throw new g(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}i(xt,"toLowerStringArray");var Fl=i(async(n,e,t)=>{f("policy.inbound.jwt-scope-validation");let r=n.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(r,t.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var jl=i(async(n,e,t,r)=>{f("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return ei(r,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(o),a=[];if(s.length===0)return ei(r,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(m=>{a.push({responseName:u,contentName:l,exampleName:m,exampleValue:d[m]})})})}),a=a.filter(u=>!(t.responsePrefixFilter&&!u.responseName.startsWith(t.responsePrefixFilter)||t.contentType&&u.contentName!==t.contentType||t.exampleName&&u.exampleName!==t.exampleName)),t.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return Ra(a[u])}else return a.length>0?Ra(a[0]):ei(r,n,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function Ra(n){let e=JSON.stringify(n.exampleValue,null,2),t=new Headers;switch(t.set("Content-Type",n.contentName),n.responseName){case"1XX":return new Response(e,{status:100,headers:t});case"2XX":return new Response(e,{status:200,headers:t});case"3XX":return new Response(e,{status:300,headers:t});case"4XX":return new Response(e,{status:400,headers:t});case"5XX":case"default":return new Response(e,{status:500,headers:t});default:return new Response(e,{status:Number(n.responseName),headers:t})}}i(Ra,"generateResponse");var ei=i((n,e,t,r)=>{let o=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${r}`;return x.internalServerError(e,t,{detail:o})},"getProblemDetailResponse");var zl="Incoming",Bl={logRequestBody:!0,logResponseBody:!0};function Pa(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}i(Pa,"headersToObject");function Ia(){return new Date().toISOString()}i(Ia,"timestamp");var ti=new WeakMap,Gl={};function Vl(n,e){let t=ti.get(n);t||(t=Gl);let r=Object.assign({...t},e);ti.set(n,r)}i(Vl,"setMoesifContext");async function Ea(n,e){let t=n.headers.get("content-type");if(t&&t.indexOf("json")!==-1)try{return await n.clone().json()}catch(o){e.log.error(o)}let r=await n.clone().text();return e.log.debug({textBody:r}),r}i(Ea,"readBody");var Wl={},ni;function xa(){if(!ni)throw new S("Invalid State - no _lastLogger");return ni}i(xa,"getLastLogger");function Kl(n){let e=Wl[n];return e||(e=new Y("moesif-inbound",100,async t=>{let r=JSON.stringify(t);xa().debug("posting",r);let o=await Z.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||xa().error({status:o.status,body:await o.text()})})),e}i(Kl,"getDispatcher");async function Jl(n,e,t,r){f("policy.inbound.moesif-analytics"),ni=e.log;let o=Ia(),s=Object.assign(Bl,t);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await Ea(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Kl(s.applicationId),d=n.headers.get("true-client-ip"),p=ti.get(e)??{},m={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Pa(n.headers)},y=s.logResponseBody?await Ea(u,e):void 0,A={time:Ia(),status:u.status,headers:Pa(u.headers),body:y},P={request:m,response:A,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:zl};l.enqueue(P),e.waitUntil(l.waitUntilFlushed())}),n}i(Jl,"MoesifInboundPolicy");async function Ta(n,e,t,r){let o=Q.getLogger(n),{authApiJWT:s,meteringServiceUrl:a}=h.instance,u;try{let l=await Z.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription`,l)}let c=u&&u.data&&u.data.length>0?u.data:void 0;return c&&c.length>1?c.sort((d,p)=>d.createdOn>p.createdOn?-1:1)[0]:c&&c[0]}i(Ta,"loadSubscription");async function va(n,e,t,r,o){let{authApiJWT:s,meteringServiceUrl:a}=h.instance,u=Q.getLogger(n);try{let c=await Z.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`,c)}}i(va,"consumeSubcriptionQuotas");var Ql=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function Hn(n,e){try{let t=[];for(let r in n)typeof n[r]!="number"&&!(Number.isInteger(n[r])&&/^-?\d+$/.test(n[r].toString()))&&t.push(r);if(t.length>0)throw new g(t.length>1?`The values found in these properties are not integers : ${t.join(", ")}`:`The value in property '${t[0]}' is not an integer`)}catch(t){throw t instanceof g?new g(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}i(Hn,"validateMeters");function Ca(n,e){if(n)try{if(n.length===0)throw new g("Must set valid subscription statuses");let t=ot(n),r=[];for(let o of t)Ql.has(o)||r.push(o);if(r.length>0)throw new g(`Found the following invalid statuses: ${r.join(", ")}`);return n}catch(t){throw t instanceof g?new g(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}i(Ca,"parseAllowedSubscriptionStatuses");function Oa(n,e){let t={},r={};for(let o in e)n.hasOwnProperty(o)?t[o]=e[o]:r[o]=e[o];return{metersInSubscription:t,metersNotInSubscription:r}}i(Oa,"compareMeters");var ri=class extends ae{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return oe.get(e,At)}static setMeters(e,t){Hn(t,"setMeters");let r=oe.get(e,kt)??{};Object.assign(r,t),oe.set(e,kt,r)}constructor(e,t){super(e,t),f("policy.inbound.monetization")}async handler(e,t){K(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let r=this.options.allowRequestsOverQuota??!1,o=Be(this.options.meterOnStatusCodes),s=oe.get(t,kt),a={...this.options.meters,...s};Hn(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=Ca(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(P,v,N)=>{let k=oe.get(N,At);if((this.options.allowRequestsWithoutSubscription??!1)&&!k){N.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let q=oe.get(N,kt),$={...this.options.meters,...q};if(Hn($,this.policyName),o.includes(P.status)&&k&&$){N.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${k.id}' with meters '${JSON.stringify($)} on response status '${P.status}'`);let{metersInSubscription:E,metersNotInSubscription:H}=Oa(k.meters,$);if(H&&Object.keys(H).length>0){let G=Object.keys(H);N.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${G}'`)}await va(N,k.id,this.policyName,this.options.bucketId,E)}});let l=e.user;if(!l)return u?e:x.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new g(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await Ta(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:x.unauthorized(e,t,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return t.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),x.unauthorized(e,t,{detail:"No valid subscription found"});c.includes(p.status)&&(t.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),oe.set(t,At,p));let m=oe.get(t,At);if(!m)return u?e:(t.log.warn("Subscription is not available for user"),x.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(m&&Object.keys(m.meters).length===0)return t.log.error(`Quota is not set up for subscription '${m.id}'`),x.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let A=Object.keys(a).filter(P=>!Object.keys(m.meters).includes(P));if(A.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${A.join(", ")}`),x.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${A.join(", ")}`,title:"Quota Exceeded"});for(let P of Object.keys(a))if(m.meters[P].available<=0&&!r)return x.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${P}'`,title:"Quota Exceeded"});return e}};async function Un(n,e){let t=new URLSearchParams({client_id:n.clientId,client_secret:n.clientSecret,grant_type:"client_credentials"});n.scope&&t.append("scope",n.scope),n.audience&&t.append("audience",n.audience);let r=await ye({retries:n.retries?.maxRetries??3,retryDelayMs:n.retries?.delayMs??10},n.tokenEndpointUrl,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let s=await r.text();e.log.error(`Error getting token from identity provider. Status: ${r.status}`,s)}catch{}throw new S("Error getting token from identity provider.")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new S("Response returned from identity provider is not in the expected format.")}i(Un,"getClientCredentialsAccessToken");var Tt=class extends Error{constructor(t,r,o){super(r,o);this.code=t}static{i(this,"OpenFGAError")}},Zn=class{static{i(this,"BaseOpenFGAClient")}apiUrl;storeId;authorizationModelId;constructor(e){this.apiUrl=e.apiUrl,this.storeId=e.storeId,this.authorizationModelId=e.authorizationModelId}getStoreId(e={},t=!1){let r=e?.storeId||this.storeId;if(!t&&!r)throw new Error("storeId is required");return r}getAuthorizationModelId(e={}){return e?.authorizationModelId||this.authorizationModelId}async get(e,t){return this.fetch(e,"GET",t)}async put(e,t,r){return this.fetch(e,"PUT",r,t)}post(e,t,r){return this.fetch(e,"POST",r,t)}async fetch(e,t,r,o){let s=new Headers(r.headers||{});s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.set("User-Agent",h.instance.systemUserAgent);let a=`${this.apiUrl}${e}`,u=new Request(a,{method:t,headers:s,body:o?JSON.stringify(o):void 0}),c=await Z.fetch(u);if(c.status!==200){let l;try{l=await c.json()}catch{}throw!l||!l.code||!l.message?new Tt("unknown",`Unknown error. Status: ${c.status}`):new Tt(l.code,l.message)}return c.json()}};function Qt(n,e,t){!n[e]&&t&&(n[e]=t)}i(Qt,"setHeaderIfNotSet");var Sa="X-OpenFGA-Client-Method",Aa="X-OpenFGA-Client-Bulk-Request-Id",Yt=class extends Zn{static{i(this,"OpenFGAClient")}async check(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/check`,{tuple_key:{user:e.user,relation:e.relation,object:e.object},context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]},authorization_model_id:this.getAuthorizationModelId(t)},t)}async batchCheck(e,t={}){let{headers:r={}}=t;return Qt(r,Sa,"BatchCheck"),Qt(r,Aa,crypto.randomUUID()),{responses:await Promise.all(e.map(async s=>this.check(s,Object.assign({},t,r)).then(a=>(a._request=s,a)).catch(a=>{if(a instanceof Tt)throw a;return{allowed:void 0,error:a,_request:s}})))}}async expand(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/expand`,{authorization_model_id:this.getAuthorizationModelId(t),tuple_key:e},t)}async listObjects(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-objects`,{authorization_model_id:this.getAuthorizationModelId(t),user:e.user,relation:e.relation,type:e.type,context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]}},t)}async listRelations(e,t={}){let{user:r,object:o,relations:s,contextualTuples:a,context:u}=e,{headers:c={}}=t;if(Qt(c,Sa,"ListRelations"),Qt(c,Aa,crypto.randomUUID()),!s?.length)throw new Error("When calling listRelations, at least one relation must be passed in the relations field");let l=await this.batchCheck(s.map(p=>({user:r,relation:p,object:o,contextualTuples:a,context:u})),Object.assign({},t,c)),d=l.responses.find(p=>p.error);if(d)throw d.error;return{relations:l.responses.filter(p=>p.allowed).map(p=>p._request.relation)}}async listUsers(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-users`,{authorization_model_id:this.getAuthorizationModelId(t),relation:e.relation,object:e.object,user_filters:e.user_filters,context:e.context,contextual_tuples:e.contextualTuples||[]},t)}};var ka=Symbol("openfga-authz-context-data"),vt=class extends ae{static{i(this,"BaseOpenFGAAuthZInboundPolicy")}client;authorizer;cache;static setContextChecks(e,t){let r=Array.isArray(t)?t:[t];oe.set(e,ka,r)}constructor(e,t){if(super(e,t),K(e,t).required("apiUrl","string").optional("storeId","string").optional("authorizationModelId","string"),!e.credentials)throw new g(`${this.policyType} '${this.policyName}' - The 'credentials' option is required.`);if(e.credentials.method==="client-credentials")K(e.credentials,t).required("clientId","string").required("clientSecret","string").required("oauthTokenEndpointUrl","string").optional("apiAudience","string");else if(e.credentials.method==="api-token")K(e.credentials,t).required("token","string").optional("headerName","string").optional("headerValuePrefix","string");else if(e.credentials.method==="header")K(e.credentials,t).optional("headerName","string");else if(e.credentials.method!=="none")throw new g(`${this.policyType} '${this.policyName}' - The 'credentials.type' option is invalid. It must be set to either 'none', 'api-token', 'client-credentials', or 'header'.`);this.authorizer=this.getAuthorizer(e.credentials),this.client=new Yt({apiUrl:e.apiUrl,storeId:e.storeId,authorizationModelId:e.authorizationModelId})}async handler(e,t){if(!this.cache){let a=await se(this.policyName,void 0,this.options);this.cache=new re(a,t)}let r=i(a=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=oe.get(t,ka);if(!o||o.length===0)throw new S(`${this.policyType} '${this.policyName}' - No checks found in the context.`);let s=await this.authorizer(e,t);try{t.log.debug("OpenFGA checks",o);let a=await this.client.batchCheck(o,{headers:s});return t.log.debug("OpenFGA Response",a),a.responses.every(u=>u.allowed)?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling OpenFGA service`,a),x.internalServerError(e,t)}}getAuthorizer(e){if(e.method==="none")return async()=>({});if(e.method==="header")return async t=>{let r=e.headerName??"Authorization",o=t.headers.get(r);if(!o)throw new W(`${this.policyType} '${this.policyName}' - The header '${r}' is missing.`);return{[r]:o}};if(e.method==="api-token")return async()=>({[e.headerName??"Authorization"]:`${e.headerValuePrefix??"Bearer "} ${e.token}`});if(e.method==="client-credentials")return async(t,r)=>{let o=await this.cache?.get("client_credentials_token");if(o)return{Authorization:`Bearer ${o}`};let s=await Un({tokenEndpointUrl:e.oauthTokenEndpointUrl,clientId:e.clientId,clientSecret:e.clientSecret,audience:e.apiAudience},r);return this.cache?.put("client_credentials_token",s.access_token,s.expires_in),{Authorization:`Bearer ${s.access_token}`}};throw new S("Invalid state for credentials method is not valid. This should not happen.")}};var La=["us1","eu1","au1"],oi=class extends vt{static{i(this,"OktaFGAAuthZInboundPolicy")}constructor(e,t){if(!La.includes(e.region))throw new g(`OktaFGAAuthZInboundPolicy '${t}' - The 'region' option is invalid. Must be one of ${La.join(", ")}.`);let r={...e,apiUrl:`https://api.${e.region}.fga.dev`,credentials:{method:"client-credentials",oauthTokenEndpointUrl:"https://fga.us.auth0.com/oauth/token",clientId:e.credentials.clientId,clientSecret:e.credentials.clientSecret,apiAudience:`https://api.${e.region}.fga.dev/`}};super(r,t),f("policy.inbound.oktafga-authz")}};var Yl=i(async(n,e,t,r)=>(f("policy.inbound.okta-jwt-auth"),Re(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"OktaJwtInboundPolicy");var ii=class extends vt{static{i(this,"OpenFGAAuthZInboundPolicy")}constructor(e,t){super(e,t),f("policy.inbound.openfga-authz")}};import{importSPKI as Xl}from"jose";var si,ed=i(async(n,e,t,r)=>{if(f("policy.inbound.propel-auth-jwt-auth"),!si)try{si=await Xl(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return Re(n,e,{issuer:t.authUrl,secret:si,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var ai="quota-inbound-policy-f307056c-8c00-4f2c-b4ac-c0ac7d04eca0",_a="quota-usage-2017e968-4de8-4a63-8951-1e423df0d64b";var ui=class n extends ae{static{i(this,"QuotaInboundPolicy")}constructor(e,t){super(e,t),f("policy.inbound.quota")}async handler(e,t){let r=this.options.debug??!1;t.log.debug({debug:r}),K(this.options,this.policyName).required("period","string").required("quotaBy","string").optional("quotaAnchorMode","string").optional("allowances","object"),n.setMeters(t,{requests:1});let o=Q.getLogger(t);try{let s=td(this.options,this.policyName),a=s.functions.getAnchorDate(e,t,this.policyName),u=s.functions.getQuotaDetail(e,t,this.policyName),[c,l]=await Promise.all([a,u]),d=nd(l.key,this.policyName);r&&t.log.debug(`QuotaInboundPolicy: key - '${d}'`);let p=Qe(this.policyName,o),m=await p.getQuota(d,t.requestId);n.#e(t,this.policyName,m),r&&t.log.debug("QuotaInboundPolicy: quotaResult",m),c&&new Date(m.anchorDate)!==c&&t.log.warn(`QuotaInboundPolicy '${this.policyName}' provided anchorDate ('${c}') did not match the stored, immutable anchorDate ('${m.anchorDate}')`);let y=Object.assign({},s.defaultAllowances);Object.assign(y,l.allowances);let A=[],P="";if(Object.entries(y).forEach(([v,N])=>{r&&(P+=`${v} - allowed: ${N} value: ${m.meters[v]??0}
72
+ `),(m.meters[v]??0)>=N&&A.push(v)}),r&&t.log.debug("QuotaInboundPolicy: debugTable",P),A.length>0)return x.tooManyRequests(e,t,{detail:`Quota exceeded for meters '${A.join(", ")}'`});t.addResponseSendingFinalHook(async(v,N,k)=>{if(r&&k.log.debug(`QuotaInboundPolicy: backend response - ${v.status}: ${v.statusText}`),!s.quotaOnStatusCodes.includes(v.status))return;let j=oe.get(k,ai),q={config:{period:s.period,anchorDate:c?.toISOString()??""},increments:j};r&&k.log.debug("QuotaInboundPolicy: setQuotaDetails",q);let $=p.setQuota(d,q,k.requestId);k.waitUntil($)})}catch(s){o.error(s),t.log.error(s)}return e}static setMeters(e,t){let r=oe.get(e,ai)??{};Object.assign(r,t),oe.set(e,ai,r)}static getUsage(e,t){let r=oe.get(e,`${_a}-${t}`);if(r===void 0)throw new S(`QuotaInboundPolicy.getUsage was called for policy named '${t}' but the policy itself has not yet executed.`);return r}static#e(e,t,r){oe.set(e,`${_a}-${t}`,r)}};function td(n,e){let t=i(async s=>({key:`user-1385b4e8-800f-488e-b089-c197544e5801-${s.user?.sub}`,allowances:n.allowances??{}}),"getQuotaDetail"),r=i(async()=>{},"getAnchorDate");if(n.quotaBy==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getQuotaDetailExport===void 0)throw new g(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getQuotaDetailExport' is required when 'quotaBy' is 'function'`);t=n.identifier.module[n.identifier.getQuotaDetailExport]}if(n.quotaAnchorMode==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getAnchorDateExport===void 0)throw new g(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getAnchorDateExport' is required when 'quotaAnchorMode' is 'function'`);r=n.identifier.module[n.identifier.getAnchorDateExport]}return{period:n.period,quotaBy:n.quotaBy??"user",quotaAnchorMode:n.quotaAnchorMode??"first-api-call",quotaOnStatusCodes:Be(n.quotaOnStatusCodes??"200-299"),defaultAllowances:Object.assign({},n.allowances),functions:{getQuotaDetail:t,getAnchorDate:r}}}i(td,"validateAndParseOptions");function nd(n,e){return encodeURIComponent(`${e}-${n}`)}i(nd,"processKey");var Na=he("zuplo:policies:RateLimitInboundPolicy"),Da=i(async(n,e,t,r)=>{let o=Q.getLogger(e),s=i(($,E)=>{let H={};return(!$||$==="retry-after")&&(H[Pt]=E.toString()),x.tooManyRequests(n,e,void 0,H)},"rateLimited"),u=await Rt(r,t)(n,e,r),c=u.key,l=u.requestsAllowed??t.requestsAllowed,d=u.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",m=Qe(r,o),A=`rate-limit${h.instance.isTestMode?h.instance.build.BUILD_ID:""}/${r}/${c}`,P=await se(r,void 0,t),v=new re(P,e),N=m.getCountAndUpdateExpiry(A,d,e.requestId),k;i(async()=>{let $=await N;if($.count>l){let E=Date.now()+$.ttlSeconds*1e3;v.put(A,E,$.ttlSeconds),Na(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${A}' (async mode)`),k=s(p,$.ttlSeconds)}},"asyncCheck")();let q=await v.get(A);if(q!==void 0&&q>Date.now()){Na(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${A}' (async mode)`);let $=Math.round((q-Date.now())/1e3);return s(p,$)}return e.addResponseSendingHook(async $=>k??$),n},"AsyncRateLimitInboundPolicyImpl");var Ma=he("zuplo:policies:RateLimitInboundPolicy"),rd="strict",qa=i(async(n,e,t,r)=>{if(f("policy.inbound.rate-limit"),(t.mode??rd)==="async")return Da(n,e,t,r);let s=Date.now(),a=Q.getLogger(e),u=i((l,d)=>{if(t.throwOnFailure)throw new W(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[Pt]=d.toString()),x.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await Rt(r,t)(n,e,r),p=d.key,m=d.requestsAllowed??t.requestsAllowed,y=d.timeWindowMinutes??t.timeWindowMinutes,A=t.headerMode??"retry-after",P=Qe(r,a),N=`rate-limit${h.instance.isTestMode||h.instance.isWorkingCopy?h.instance.build.BUILD_ID:""}/${r}/${p}`,k=await P.getCountAndUpdateExpiry(N,y,e.requestId);return k.count>m?(Ma(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${N}' (strict mode)`),c(A,k.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-s;Ma(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var ci;function Ha(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}i(Ha,"headersToNameValuePairs");function od(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}i(od,"queryToNameValueParis");function id(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}i(id,"parseIntOrUndefined");var Ua={};async function sd(n,e,t,r){f("policy.inbound.readme-metrics");let o=new Date,s=Date.now();return ci||(ci={name:"zuplo",version:h.instance.build.ZUPLO_VERSION,comment:`zuplo/${h.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?rt(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?rt(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:h.instance.isWorkingCopy||h.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:ci,entries:[{startedDateTime:o.toISOString(),time:Date.now()-s,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:Ha(n.headers),queryString:od(n.query)},response:{status:a.status,statusText:a.statusText,headers:Ha(a.headers),content:{size:id(n.headers.get("content-length"))}}}]}}},d=Ua[t.apiKey];if(!d){let p=t.apiKey;d=new Y("readme-metering-inbound-policy",10,async m=>{try{let y=t.url??"https://metrics.readme.io/request",A=await Z.fetch(y,{method:"POST",body:JSON.stringify(m),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});A.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${A.status}: '${await A.text()}'`)}catch(y){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${y.message}'`),y}}),Ua[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}i(sd,"ReadmeMetricsInboundPolicy");var ad=i(async(n,e,t,r)=>{f("policy.inbound.remove-headers");let o=t?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new g(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let s=new Headers(n.headers);return o.forEach(u=>{s.delete(u)}),new te(n,{headers:s})},"RemoveHeadersInboundPolicy");var ud=i(async(n,e,t,r,o)=>{f("policy.outbound.remove-headers");let s=r?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new g(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(n.headers);return s.forEach(c=>{a.delete(c)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var cd=i(async(n,e,t,r)=>{f("policy.inbound.remove-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length===0)throw new g(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let s=new URL(n.url);return o.forEach(u=>{s.searchParams.delete(u)}),new te(s.toString(),n)},"RemoveQueryParamsInboundPolicy");var ld=i(async(n,e,t,r)=>{f("policy.outbound.replace-string");let o=await n.text(),s=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(s,r.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var Za=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),dd=i(async(n,e,t)=>{f("policy.inbound.request-size-limit");let r=t.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(n.method))return n;let o=n.headers.get("content-length"),s=o!==null?parseInt(o):void 0;return s&&!isNaN(s)&&s>t.maxSizeInBytes?Za():s&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?Za():n},"RequestSizeLimitInboundPolicy");var Ct=i(n=>{let e=n.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),Ot=i((n,e,t,r,o)=>{let s=[],a=!0,u=[];return n.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,s.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=Bn(t,r,o,c.name),p=ge.instance.schemaValidator[d],m=p(e[c.name]),y=li(p.errors);m||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${y.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),Ae=i((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),ke=i(n=>n==="log-only"||n==="reject-and-log","shouldLog"),Le=i(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),li=i(n=>n?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function $a(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(y){let A=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,P=x.badRequest(e,n,{detail:`${A}, see errors property for more details`,errors:`${y}`});if(ke(t.validateBody)&&Ae(n,t.logLevel??"info",A,[r],y),Le(t.validateBody))return P}if(!e.headers.get("Content-Type")){let y=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,A=x.badRequest(e,n,{detail:y});return ke(t.validateBody)&&Ae(n,t.logLevel??"info",y,[r],[y]),Le(t.validateBody)?A:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=Gn(n.route.path,e.method,o),u=ge.instance.schemaValidator[a];if(!u){let y=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,A=x.badRequest(e,n,{detail:y});return ke(t.validateBody)&&Ae(n,t.logLevel??"info",y,[r],[y]),Le(t.validateBody)?A:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=li(l),m=x.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(ke(t.validateBody)&&Ae(n,t.logLevel??"info",d,[r],p),Le(t.validateBody))return m}i($a,"handleBodyValidation");function Fa(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Ct(n),s=Ot(o.filter(a=>a.location==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=x.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:s.errors});if(ke(t.validateHeaders)&&Ae(n,t.logLevel??"info",a,s.invalidValues,s.errors),Le(t.validateHeaders))return u}}i(Fa,"handleHeadersValidation");function ja(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=Ct(n),o=Ot(r.filter(s=>s.location==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let s="Path parameters validation failed",a=x.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(ke(t.validatePathParameters)&&Ae(n,t.logLevel??"info",s,o.invalidValues,o.errors),Le(t.validatePathParameters))return a}}i(ja,"handlePathParameterValidation");function za(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=Ct(n),o=Ot(r.filter(s=>s.location==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let s="Query parameters validation failed",a=x.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(ke(t.validateQueryParameters)&&Ae(n,t.logLevel??"info",s,o.invalidValues,o.errors),Le(t.validateQueryParameters))return a}}i(za,"handleQueryParameterValidation");var Ba=i(async(n,e,t)=>{f("policy.inbound.request-validation");let r=za(e,n,t);if(r!==void 0||(r=ja(e,n,t),r!==void 0)||(r=Fa(e,n,t),r!==void 0))return r;let o=await $a(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),pd=Ba;var md=i(async(n,e,t,r)=>{if(f("policy.inbound.require-origin"),t.origins===void 0||t.origins.length===0)throw new g(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof t.origins=="string"?t.origins.split(","):t.origins;o=o.map(a=>a.trim());let s=n.headers.get("origin");if(!s||!o.includes(s)){let a=t.failureDetail??"Forbidden";return x.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var gd=i(async(n,e,t)=>(f("policy.inbound.set-body"),new te(n,{body:t.body})),"SetBodyInboundPolicy");var fd=i(async(n,e,t,r)=>{f("policy.inbound.set-headers");let o=t.headers;if(!o||!Array.isArray(o)||o.length==0)throw new g(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let s=new Headers(n.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new g(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.has(u.name)||c)&&s.set(u.name,u.value)}),new te(n,{headers:s})},"SetHeadersInboundPolicy");var hd=i(async(n,e,t,r,o)=>{f("policy.outbound.set-headers");let s=r.headers;if(!s||!Array.isArray(s)||s.length==0)throw new g(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return s.forEach(c=>{if(!c.name||c.name.length===0)throw new g(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"SetHeadersOutboundPolicy");var yd=i(async(n,e,t,r)=>{f("policy.inbound.set-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length==0)throw new g(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let s=new URL(n.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new g(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.searchParams.has(u.name)||c)&&s.searchParams.set(u.name,u.value)}),new te(s.toString(),n)},"SetQueryParamsInboundPolicy");var bd=i(async(n,e,t,r,o)=>{if(f("policy.outbound.set-status"),!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(n.body,{headers:n.headers,status:r.status,statusText:r.statusText??n.statusText})},"SetStatusOutboundPolicy");var wd=i(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),Rd=i(async(n,e,t,r)=>{if(f("policy.inbound.sleep"),!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new g(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await wd(t.sleepInMs),n},"SleepInboundPolicy");var Pd=i(async(n,e,t,r)=>{f("policy.inbound.supabase-jwt-auth"),K(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},s=await Re(n,e,o,r);if(s instanceof Response)return s;if(!(s instanceof te))throw new W("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return s;let u=n.user?.data.app_metadata;if(!u)throw new S(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?x.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var Id=i(async(n,e,t,r)=>{f("policy.inbound.upstream-azure-ad-service-auth"),K(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await se(r,void 0,t),s=new re(o,e),a=await s.get(r);if(!a){let u=await Ed(t,e);s.put(r,u.access_token,u.expires_in-(t.expirationOffsetSeconds??300)),a=u.access_token}return n.headers.set("Authorization",`Bearer ${a}`),n},"UpstreamAzureAdServiceAuthInboundPolicy");async function Ed(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await ye({retries:n.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${n.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let s=await r.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new S("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 S("Response returned from Azure AD is not in the expected format.")}i(Ed,"getAccessToken");var Ga="https://accounts.google.com/o/oauth2/token",di,xd=i(async(n,e,t,r)=>{f("policy.inbound.upstream-firebase-admin-auth"),K(t,r).required("serviceAccountJson","string"),di||(di=await Te.init(t.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},s=await se(r,void 0,t),a=new re(s,e),u=await a.get(r);if(!u){let c=await Ne({serviceAccount:di,audience:Ga,payload:o}),l=await wn(Ga,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new S("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var Td="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",vd=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],pi,Cd=i(async(n,e,t,r)=>{if(f("policy.inbound.upstream-firebase-user-auth"),K(t,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!t.userId&&!t.userIdPropertyPath)throw new g(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof t.developerClaims<"u"){for(let p in t.developerClaims)if(Object.prototype.hasOwnProperty.call(t.developerClaims,p)){if(vd.indexOf(p)!==-1)throw new g(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}pi||(pi=await Te.init(t.serviceAccountJson));let s=t.userId;if(!s&&!t.userIdPropertyPath){if(!n.user)throw new S("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new S(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=rt(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new S(`Unable to determine user from for the policy ${r}`);let a=await se(r,void 0,t),u=new re(a,e),c={uid:s,claims:o},l=await at(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await Ne({serviceAccount:pi,audience:Td,payload:c}),m=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,y=await qs(m,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!y.idToken)throw new S("Invalid token response from Firebase");d=y.idToken,u.put(l,d,(y.expiresIn?parseInt(y.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var Xt=class{static{i(this,"ZuploServices")}static async getIDToken(e,t){let r=new re("0c13603a-a19f-4f03-a04a-50aa393f7ffa-zuplo-tokens",e),o=await se("zuplo-token",void 0,t),s=await r.get(o);if(s)return s;let{authClientId:a,authClientSecret:u,developerApiUrl:c,zuploClientAuthBucketId:l}=h.instance;if(!a||!u)throw new S("Zuplo service authentication is not enabled for this deployment. Contact support assistance.");let d=await Un({tokenEndpointUrl:`${c}/v1/client-auth/${l}/oauth/token`,clientId:a,clientSecret:u,audience:t?.audience},e);return r.put(o,d.access_token,d.expires_in-300),d.access_token}};var Va="service-account-id-token",mi=class extends ae{static{i(this,"UpstreamGcpFederatedAuthInboundPolicy")}cacheName;normalizedWorkloadIdentityProvider;constructor(e,t){super(e,t),f("policy.inbound.upstream-gcp-federated-auth"),K(e,t).required("audience","string").required("serviceAccountEmail","string").required("workloadIdentityProvider","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number").optional("useMemoryCacheOnly","boolean").optional("tokenLifetime","number"),e.workloadIdentityProvider.startsWith("https://iam.googleapis.com/")?this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider.replace("https://iam.googleapis.com/",""):this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider}async handler(e,t){this.cacheName||(this.cacheName=await se(this.policyName,void 0,this.options));let r;this.options.useMemoryCacheOnly?r=new Fe(this.cacheName):r=new re(this.cacheName,t);let o=await r.get(Va);if(!o){let s=`https://iam.googleapis.com/${this.normalizedWorkloadIdentityProvider}`,a=await Xt.getIDToken(t,{audience:s}),u=await Ds(this.normalizedWorkloadIdentityProvider,a,{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!u.access_token||!u.expires_in)throw new S("Invalid token response from GCP");let c=u.access_token,l=await Ms({serviceAccountEmailOrIdentifier:this.options.serviceAccountEmail,audience:this.options.audience,accessToken:c},{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!l.token)throw new S("Invalid token response from GCP");o=l.token,r.put(Va,c,3600-(this.options.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${o}`),e}};var gi,Od=i(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-jwt"),K(t,r).required("audience","string").required("serviceAccountJson","string"),gi||(gi=await Te.init(t.serviceAccountJson));let o=await Ne({serviceAccount:gi,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var Wa="https://www.googleapis.com/oauth2/v4/token",fi,Sd=i(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-service-auth"),K(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),fi||(fi=await Te.init(t.serviceAccountJson));let o={};if(t.scopes&&t.audience)throw new g("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let c=ot(t.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof g?new g(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}t.audience&&(o.target_audience=`${t.audience}`);let s=await se(r,void 0,t),a;t.useMemoryCacheOnly?a=new Fe(s):a=new re(s,e);let u=await a.get(r);if(!u){let c=await Ne({serviceAccount:fi,audience:Wa,payload:o}),l=await wn(Wa,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new S("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new S("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var Ad=i(async(n,e,t)=>{f("policy.inbound.validate-json-schema");let r=n.clone(),o;try{o=await r.json()}catch{return x.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator.default(o))return n;let{errors:a}=t.validator.default;if(!a)throw new W("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return x.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var Ka=i(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=i((P,v)=>e(P,"name",{value:v,configurable:!0}),"__name"),o=i((P,v)=>i(function(){return v||(0,P[t(P)[0]])((v={exports:{}}).exports,v),v.exports},"__require"),"__commonJS"),s=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(P){var v={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:i(function(k,j){return j},"tagValueProcessor"),attributeValueProcessor:i(function(k,j){return j},"attributeValueProcessor"),stopNodes:[],alwaysCreateTextNode:!1,isArray:i(()=>!1,"isArray"),commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:i(function(k,j,q){return k},"updateTag")},N=r(function(k){return Object.assign({},v,k)},"buildOptions");P.buildOptions=N,P.defaultOptions=v}}),a=o({"node_modules/fast-xml-parser/src/util.js"(P){"use strict";var v=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",N=v+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",k="["+v+"]["+N+"]*",j=new RegExp("^"+k+"$"),q=r(function(E,H){let G=[],V=H.exec(E);for(;V;){let C=[];C.startIndex=H.lastIndex-V[0].length;let T=V.length;for(let U=0;U<T;U++)C.push(V[U]);G.push(C),V=H.exec(E)}return G},"getAllMatches"),$=r(function(E){let H=j.exec(E);return!(H===null||typeof H>"u")},"isName");P.isExist=function(E){return typeof E<"u"},P.isEmptyObject=function(E){return Object.keys(E).length===0},P.merge=function(E,H,G){if(H){let V=Object.keys(H),C=V.length;for(let T=0;T<C;T++)G==="strict"?E[V[T]]=[H[V[T]]]:E[V[T]]=H[V[T]]}},P.getValue=function(E){return P.isExist(E)?E:""},P.isName=$,P.getAllMatches=q,P.nameRegexp=k}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(P,v){"use strict";var N=class{static{i(this,"XmlNode")}static{r(this,"XmlNode")}constructor(k){this.tagname=k,this.child=[],this[":@"]={}}add(k,j){k==="__proto__"&&(k="#__proto__"),this.child.push({[k]:j})}addChild(k){k.tagname==="__proto__"&&(k.tagname="#__proto__"),k[":@"]&&Object.keys(k[":@"]).length>0?this.child.push({[k.tagname]:k.child,":@":k[":@"]}):this.child.push({[k.tagname]:k.child})}};v.exports=N}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(P,v){var N=a();function k(C,T){let U={};if(C[T+3]==="O"&&C[T+4]==="C"&&C[T+5]==="T"&&C[T+6]==="Y"&&C[T+7]==="P"&&C[T+8]==="E"){T=T+9;let de=1,J=!1,X=!1,Ce="";for(;T<C.length;T++)if(C[T]==="<"&&!X){if(J&&$(C,T))T+=7,[entityName,val,T]=j(C,T+1),val.indexOf("&")===-1&&(U[V(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(J&&E(C,T))T+=8;else if(J&&H(C,T))T+=8;else if(J&&G(C,T))T+=9;else if(q)X=!0;else throw new Error("Invalid DOCTYPE");de++,Ce=""}else if(C[T]===">"){if(X?C[T-1]==="-"&&C[T-2]==="-"&&(X=!1,de--):de--,de===0)break}else C[T]==="["?J=!0:Ce+=C[T];if(de!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:U,i:T}}i(k,"readDocType"),r(k,"readDocType");function j(C,T){let U="";for(;T<C.length&&C[T]!=="'"&&C[T]!=='"';T++)U+=C[T];if(U=U.trim(),U.indexOf(" ")!==-1)throw new Error("External entites are not supported");let de=C[T++],J="";for(;T<C.length&&C[T]!==de;T++)J+=C[T];return[U,J,T]}i(j,"readEntityExp"),r(j,"readEntityExp");function q(C,T){return C[T+1]==="!"&&C[T+2]==="-"&&C[T+3]==="-"}i(q,"isComment"),r(q,"isComment");function $(C,T){return C[T+1]==="!"&&C[T+2]==="E"&&C[T+3]==="N"&&C[T+4]==="T"&&C[T+5]==="I"&&C[T+6]==="T"&&C[T+7]==="Y"}i($,"isEntity"),r($,"isEntity");function E(C,T){return C[T+1]==="!"&&C[T+2]==="E"&&C[T+3]==="L"&&C[T+4]==="E"&&C[T+5]==="M"&&C[T+6]==="E"&&C[T+7]==="N"&&C[T+8]==="T"}i(E,"isElement"),r(E,"isElement");function H(C,T){return C[T+1]==="!"&&C[T+2]==="A"&&C[T+3]==="T"&&C[T+4]==="T"&&C[T+5]==="L"&&C[T+6]==="I"&&C[T+7]==="S"&&C[T+8]==="T"}i(H,"isAttlist"),r(H,"isAttlist");function G(C,T){return C[T+1]==="!"&&C[T+2]==="N"&&C[T+3]==="O"&&C[T+4]==="T"&&C[T+5]==="A"&&C[T+6]==="T"&&C[T+7]==="I"&&C[T+8]==="O"&&C[T+9]==="N"}i(G,"isNotation"),r(G,"isNotation");function V(C){if(N.isName(C))return C;throw new Error(`Invalid entity name ${C}`)}i(V,"validateEntityName"),r(V,"validateEntityName"),v.exports=k}}),l=o({"../../node_modules/strnum/strnum.js"(P,v){var N=/^[-+]?0x[a-fA-F0-9]+$/,k=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var j={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function q(E,H={}){if(H=Object.assign({},j,H),!E||typeof E!="string")return E;let G=E.trim();if(H.skipLike!==void 0&&H.skipLike.test(G))return E;if(H.hex&&N.test(G))return Number.parseInt(G,16);{let V=k.exec(G);if(V){let C=V[1],T=V[2],U=$(V[3]),de=V[4]||V[6];if(!H.leadingZeros&&T.length>0&&C&&G[2]!==".")return E;if(!H.leadingZeros&&T.length>0&&!C&&G[1]!==".")return E;{let J=Number(G),X=""+J;return X.search(/[eE]/)!==-1||de?H.eNotation?J:E:G.indexOf(".")!==-1?X==="0"&&U===""||X===U||C&&X==="-"+U?J:E:T?U===X||C+U===X?J:E:G===X||G===C+X?J:E}}else return E}}i(q,"toNumber"),r(q,"toNumber");function $(E){return E&&E.indexOf(".")!==-1&&(E=E.replace(/0+$/,""),E==="."?E="0":E[0]==="."?E="0"+E:E[E.length-1]==="."&&(E=E.substr(0,E.length-1))),E}i($,"trimZeros"),r($,"trimZeros"),v.exports=q}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(P,v){"use strict";var N=a(),k=u(),j=c(),q=l(),$=class{static{i(this,"OrderedObjParser")}static{r(this,"OrderedObjParser")}constructor(R){this.options=R,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:i((I,L)=>String.fromCharCode(Number.parseInt(L,10)),"val")},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:i((I,L)=>String.fromCharCode(Number.parseInt(L,16)),"val")}},this.addExternalEntities=E,this.parseXml=T,this.parseTextData=H,this.resolveNameSpace=G,this.buildAttributesMap=C,this.isItStopNode=X,this.replaceEntitiesValue=de,this.readStopNodeData=B,this.saveTextToParentTag=J,this.addChild=U}};function E(R){let I=Object.keys(R);for(let L=0;L<I.length;L++){let z=I[L];this.lastEntities[z]={regex:new RegExp("&"+z+";","g"),val:R[z]}}}i(E,"addExternalEntities"),r(E,"addExternalEntities");function H(R,I,L,z,_,D,ee){if(R!==void 0&&(this.options.trimValues&&!z&&(R=R.trim()),R.length>0)){ee||(R=this.replaceEntitiesValue(R));let F=this.options.tagValueProcessor(I,R,L,_,D);return F==null?R:typeof F!=typeof R||F!==R?F:this.options.trimValues?pe(R,this.options.parseTagValue,this.options.numberParseOptions):R.trim()===R?pe(R,this.options.parseTagValue,this.options.numberParseOptions):R}}i(H,"parseTextData"),r(H,"parseTextData");function G(R){if(this.options.removeNSPrefix){let I=R.split(":"),L=R.charAt(0)==="/"?"/":"";if(I[0]==="xmlns")return"";I.length===2&&(R=L+I[1])}return R}i(G,"resolveNameSpace"),r(G,"resolveNameSpace");var V=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function C(R,I,L){if(!this.options.ignoreAttributes&&typeof R=="string"){let z=N.getAllMatches(R,V),_=z.length,D={};for(let ee=0;ee<_;ee++){let F=this.resolveNameSpace(z[ee][1]),M=z[ee][4],ue=this.options.attributeNamePrefix+F;if(F.length)if(this.options.transformAttributeName&&(ue=this.options.transformAttributeName(ue)),ue==="__proto__"&&(ue="#__proto__"),M!==void 0){this.options.trimValues&&(M=M.trim()),M=this.replaceEntitiesValue(M);let ne=this.options.attributeValueProcessor(F,M,I);ne==null?D[ue]=M:typeof ne!=typeof M||ne!==M?D[ue]=ne:D[ue]=pe(M,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(D[ue]=!0)}if(!Object.keys(D).length)return;if(this.options.attributesGroupName){let ee={};return ee[this.options.attributesGroupName]=D,ee}return D}}i(C,"buildAttributesMap"),r(C,"buildAttributesMap");var T=r(function(R){R=R.replace(/\r\n?/g,`
73
+ `);let I=new k("!xml"),L=I,z="",_="";for(let D=0;D<R.length;D++)if(R[D]==="<")if(R[D+1]==="/"){let F=b(R,">",D,"Closing Tag is not closed."),M=R.substring(D+2,F).trim();if(this.options.removeNSPrefix){let Se=M.indexOf(":");Se!==-1&&(M=M.substr(Se+1))}this.options.transformTagName&&(M=this.options.transformTagName(M)),L&&(z=this.saveTextToParentTag(z,L,_));let ue=_.substring(_.lastIndexOf(".")+1);if(M&&this.options.unpairedTags.indexOf(M)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${M}>`);let ne=0;ue&&this.options.unpairedTags.indexOf(ue)!==-1?(ne=_.lastIndexOf(".",_.lastIndexOf(".")-1),this.tagsNodeStack.pop()):ne=_.lastIndexOf("."),_=_.substring(0,ne),L=this.tagsNodeStack.pop(),z="",D=F}else if(R[D+1]==="?"){let F=O(R,D,!1,"?>");if(!F)throw new Error("Pi Tag is not closed.");if(z=this.saveTextToParentTag(z,L,_),!(this.options.ignoreDeclaration&&F.tagName==="?xml"||this.options.ignorePiTags)){let M=new k(F.tagName);M.add(this.options.textNodeName,""),F.tagName!==F.tagExp&&F.attrExpPresent&&(M[":@"]=this.buildAttributesMap(F.tagExp,_,F.tagName)),this.addChild(L,M,_)}D=F.closeIndex+1}else if(R.substr(D+1,3)==="!--"){let F=b(R,"-->",D+4,"Comment is not closed.");if(this.options.commentPropName){let M=R.substring(D+4,F-2);z=this.saveTextToParentTag(z,L,_),L.add(this.options.commentPropName,[{[this.options.textNodeName]:M}])}D=F}else if(R.substr(D+1,2)==="!D"){let F=j(R,D);this.docTypeEntities=F.entities,D=F.i}else if(R.substr(D+1,2)==="!["){let F=b(R,"]]>",D,"CDATA is not closed.")-2,M=R.substring(D+9,F);z=this.saveTextToParentTag(z,L,_);let ue=this.parseTextData(M,L.tagname,_,!0,!1,!0,!0);ue==null&&(ue=""),this.options.cdataPropName?L.add(this.options.cdataPropName,[{[this.options.textNodeName]:M}]):L.add(this.options.textNodeName,ue),D=F+2}else{let F=O(R,D,this.options.removeNSPrefix),M=F.tagName,ue=F.rawTagName,ne=F.tagExp,Se=F.attrExpPresent,Ei=F.closeIndex;this.options.transformTagName&&(M=this.options.transformTagName(M)),L&&z&&L.tagname!=="!xml"&&(z=this.saveTextToParentTag(z,L,_,!1));let xi=L;if(xi&&this.options.unpairedTags.indexOf(xi.tagname)!==-1&&(L=this.tagsNodeStack.pop(),_=_.substring(0,_.lastIndexOf("."))),M!==I.tagname&&(_+=_?"."+M:M),this.isItStopNode(this.options.stopNodes,_,M)){let Oe="";if(ne.length>0&&ne.lastIndexOf("/")===ne.length-1)D=F.closeIndex;else if(this.options.unpairedTags.indexOf(M)!==-1)D=F.closeIndex;else{let zn=this.readStopNodeData(R,ue,Ei+1);if(!zn)throw new Error(`Unexpected end of ${ue}`);D=zn.i,Oe=zn.tagContent}let jn=new k(M);M!==ne&&Se&&(jn[":@"]=this.buildAttributesMap(ne,_,M)),Oe&&(Oe=this.parseTextData(Oe,M,_,!0,Se,!0,!0)),_=_.substr(0,_.lastIndexOf(".")),jn.add(this.options.textNodeName,Oe),this.addChild(L,jn,_)}else{if(ne.length>0&&ne.lastIndexOf("/")===ne.length-1){M[M.length-1]==="/"?(M=M.substr(0,M.length-1),_=_.substr(0,_.length-1),ne=M):ne=ne.substr(0,ne.length-1),this.options.transformTagName&&(M=this.options.transformTagName(M));let Oe=new k(M);M!==ne&&Se&&(Oe[":@"]=this.buildAttributesMap(ne,_,M)),this.addChild(L,Oe,_),_=_.substr(0,_.lastIndexOf("."))}else{let Oe=new k(M);this.tagsNodeStack.push(L),M!==ne&&Se&&(Oe[":@"]=this.buildAttributesMap(ne,_,M)),this.addChild(L,Oe,_),L=Oe}z="",D=Ei}}else z+=R[D];return I.child},"parseXml");function U(R,I,L){let z=this.options.updateTag(I.tagname,L,I[":@"]);z===!1||(typeof z=="string"&&(I.tagname=z),R.addChild(I))}i(U,"addChild"),r(U,"addChild");var de=r(function(R){if(this.options.processEntities){for(let I in this.docTypeEntities){let L=this.docTypeEntities[I];R=R.replace(L.regx,L.val)}for(let I in this.lastEntities){let L=this.lastEntities[I];R=R.replace(L.regex,L.val)}if(this.options.htmlEntities)for(let I in this.htmlEntities){let L=this.htmlEntities[I];R=R.replace(L.regex,L.val)}R=R.replace(this.ampEntity.regex,this.ampEntity.val)}return R},"replaceEntitiesValue");function J(R,I,L,z){return R&&(z===void 0&&(z=Object.keys(I.child).length===0),R=this.parseTextData(R,I.tagname,L,!1,I[":@"]?Object.keys(I[":@"]).length!==0:!1,z),R!==void 0&&R!==""&&I.add(this.options.textNodeName,R),R=""),R}i(J,"saveTextToParentTag"),r(J,"saveTextToParentTag");function X(R,I,L){let z="*."+L;for(let _ in R){let D=R[_];if(z===D||I===D)return!0}return!1}i(X,"isItStopNode"),r(X,"isItStopNode");function Ce(R,I,L=">"){let z,_="";for(let D=I;D<R.length;D++){let ee=R[D];if(z)ee===z&&(z="");else if(ee==='"'||ee==="'")z=ee;else if(ee===L[0])if(L[1]){if(R[D+1]===L[1])return{data:_,index:D}}else return{data:_,index:D};else ee===" "&&(ee=" ");_+=ee}}i(Ce,"tagExpWithClosingIndex"),r(Ce,"tagExpWithClosingIndex");function b(R,I,L,z){let _=R.indexOf(I,L);if(_===-1)throw new Error(z);return _+I.length-1}i(b,"findClosingIndex"),r(b,"findClosingIndex");function O(R,I,L,z=">"){let _=Ce(R,I+1,z);if(!_)return;let D=_.data,ee=_.index,F=D.search(/\s/),M=D,ue=!0;F!==-1&&(M=D.substring(0,F),D=D.substring(F+1).trimStart());let ne=M;if(L){let Se=M.indexOf(":");Se!==-1&&(M=M.substr(Se+1),ue=M!==_.data.substr(Se+1))}return{tagName:M,tagExp:D,closeIndex:ee,attrExpPresent:ue,rawTagName:ne}}i(O,"readTagExp"),r(O,"readTagExp");function B(R,I,L){let z=L,_=1;for(;L<R.length;L++)if(R[L]==="<")if(R[L+1]==="/"){let D=b(R,">",L,`${I} is not closed`);if(R.substring(L+2,D).trim()===I&&(_--,_===0))return{tagContent:R.substring(z,L),i:D};L=D}else if(R[L+1]==="?")L=b(R,"?>",L+1,"StopNode is not closed.");else if(R.substr(L+1,3)==="!--")L=b(R,"-->",L+3,"StopNode is not closed.");else if(R.substr(L+1,2)==="![")L=b(R,"]]>",L,"StopNode is not closed.")-2;else{let D=O(R,L,">");D&&((D&&D.tagName)===I&&D.tagExp[D.tagExp.length-1]!=="/"&&_++,L=D.closeIndex)}}i(B,"readStopNodeData"),r(B,"readStopNodeData");function pe(R,I,L){if(I&&typeof R=="string"){let z=R.trim();return z==="true"?!0:z==="false"?!1:q(R,L)}else return N.isExist(R)?R:""}i(pe,"parseValue"),r(pe,"parseValue"),v.exports=$}}),p=o({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(P){"use strict";function v($,E){return N($,E)}i(v,"prettify"),r(v,"prettify");function N($,E,H){let G,V={};for(let C=0;C<$.length;C++){let T=$[C],U=k(T),de="";if(H===void 0?de=U:de=H+"."+U,U===E.textNodeName)G===void 0?G=T[U]:G+=""+T[U];else{if(U===void 0)continue;if(T[U]){let J=N(T[U],E,de),X=q(J,E);T[":@"]?j(J,T[":@"],de,E):Object.keys(J).length===1&&J[E.textNodeName]!==void 0&&!E.alwaysCreateTextNode?J=J[E.textNodeName]:Object.keys(J).length===0&&(E.alwaysCreateTextNode?J[E.textNodeName]="":J=""),V[U]!==void 0&&V.hasOwnProperty(U)?(Array.isArray(V[U])||(V[U]=[V[U]]),V[U].push(J)):E.isArray(U,de,X)?V[U]=[J]:V[U]=J}}}return typeof G=="string"?G.length>0&&(V[E.textNodeName]=G):G!==void 0&&(V[E.textNodeName]=G),V}i(N,"compress"),r(N,"compress");function k($){let E=Object.keys($);for(let H=0;H<E.length;H++){let G=E[H];if(G!==":@")return G}}i(k,"propName"),r(k,"propName");function j($,E,H,G){if(E){let V=Object.keys(E),C=V.length;for(let T=0;T<C;T++){let U=V[T];G.isArray(U,H+"."+U,!0,!0)?$[U]=[E[U]]:$[U]=E[U]}}}i(j,"assignAttributes"),r(j,"assignAttributes");function q($,E){let{textNodeName:H}=E,G=Object.keys($).length;return!!(G===0||G===1&&($[H]||typeof $[H]=="boolean"||$[H]===0))}i(q,"isLeafTag"),r(q,"isLeafTag"),P.prettify=v}}),m=o({"node_modules/fast-xml-parser/src/validator.js"(P){"use strict";var v=a(),N={allowBooleanAttributes:!1,unpairedTags:[]};P.validate=function(b,O){O=Object.assign({},N,O);let B=[],pe=!1,R=!1;b[0]==="\uFEFF"&&(b=b.substr(1));for(let I=0;I<b.length;I++)if(b[I]==="<"&&b[I+1]==="?"){if(I+=2,I=j(b,I),I.err)return I}else if(b[I]==="<"){let L=I;if(I++,b[I]==="!"){I=q(b,I);continue}else{let z=!1;b[I]==="/"&&(z=!0,I++);let _="";for(;I<b.length&&b[I]!==">"&&b[I]!==" "&&b[I]!==" "&&b[I]!==`
74
+ `&&b[I]!=="\r";I++)_+=b[I];if(_=_.trim(),_[_.length-1]==="/"&&(_=_.substring(0,_.length-1),I--),!J(_)){let F;return _.trim().length===0?F="Invalid space after '<'.":F="Tag '"+_+"' is an invalid name.",U("InvalidTag",F,X(b,I))}let D=H(b,I);if(D===!1)return U("InvalidAttr","Attributes for '"+_+"' have open quote.",X(b,I));let ee=D.value;if(I=D.index,ee[ee.length-1]==="/"){let F=I-ee.length;ee=ee.substring(0,ee.length-1);let M=V(ee,O);if(M===!0)pe=!0;else return U(M.err.code,M.err.msg,X(b,F+M.err.line))}else if(z)if(D.tagClosed){if(ee.trim().length>0)return U("InvalidTag","Closing tag '"+_+"' can't have attributes or invalid starting.",X(b,L));{let F=B.pop();if(_!==F.tagName){let M=X(b,F.tagStartPos);return U("InvalidTag","Expected closing tag '"+F.tagName+"' (opened in line "+M.line+", col "+M.col+") instead of closing tag '"+_+"'.",X(b,L))}B.length==0&&(R=!0)}}else return U("InvalidTag","Closing tag '"+_+"' doesn't have proper closing.",X(b,I));else{let F=V(ee,O);if(F!==!0)return U(F.err.code,F.err.msg,X(b,I-ee.length+F.err.line));if(R===!0)return U("InvalidXml","Multiple possible root nodes found.",X(b,I));O.unpairedTags.indexOf(_)!==-1||B.push({tagName:_,tagStartPos:L}),pe=!0}for(I++;I<b.length;I++)if(b[I]==="<")if(b[I+1]==="!"){I++,I=q(b,I);continue}else if(b[I+1]==="?"){if(I=j(b,++I),I.err)return I}else break;else if(b[I]==="&"){let F=T(b,I);if(F==-1)return U("InvalidChar","char '&' is not expected.",X(b,I));I=F}else if(R===!0&&!k(b[I]))return U("InvalidXml","Extra text at the end",X(b,I));b[I]==="<"&&I--}}else{if(k(b[I]))continue;return U("InvalidChar","char '"+b[I]+"' is not expected.",X(b,I))}if(pe){if(B.length==1)return U("InvalidTag","Unclosed tag '"+B[0].tagName+"'.",X(b,B[0].tagStartPos));if(B.length>0)return U("InvalidXml","Invalid '"+JSON.stringify(B.map(I=>I.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return U("InvalidXml","Start tag expected.",1);return!0};function k(b){return b===" "||b===" "||b===`
75
+ `||b==="\r"}i(k,"isWhiteSpace"),r(k,"isWhiteSpace");function j(b,O){let B=O;for(;O<b.length;O++)if(b[O]=="?"||b[O]==" "){let pe=b.substr(B,O-B);if(O>5&&pe==="xml")return U("InvalidXml","XML declaration allowed only at the start of the document.",X(b,O));if(b[O]=="?"&&b[O+1]==">"){O++;break}else continue}return O}i(j,"readPI"),r(j,"readPI");function q(b,O){if(b.length>O+5&&b[O+1]==="-"&&b[O+2]==="-"){for(O+=3;O<b.length;O++)if(b[O]==="-"&&b[O+1]==="-"&&b[O+2]===">"){O+=2;break}}else if(b.length>O+8&&b[O+1]==="D"&&b[O+2]==="O"&&b[O+3]==="C"&&b[O+4]==="T"&&b[O+5]==="Y"&&b[O+6]==="P"&&b[O+7]==="E"){let B=1;for(O+=8;O<b.length;O++)if(b[O]==="<")B++;else if(b[O]===">"&&(B--,B===0))break}else if(b.length>O+9&&b[O+1]==="["&&b[O+2]==="C"&&b[O+3]==="D"&&b[O+4]==="A"&&b[O+5]==="T"&&b[O+6]==="A"&&b[O+7]==="["){for(O+=8;O<b.length;O++)if(b[O]==="]"&&b[O+1]==="]"&&b[O+2]===">"){O+=2;break}}return O}i(q,"readCommentAndCDATA"),r(q,"readCommentAndCDATA");var $='"',E="'";function H(b,O){let B="",pe="",R=!1;for(;O<b.length;O++){if(b[O]===$||b[O]===E)pe===""?pe=b[O]:pe!==b[O]||(pe="");else if(b[O]===">"&&pe===""){R=!0;break}B+=b[O]}return pe!==""?!1:{value:B,index:O,tagClosed:R}}i(H,"readAttributeStr"),r(H,"readAttributeStr");var G=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function V(b,O){let B=v.getAllMatches(b,G),pe={};for(let R=0;R<B.length;R++){if(B[R][1].length===0)return U("InvalidAttr","Attribute '"+B[R][2]+"' has no space in starting.",Ce(B[R]));if(B[R][3]!==void 0&&B[R][4]===void 0)return U("InvalidAttr","Attribute '"+B[R][2]+"' is without value.",Ce(B[R]));if(B[R][3]===void 0&&!O.allowBooleanAttributes)return U("InvalidAttr","boolean attribute '"+B[R][2]+"' is not allowed.",Ce(B[R]));let I=B[R][2];if(!de(I))return U("InvalidAttr","Attribute '"+I+"' is an invalid name.",Ce(B[R]));if(!pe.hasOwnProperty(I))pe[I]=1;else return U("InvalidAttr","Attribute '"+I+"' is repeated.",Ce(B[R]))}return!0}i(V,"validateAttributeString"),r(V,"validateAttributeString");function C(b,O){let B=/\d/;for(b[O]==="x"&&(O++,B=/[\da-fA-F]/);O<b.length;O++){if(b[O]===";")return O;if(!b[O].match(B))break}return-1}i(C,"validateNumberAmpersand"),r(C,"validateNumberAmpersand");function T(b,O){if(O++,b[O]===";")return-1;if(b[O]==="#")return O++,C(b,O);let B=0;for(;O<b.length;O++,B++)if(!(b[O].match(/\w/)&&B<20)){if(b[O]===";")break;return-1}return O}i(T,"validateAmpersand"),r(T,"validateAmpersand");function U(b,O,B){return{err:{code:b,msg:O,line:B.line||B,col:B.col}}}i(U,"getErrorObject"),r(U,"getErrorObject");function de(b){return v.isName(b)}i(de,"validateAttrName"),r(de,"validateAttrName");function J(b){return v.isName(b)}i(J,"validateTagName"),r(J,"validateTagName");function X(b,O){let B=b.substring(0,O).split(/\r?\n/);return{line:B.length,col:B[B.length-1].length+1}}i(X,"getLineNumberForPosition"),r(X,"getLineNumberForPosition");function Ce(b){return b.startIndex+b[1].length}i(Ce,"getPositionFromMatch"),r(Ce,"getPositionFromMatch")}}),y=o({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(P,v){var{buildOptions:N}=s(),k=d(),{prettify:j}=p(),q=m(),$=class{static{i(this,"XMLParser")}static{r(this,"XMLParser")}constructor(E){this.externalEntities={},this.options=N(E)}parse(E,H){if(typeof E!="string")if(E.toString)E=E.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(H){H===!0&&(H={});let C=q.validate(E,H);if(C!==!0)throw Error(`${C.err.msg}:${C.err.line}:${C.err.col}`)}let G=new k(this.options);G.addExternalEntities(this.externalEntities);let V=G.parseXml(E);return this.options.preserveOrder||V===void 0?V:j(V,this.options)}addEntity(E,H){if(H.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(E.indexOf("&")!==-1||E.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(H==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[E]=H}};v.exports=$}});let A=y();return new A(n)},"getXmlParser");var hi=class extends Ge{static{i(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),f("policy.outbound.xml-to-json"),K(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=e.parseOnStatusCodes?Be(e.parseOnStatusCodes):void 0,this.parser=Ka({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,t,r){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let o;try{let u=await e.text();o=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw r.log.error(c,u),new S(c)}let s=new Headers(e.headers);return s.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:s})}};var yi=class{static{i(this,"ServiceProviderImpl")}services=new Map;addService(e,t){if(this.services.get(e))throw new W(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,t)}getService(e){return this.services.get(e)}};var bi=class{static{i(this,"BackgroundDispatcher")}#e;constructor(e,t){if(!t||t.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new Y(t.name??"",t.msDelay,e)}enqueue=i(e=>{this.#e.enqueue(e),Cn().waitUntil(this.#e.waitUntilFlushed())},"enqueue")};var Ja=10,Qa=3e4,wi=class{static{i(this,"BackgroundLoader")}#e=new Map;#t;#n;#r;#o;#i={};constructor(e,t){if(typeof t=="number"){let r=t;this.#n=r*1e3,this.#o=Qa,this.#r=Ja}else{let r=t;this.#n=r.ttlSeconds*1e3,this.#o=r.loaderTimeoutSeconds?r.loaderTimeoutSeconds*1e3:Qa,this.#r=Ja}this.#t=e}#s(e){return e.expiry<=new Date}#a(e){let t=this.#i[e];return!(t===void 0||t===0)}#u(e){let t=this.#e.get(e);if(t&&!this.#s(t))return t.data}async get(e){let t=this.#u(e);if(t)return this.#l(e),t;if(this.#a(e))try{await kd(()=>this.#u(e)!==void 0||!this.#a,this.#o+this.#r+1,this.#r);let r=this.#u(e);if(r)return r}catch{}return this.#c(e)}#l(e){if(!this.#a(e)){let t=this.#c(e);Cn().waitUntil(t)}}async#c(e){try{this.#i[e]===void 0&&(this.#i[e]=0),this.#i[e]++;let t=await Promise.race([this.#t(e),scheduler.wait(this.#o)]);if(t===void 0)throw new Error(`BackgroundLoader: Loader timed out after ${this.#o} ms.`);return this.#e.set(e,{data:t,expiry:new Date(Date.now()+this.#n)}),t}finally{this.#i[e]--}}};async function kd(n,e,t){let r=Date.now();for(;!n();){let o=Date.now()-r;if(o>e)throw new Error(`BackgroundLoader: Timeout waiting for an on-going loader after ${o} ms.`);await scheduler.wait(t)}}i(kd,"waitUntilTrue");var Ri=["sha-1","sha-256","sha-384","sha-512"],$n=class{static{i(this,"BaseCryptoBeta")}};var Pi=class extends $n{static{i(this,"WorkerCryptoBeta")}async digest(e,t){if(!Ri.includes(e.toLowerCase()))throw new S(`Algorithm ${e} is not supported. Try using ${Ri.join(", ")}`);let r=new TextEncoder().encode(t),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var Fn=class{constructor(e){this.context=e}static{i(this,"BaseKeyValueStore")}};var Ii=class extends Fn{static{i(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let t=h.instance.runtime.ZUPLO_KV;if(!t)throw new nn("The Key Value Store feature is not enabled for this project.");this.#e=t,f("platform.kv-store")}put(e,t,r){if(typeof e!="string")throw new g("value must be of type string");return this.#e.put(e,t,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,t){return this.#e.get(e,{type:"text",cacheTtl:t?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};export{Ro as AWSLoggingPlugin,nl as AmberfloMeteringInboundPolicy,Uo as AmberfloMeteringPolicy,il as ApiAuthKeyInboundPolicy,Zo as ApiKeyInboundPolicy,Ao as AuditLogDataStaxProvider,ko as AuditLogPlugin,ll as Auth0JwtInboundPolicy,Ic as AwsLambdaHandlerExtensions,zo as AxiomaticsAuthZInboundPolicy,bi as BackgroundDispatcher,wi as BackgroundLoader,dl as BasicAuthInboundPolicy,qa as BasicRateLimitInboundPolicy,Y as BatchDispatch,Vo as BrownoutInboundPolicy,Il as CachingInboundPolicy,El as ChangeMethodInboundPolicy,xl as ClearHeadersInboundPolicy,Tl as ClearHeadersOutboundPolicy,vl as ClerkJwtInboundPolicy,Cl as CognitoJwtInboundPolicy,Xo as ComplexRateLimitInboundPolicy,Dl as CompositeInboundPolicy,Ml as CompositeOutboundPolicy,g as ConfigurationError,xr as ContentTypes,oe as ContextData,Pi as CryptoBeta,ql as CurityPhantomTokenInboundPolicy,Qr as DataDogLoggingPlugin,Eo as DataDogMetricsPlugin,lo as DynaTraceLoggingPlugin,Co as DynatraceMetricsPlugin,Ul as FirebaseJwtInboundPolicy,Zl as FormDataToJsonInboundPolicy,$l as GeoFilterInboundPolicy,Gr as GoogleCloudLoggingPlugin,no as Handler,x as HttpProblems,ln as HttpStatusCode,ae as InboundPolicy,Fl as JWTScopeValidationInboundPolicy,Ii as KeyValueStore,mo as LokiLoggingPlugin,Vt as LookupResult,re as MemoryZoneReadThroughCache,jl as MockApiInboundPolicy,Jl as MoesifInboundPolicy,ri as MonetizationInboundPolicy,oi as OktaFGAAuthZInboundPolicy,Yl as OktaJwtInboundPolicy,ii as OpenFGAAuthZInboundPolicy,Re as OpenIdJwtInboundPolicy,Ge as OutboundPolicy,tt as ProblemResponseFormatter,ed as PropelAuthJwtInboundPolicy,ui as QuotaInboundPolicy,qa as RateLimitInboundPolicy,sd as ReadmeMetricsInboundPolicy,ad as RemoveHeadersInboundPolicy,ud as RemoveHeadersOutboundPolicy,cd as RemoveQueryParamsInboundPolicy,ld as ReplaceStringOutboundPolicy,dd as RequestSizeLimitInboundPolicy,Ba as RequestValidationInboundPolicy,md as RequireOriginInboundPolicy,Dt as ResponseSendingEvent,Mt as ResponseSentEvent,Wt as Router,S as RuntimeError,on as SYSTEM_LOGGER,pd as SchemaBasedRequestValidation,_e as SemanticAttributes,yi as ServiceProviderImpl,gd as SetBodyInboundPolicy,fd as SetHeadersInboundPolicy,hd as SetHeadersOutboundPolicy,yd as SetQueryParamsInboundPolicy,bd as SetStatusOutboundPolicy,Rd as SleepInboundPolicy,la as StripeMonetizationPlugin,Jt as StripeWebhookVerificationInboundPolicy,ho as SumoLogicLoggingPlugin,Pd as SupabaseJwtInboundPolicy,Ze as SystemRouteName,Lt as TelemetryPlugin,Id as UpstreamAzureAdServiceAuthInboundPolicy,xd as UpstreamFirebaseAdminAuthInboundPolicy,Cd as UpstreamFirebaseUserAuthInboundPolicy,mi as UpstreamGcpFederatedAuthInboundPolicy,Od as UpstreamGcpJwtInboundPolicy,Sd as UpstreamGcpServiceAuthInboundPolicy,bo as VMWareLogInsightLoggingPlugin,Ad as ValidateJsonSchemaInbound,hi as XmlToJsonOutboundPolicy,St as ZoneCache,te as ZuploRequest,Xt as ZuploServices,Ec as awsLambdaHandler,Pe as environment,Bn as getIdForParameterSchema,Xa as getIdForRefSchema,Gn as getIdForRequestBodySchema,Ya as getRawOperationDataIdentifierName,vr as httpStatuses,kc as openApiSpecHandler,_c as redirectHandler,eu as sanitizedIdentifierName,Tr as serialize,Vl as setMoesifContext,f as trackFeature,Dc as urlForwardHandler,qc as urlRewriteHandler,Hc as webSocketHandler,Uc as webSocketPipelineHandler};
76
76
  /*! For license information please see index.js.LEGAL.txt */