@zuplo/runtime 6.54.12 → 6.54.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/out/esm/{chunk-IALZJEX3.js → chunk-DJ47NX57.js} +5 -5
- package/out/esm/{chunk-VNF2YIXK.js → chunk-SEPHSKCD.js} +1 -1
- package/out/esm/index.js +1 -1
- package/out/esm/internal/index.js +1 -1
- package/out/esm/mocks/index.js +1 -1
- package/package.json +1 -1
- /package/out/esm/{chunk-IALZJEX3.js.LEGAL.txt → chunk-DJ47NX57.js.LEGAL.txt} +0 -0
|
@@ -22,15 +22,15 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
var fe=Object.create;var w=Object.defineProperty;var
|
|
26
|
-
`).map(l=>l.trim()).join(" ");case"%O":return e(n[s++]);case"%j":try{return JSON.stringify(n[s++])}catch{return"[Circular]"}default:return o}});for(let o of n.splice(s))o===null||!(typeof o=="object"&&o!==null)?u+=" "+o:u+=" "+e(o);return u}r(K,"format");function R(e,t,n,s){let i={seen:[],stylize:
|
|
25
|
+
var fe=Object.create;var w=Object.defineProperty;var ge=Object.getOwnPropertyDescriptor;var de=Object.getOwnPropertyNames;var _e=Object.getPrototypeOf,Ee=Object.prototype.hasOwnProperty;var r=(e,t)=>w(e,"name",{value:t,configurable:!0});var ot=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),it=(e,t)=>{for(var n in t)w(e,n,{get:t[n],enumerable:!0})},he=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of de(t))!Ee.call(e,i)&&i!==n&&w(e,i,{get:()=>t[i],enumerable:!(s=ge(t,i))||s.enumerable});return e};var st=(e,t,n)=>(n=e!=null?fe(_e(e)):{},he(t||!e||!e.__esModule?w(n,"default",{value:e,enumerable:!0}):n,e));var j=class extends Error{static{r(this,"SystemError")}constructor(t,n){super(t,n),this.name="InternalError"}},y=class extends Error{static{r(this,"RuntimeError")}extensionMembers;constructor(t,n){typeof t=="string"?super(t,n):(super(t.message,n),this.extensionMembers=t.extensionMembers),this.name="RuntimeError"}},W=class extends y{static{r(this,"ConfigurationError")}constructor(t,n){super(t,n),this.name="ConfigurationError"}};var at="zuplo-request-id",me="zp-rid",Oe="zp-body-removed",ye="cf-ray",pt="x-forwarded-scheme",ft="x-forwarded-proto",gt="x-scheme",Re="cf-ipcity",be="cf-ipcontinent",Ae="cf-ipcountry",xe="cf-iplongitude",Le="cf-iplatitude",dt="cf-region",_t="cf-region-code",Et="cf-metro-code",ht="cf-postal-code",mt="cf-timezone",Ot="zp-ipcity",yt="zp-ipcontinent",Rt="zp-ipcountry",bt="zp-iplongitude",At="zp-iplatitude",Te="zp-asn",Pe="zp-asorg",Ie="zp-colo",Ce="zp-postalcode",we="zp-metrocode",Se="zp-region",Ue="zp-regioncode",Ne="zp-timezone",xt="zp-http-protocol",N="zp-local-service",De="x-akamai-edgescape",Lt=[De,N],Tt=[Re,be,Ae,xe,Le,Te,Pe,Ie,Ce,we,Se,Ue,Ne],Pt=["zp-","cf-"],It=[me,ye,Oe];var Ct=Symbol("zuplo_meters"),wt=Symbol("zuplo_dynamic_meters"),St="system-logger";var ze=!1;function L(e,t){return{open:`\x1B[${e.join(";")}m`,close:`\x1B[${t}m`,regexp:new RegExp(`\\x1b\\[${t}m`,"g")}}r(L,"code");function T(e,t){return ze?`${t.open}${e.replace(t.regexp,t.open)}${t.close}`:e}r(T,"run");function He(e){return T(e,L([31],39))}r(He,"red");function Me(e){return T(e,L([32],39))}r(Me,"green");function ve(e){return T(e,L([33],39))}r(ve,"yellow");function Ze(e){return T(e,L([34],39))}r(Ze,"blue");function Fe(e){return T(e,L([35],39))}r(Fe,"magenta");function Ge(e){return T(e,L([36],39))}r(Ge,"cyan");var Nt=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 q=[He,Me,ve,Ze,Fe,Ge];function $e(e){let t=0,n=e.length,s=0;if(n>0)for(;s<n;)t=(t<<5)-t+e.charCodeAt(s++)|0;return t}r($e,"hashCode");function J(e){let t=Math.abs($e(e));return q[t%q.length]}r(J,"generateColor");function K(e,t,...n){let s=0,i=n.length,u=String(t).replace(/%[sdjoO%]/g,o=>{if(o==="%%")return"%";if(s>=i)return o;switch(o){case"%s":return String(n[s++]);case"%d":return Number(n[s++]).toString();case"%o":return e(n[s++]).split(`
|
|
26
|
+
`).map(l=>l.trim()).join(" ");case"%O":return e(n[s++]);case"%j":try{return JSON.stringify(n[s++])}catch{return"[Circular]"}default:return o}});for(let o of n.splice(s))o===null||!(typeof o=="object"&&o!==null)?u+=" "+o:u+=" "+e(o);return u}r(K,"format");function R(e,t,n,s){let i={seen:[],stylize:ke,showHidden:t??!1,depth:n??2,colors:s??!1,customInspect:!0};return i.colors&&(i.stylize=Be),S(i,e,i.depth)}r(R,"inspect");R.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]};R.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function ke(e,t){return e}r(ke,"stylizeNoColor");function Ve(e){return typeof e=="boolean"}r(Ve,"isBoolean");function Q(e){return e===void 0}r(Q,"isUndefined");function Be(e,t){let n=R.styles[t];return n?"\x1B["+R.colors[n][0]+"m"+e+"\x1B["+R.colors[n][1]+"m":e}r(Be,"stylizeWithColor");function D(e){return typeof e=="function"}r(D,"isFunction");function ee(e){return typeof e=="string"}r(ee,"isString");function Ye(e){return typeof e=="number"}r(Ye,"isNumber");function te(e){return e===null}r(te,"isNull");function ne(e,t){return Object.prototype.hasOwnProperty.call(e,t)}r(ne,"hasOwn");function z(e){return Z(e)&&F(e)==="[object RegExp]"}r(z,"isRegExp");function Z(e){return typeof e=="object"&&e!==null}r(Z,"isObject");function H(e){return Z(e)&&(F(e)==="[object Error]"||e instanceof Error)}r(H,"isError");function X(e){return Z(e)&&F(e)==="[object Date]"}r(X,"isDate");function F(e){return Object.prototype.toString.call(e)}r(F,"objectToString");function je(e){let t={};return e.forEach(function(n,s){t[n]=!0}),t}r(je,"arrayToHash");function We(e,t,n,s,i){let u=[];for(let o=0,l=t.length;o<l;++o)ne(t,String(o))?u.push(v(e,t,n,s,String(o),!0)):u.push("");return i.forEach(function(o){o.match(/^\d+$/)||u.push(v(e,t,n,s,o,!0))}),u}r(We,"formatArray");function M(e){return"["+Error.prototype.toString.call(e)+"]"}r(M,"formatError");function S(e,t,n){if(e.customInspect&&t&&D(t.inspect)&&t.inspect!==R&&!(t.constructor&&t.constructor.prototype===t)){let a=t.inspect(n,e);return ee(a)||(a=S(e,a,n)),a}let s=qe(e,t);if(s)return s;let i=Object.keys(t),u=je(i);try{e.showHidden&&Object.getOwnPropertyNames&&(i=Object.getOwnPropertyNames(t))}catch{}if(H(t)&&(i.indexOf("message")>=0||i.indexOf("description")>=0))return M(t);if(i.length===0){if(D(t)){let a=t.name?": "+t.name:"";return e.stylize("[Function"+a+"]","special")}if(z(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(X(t))return e.stylize(Date.prototype.toString.call(t),"date");if(H(t))return M(t)}let o="",l=!1,p=["{","}"];if(Array.isArray(t)&&(l=!0,p=["[","]"]),D(t)&&(o=" [Function"+(t.name?": "+t.name:"")+"]"),z(t)&&(o=" "+RegExp.prototype.toString.call(t)),X(t)&&(o=" "+Date.prototype.toUTCString.call(t)),H(t)&&(o=" "+M(t)),i.length===0&&(!l||t.length==0))return p[0]+o+p[1];if(n<0)return z(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special");e.seen.push(t);let c;return l?c=We(e,t,n,u,i):c=i.map(function(a){return v(e,t,n,u,a,l)}),e.seen.pop(),Je(c,o,p)}r(S,"formatValue");function v(e,t,n,s,i,u){let o,l,p;p={value:void 0};try{p.value=t[i]}catch{}try{Object.getOwnPropertyDescriptor&&(p=Object.getOwnPropertyDescriptor(t,i)||p)}catch{}if(p.get?p.set?l=e.stylize("[Getter/Setter]","special"):l=e.stylize("[Getter]","special"):p.set&&(l=e.stylize("[Setter]","special")),ne(s,i)||(o="["+i+"]"),l||(e.seen.indexOf(p.value)<0?(te(n)?l=S(e,p.value,null):l=S(e,p.value,n-1),l.indexOf(`
|
|
27
27
|
`)>-1&&(u?l=l.split(`
|
|
28
28
|
`).map(function(c){return" "+c}).join(`
|
|
29
29
|
`).substr(2):l=`
|
|
30
30
|
`+l.split(`
|
|
31
31
|
`).map(function(c){return" "+c}).join(`
|
|
32
|
-
`))):l=e.stylize("[Circular]","special")),Q(o)){if(u&&i.match(/^\d+$/))return l;o=JSON.stringify(""+i),o.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),o=e.stylize(o,"name")):(o=o.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),o=e.stylize(o,"string"))}return o+": "+l}r(v,"formatProperty");function qe(e,t){if(Q(t))return e.stylize("undefined","undefined");if(ee(t)){let n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}if(Ye(t))return e.stylize(""+t,"number");if(
|
|
32
|
+
`))):l=e.stylize("[Circular]","special")),Q(o)){if(u&&i.match(/^\d+$/))return l;o=JSON.stringify(""+i),o.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),o=e.stylize(o,"name")):(o=o.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),o=e.stylize(o,"string"))}return o+": "+l}r(v,"formatProperty");function qe(e,t){if(Q(t))return e.stylize("undefined","undefined");if(ee(t)){let n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}if(Ye(t))return e.stylize(""+t,"number");if(Ve(t))return e.stylize(""+t,"boolean");if(te(t))return e.stylize("null","null")}r(qe,"formatPrimitive");function Je(e,t,n){let s=0;return e.reduce(function(u,o){return s++,o.indexOf(`
|
|
33
33
|
`)>=0&&s++,u+o.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?n[0]+(t===""?"":t+`
|
|
34
34
|
`)+" "+e.join(`,
|
|
35
|
-
`)+" "+n[1]:n[0]+t+" "+e.join(", ")+" "+n[1]}r(Je,"reduceToSingleString");var re=r((e,...t)=>K(R,e,t),"format");var G=class{static{r(this,"Debugger")}manager;ns;color;last;enabled;constructor(t,n){this.manager=t,this.ns=n,this.color=J(n),this.last=0,this.enabled=t.enabled.some(s=>s.test(n))}log(...t){if(!this.enabled)return;let n,s=t[0];typeof s=="function"?n=s():n=String(s);let i=Date.now()-(this.last||Date.now());n=re(n,...t);let u=`${this.color(this.ns)} ${n} ${this.color(`+${i}ms`)}`;console.log(u),this.last=Date.now()}},$=class{static{r(this,"DebugManager")}debuggers;enabled;constructor(t){this.debuggers=new Map,this.enabled=t??[]}};function Ke(e){return!e||e.length===0?[]:(e=e.replace(/\s/g,"").replace(/\*/g,".+"),e.split(",").map(t=>new RegExp(`^${t}$`)))}r(Ke,"extract");var N;function oe(e){let t=globalThis.DEBUG;N||(N=new $(Ke(t)));let n=new G(N,e);return N.debuggers.set(e,n),Object.assign(n.log.bind(n),{self:n})}r(oe,"debug");function Xe(e){if(e.length>=255)throw new TypeError("Alphabet too long");let t=new Uint8Array(256);for(let c=0;c<t.length;c++)t[c]=255;for(let c=0;c<e.length;c++){let a=e.charAt(c),d=a.charCodeAt(0);if(t[d]!==255)throw new TypeError(a+" is ambiguous");t[d]=c}let n=e.length,s=e.charAt(0),i=Math.log(n)/Math.log(256),u=Math.log(256)/Math.log(n);function o(c){if(c instanceof Uint8Array||(ArrayBuffer.isView(c)?c=new Uint8Array(c.buffer,c.byteOffset,c.byteLength):Array.isArray(c)&&(c=Uint8Array.from(c))),!(c instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(c.length===0)return"";let a=0,d=0,g=0,_=c.length;for(;g!==_&&c[g]===0;)g++,a++;let m=(_-g)*u+1>>>0,E=new Uint8Array(m);for(;g!==_;){let f=c[g],A=0;for(let O=m-1;(f!==0||A<d)&&O!==-1;O--,A++)f+=256*E[O]>>>0,E[O]=f%n>>>0,f=f/n>>>0;if(f!==0)throw new Error("Non-zero carry");d=A,g++}let h=m-d;for(;h!==m&&E[h]===0;)h++;let C=s.repeat(a);for(;h<m;++h)C+=e.charAt(E[h]);return C}r(o,"encode");function l(c){if(typeof c!="string")throw new TypeError("Expected String");if(c.length===0)return new Uint8Array;let a=0,d=0,g=0;for(;c[a]===s;)d++,a++;let _=(c.length-a)*i+1>>>0,m=new Uint8Array(_);for(;c[a];){let f=t[c.charCodeAt(a)];if(f===255)return;let A=0;for(let O=_-1;(f!==0||A<g)&&O!==-1;O--,A++)f+=n*m[O]>>>0,m[O]=f%256>>>0,f=f/256>>>0;if(f!==0)throw new Error("Non-zero carry");g=A,a++}let E=_-g;for(;E!==_&&m[E]===0;)E++;let h=new Uint8Array(d+(_-E)),C=d;for(;E!==_;)h[C++]=m[E++];return h}r(l,"decodeUnsafe");function p(c){let a=l(c);if(a)return a;throw new Error("Non-base"+n+" character")}return r(p,"decode"),{encode:o,decodeUnsafe:l,decode:p}}r(Xe,"base");var ie=Xe;var Qe="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",se=ie(Qe);var x=oe("zuplo:runtime:external-service");function et(){let e,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:t}=b.instance.runtime;if(t&&t!=="undefined")try{let n=atob(t);e=JSON.parse(n)}catch{}return e}r(et,"getServiceAuth");async function ce(e,t){let n=et();if(n)if(x(`Using external service auth. ClientId: ${n.clientId})`),typeof e=="string"){let s=new URL(e),i=s.hostname,u=t??{},o=new Headers(u.headers||{});o.set("CF-Access-Client-Id",n.clientId),o.set("CF-Access-Client-Secret",n.clientSecret),u.headers=o;let l;if(n.customServiceMapping&&n.customServiceMapping[i])l=`https://${n.customServiceMapping[i]}`;else if(b.instance.useLegacyServiceRouting)l=`https://${i}.zuptunnel.com`;else{x("Using sha256 service routing");let a=b.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE){let d=await tt(i,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE),g=ue(a.ENVIRONMENT_TYPE),_=await V(`${a.ACCOUNT_NAME}-${a.PROJECT_NAME}-${g}`);_==="40d7ad502f5d743997999594c177184a00161a77865423511f3a1ea21eb5a5e"||_==="d05bffe8fa91a300187d2cf43e8aa4a56bd809c442ae10d1ee49af7d29a5a11"?l=`https://${d}.zuptunnel.com`:l=`https://${d}.t.zuplo.app`}else throw x("Cannot use sha256 service routing, missing build variables"),new y("Failed to generate fully qualified tunnel url.")}let p=new URL(`${l}${s.pathname}${s.search}`);x(`Calling external service: ${p.toString()}`);let c=await P(p.toString(),u);if(c.status===403&&c.headers.get("cf-access-domain")!==null)throw I.console.error("403 Forbidden when calling external service.",{clientId:n.clientId,tunnelHost:l}),new y("Could not connect to secure tunnel.");return c}else throw x("Cannot call external service with Request object"),new y("Currently, we only support fetch(<some_string>, ...).");else throw x("There is no external service auth configured for this zup."),new y("There are no external services configured for this zup.")}r(ce,"externalServiceHandler");async function le(e,t){if(typeof e=="string"){let n=new URL(e),s=n.hostname,i=t??{},u=`http://${s}.zuplo.svc.cluster.local:9000`,o=new URL(`${u}${n.pathname}${n.search}`),l=new Headers(i.headers||{});return l.set(U,s),i.headers=l,await P(o.toString(),i)}else throw new y("Currently, we only support fetch(<some_string>, ...).")}r(le,"clusterServiceHandler");async function tt(e,t,n,s){let i=e.toLowerCase(),u=t.toLowerCase(),o=n.toLowerCase(),l=ue(s);x(`Hashing service name: ${u}-${i}.${u}-${o}-${l}`);let p=await V(`${u}-${i}`),c=await V(`${u}-${o}-${l}`);return`${p}.${c}`}r(tt,"hashServiceName");async function V(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(u=>u.toString(16).padStart(2,"0")).join("").slice(0,-1)}r(V,"hashSegment");function ue(e){let t=e.toLowerCase();switch(t){case"production":case"preview":return t;default:return"working-copy"}}r(ue,"sanitizeEnvironmentType");var k=new Map;k.set("service:",ce);k.set("local:",le);var P=globalThis.fetch;function B(e,t){let n=nt(t);if(typeof e=="string"){let s=new URL(e),i=k.get(s.protocol);return i?i(e,n):P(e,n)}else return P(e,n)}r(B,"internalFetch");globalThis.fetch=B;var nt=r(e=>{if(!e||e instanceof Request)return e;let t=e;if(!t.zuplo)return e;let n=e;return n.cf={cacheEverything:t.zuplo?.cacheEverything,cacheTtl:t.zuplo?.cacheTtlSeconds},delete e.zuplo,e},"transformInit");var rt={console:{log:console.log.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console),debug:console.debug.bind(console),assert:console.assert.bind(console),clear:console.clear.bind(console),count:console.count.bind(console),countReset:console.countReset.bind(console),dir:console.dir.bind(console),dirxml:console.dirxml.bind(console),group:console.group.bind(console),groupCollapsed:console.groupCollapsed.bind(console),groupEnd:console.groupEnd.bind(console),table:console.table.bind(console),time:console.time.bind(console),timeEnd:console.timeEnd.bind(console),timeLog:console.timeLog.bind(console),timeStamp:console.timeStamp.bind(console),trace:console.trace.bind(console),profile:console.profile.bind(console),profileEnd:console.profileEnd.bind(console)},fetch:B},I=rt;var Y="2025-02-06",ae=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1,allowCustomPorts:!1,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1,allowCustomPorts:!1,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!1,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!1,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2024-09-02":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!0,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2025-02-06":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!0,removeLegacyLogInitialization:!0,useForwardRedirectsPropOnUrlForwardHandler:!0}});function pe(){return new b({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:Y,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,IS_LOCAL_DEVELOPMENT:!1,COMPATIBILITY_FLAGS:ae[Y]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}r(pe,"getMockEnvironment");var b=class e{static{r(this,"Environment")}config;static#e;static#t=!1;static initialize(t){this.#e||(this.#e=new e(t),this.#t=!0)}static get instance(){return this.#t||(I.console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=pe()),this.#e}constructor({build:t,runtime:n}){let s;try{if(n.ZUPLO_SYSTEM_CONFIGURATIONS){let i=new TextDecoder().decode(se.decode(n.ZUPLO_SYSTEM_CONFIGURATIONS)),u=JSON.parse(i);for(let o of Object.keys(u))n[o]||(n[o]=u[o])}if(n.__ZUPLO_CONFIG){let i=atob(n.__ZUPLO_CONFIG);s=JSON.parse(i)}}catch(i){I.console.error("Failed to parse runtime configuration",i)}this.config=s??{},this.build=t,this.runtime=n,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get zuploEdgeApiUrl(){return this.config.zuplo_edge_api_url??"https://api.zuploedge.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get zuploClientAuthBucketId(){return this.config.zuplo_auth_client_bucket_id??"auth_o8PUdhKxSTOiB794GWPwLQCD"}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get developerApiUrl(){return this.config.developer_api_url??"https://dev.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuploedge.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuploedge.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuploedge.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuploedge.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get authClientId(){return this.runtime.__ZUPLO_AUTH_CLIENT_ID}get authClientSecret(){return this.runtime.__ZUPLO_AUTH_CLIENT_SECRET}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.IS_LOCAL_DEVELOPMENT}get isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};export{r as a,ot as b,it as c,st as d,oe as e,j as f,y as g,W as h,b as i,at as j,he as k,Oe as l,ye as m,pt as n,ft as o,dt as p,Re as q,be as r,Ae as s,xe as t,Le as u,gt as v,_t as w,Et as x,mt as y,ht as z,Ot as A,yt as B,Rt as C,bt as D,At as E,Te as F,Pe as G,Ie as H,Ce as I,we as J,Se as K,Ne as L,Ue as M,xt as N,U as O,De as P,Lt as Q,Tt as R,Pt as S,It as T,Ct as U,wt as V,St as W,I as X};
|
|
36
|
-
/*! For license information please see chunk-
|
|
35
|
+
`)+" "+n[1]:n[0]+t+" "+e.join(", ")+" "+n[1]}r(Je,"reduceToSingleString");var re=r((e,...t)=>K(R,e,t),"format");var G=class{static{r(this,"Debugger")}manager;ns;color;last;enabled;constructor(t,n){this.manager=t,this.ns=n,this.color=J(n),this.last=0,this.enabled=t.enabled.some(s=>s.test(n))}log(...t){if(!this.enabled)return;let n,s=t[0];typeof s=="function"?n=s():n=String(s);let i=Date.now()-(this.last||Date.now());n=re(n,...t);let u=`${this.color(this.ns)} ${n} ${this.color(`+${i}ms`)}`;console.log(u),this.last=Date.now()}},$=class{static{r(this,"DebugManager")}debuggers;enabled;constructor(t){this.debuggers=new Map,this.enabled=t??[]}};function Ke(e){return!e||e.length===0?[]:(e=e.replace(/\s/g,"").replace(/\*/g,".+"),e.split(",").map(t=>new RegExp(`^${t}$`)))}r(Ke,"extract");var U;function oe(e){let t=globalThis.DEBUG;U||(U=new $(Ke(t)));let n=new G(U,e);return U.debuggers.set(e,n),Object.assign(n.log.bind(n),{self:n})}r(oe,"debug");function Xe(e){if(e.length>=255)throw new TypeError("Alphabet too long");let t=new Uint8Array(256);for(let c=0;c<t.length;c++)t[c]=255;for(let c=0;c<e.length;c++){let a=e.charAt(c),g=a.charCodeAt(0);if(t[g]!==255)throw new TypeError(a+" is ambiguous");t[g]=c}let n=e.length,s=e.charAt(0),i=Math.log(n)/Math.log(256),u=Math.log(256)/Math.log(n);function o(c){if(c instanceof Uint8Array||(ArrayBuffer.isView(c)?c=new Uint8Array(c.buffer,c.byteOffset,c.byteLength):Array.isArray(c)&&(c=Uint8Array.from(c))),!(c instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(c.length===0)return"";let a=0,g=0,d=0,_=c.length;for(;d!==_&&c[d]===0;)d++,a++;let h=(_-d)*u+1>>>0,E=new Uint8Array(h);for(;d!==_;){let f=c[d],A=0;for(let O=h-1;(f!==0||A<g)&&O!==-1;O--,A++)f+=256*E[O]>>>0,E[O]=f%n>>>0,f=f/n>>>0;if(f!==0)throw new Error("Non-zero carry");g=A,d++}let m=h-g;for(;m!==h&&E[m]===0;)m++;let C=s.repeat(a);for(;m<h;++m)C+=e.charAt(E[m]);return C}r(o,"encode");function l(c){if(typeof c!="string")throw new TypeError("Expected String");if(c.length===0)return new Uint8Array;let a=0,g=0,d=0;for(;c[a]===s;)g++,a++;let _=(c.length-a)*i+1>>>0,h=new Uint8Array(_);for(;c[a];){let f=t[c.charCodeAt(a)];if(f===255)return;let A=0;for(let O=_-1;(f!==0||A<d)&&O!==-1;O--,A++)f+=n*h[O]>>>0,h[O]=f%256>>>0,f=f/256>>>0;if(f!==0)throw new Error("Non-zero carry");d=A,a++}let E=_-d;for(;E!==_&&h[E]===0;)E++;let m=new Uint8Array(g+(_-E)),C=g;for(;E!==_;)m[C++]=h[E++];return m}r(l,"decodeUnsafe");function p(c){let a=l(c);if(a)return a;throw new Error("Non-base"+n+" character")}return r(p,"decode"),{encode:o,decodeUnsafe:l,decode:p}}r(Xe,"base");var ie=Xe;var Qe="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",se=ie(Qe);var x=oe("zuplo:runtime:external-service");function et(){let e,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:t}=b.instance.runtime;if(t&&t!=="undefined")try{let n=atob(t);e=JSON.parse(n)}catch{}return e}r(et,"getServiceAuth");async function ce(e,t){let n=et();if(n)if(x(`Using external service auth. ClientId: ${n.clientId})`),typeof e=="string"){let s=new URL(e),i=s.hostname,u=t??{},o=new Headers(u.headers||{});o.set("CF-Access-Client-Id",n.clientId),o.set("CF-Access-Client-Secret",n.clientSecret),u.headers=o;let l;if(n.customServiceMapping&&n.customServiceMapping[i])l=`https://${n.customServiceMapping[i]}`;else if(b.instance.useLegacyServiceRouting)l=`https://${i}.zuptunnel.com`;else{x("Using sha256 service routing");let a=b.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE){let g=await tt(i,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE),d=ue(a.ENVIRONMENT_TYPE),_=await k(`${a.ACCOUNT_NAME}-${a.PROJECT_NAME}-${d}`);_==="40d7ad502f5d743997999594c177184a00161a77865423511f3a1ea21eb5a5e"||_==="d05bffe8fa91a300187d2cf43e8aa4a56bd809c442ae10d1ee49af7d29a5a11"?l=`https://${g}.zuptunnel.com`:l=`https://${g}.t.zuplo.app`}else throw x("Cannot use sha256 service routing, missing build variables"),new y("Failed to generate fully qualified tunnel url.")}let p=new URL(`${l}${s.pathname}${s.search}`);x(`Calling external service: ${p.toString()}`);let c=await P(p.toString(),u);if(c.status===403&&c.headers.get("cf-access-domain")!==null)throw I.console.error("403 Forbidden when calling external service.",{clientId:n.clientId,tunnelHost:l}),new y("Could not connect to secure tunnel.");return c}else throw x("Cannot call external service with Request object"),new y("Currently, we only support fetch(<some_string>, ...).");else throw x("There is no external service auth configured for this zup."),new y("There are no external services configured for this zup.")}r(ce,"externalServiceHandler");async function le(e,t){if(typeof e=="string"){let n=new URL(e),s=n.hostname,i=t??{},u=`http://${s}.zuplo.svc.cluster.local:9000`,o=new URL(`${u}${n.pathname}${n.search}`),l=new Headers(i.headers||{});return l.set(N,s),i.headers=l,await P(o.toString(),i)}else throw new y("Currently, we only support fetch(<some_string>, ...).")}r(le,"clusterServiceHandler");async function tt(e,t,n,s){let i=e.toLowerCase(),u=t.toLowerCase(),o=n.toLowerCase(),l=ue(s);x(`Hashing service name: ${u}-${i}.${u}-${o}-${l}`);let p=await k(`${u}-${i}`),c=await k(`${u}-${o}-${l}`);return`${p}.${c}`}r(tt,"hashServiceName");async function k(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(u=>u.toString(16).padStart(2,"0")).join("").slice(0,-1)}r(k,"hashSegment");function ue(e){let t=e.toLowerCase();switch(t){case"production":case"preview":return t;default:return"working-copy"}}r(ue,"sanitizeEnvironmentType");var V=new Map;V.set("service:",ce);V.set("local:",le);var P=globalThis.fetch;function B(e,t){let n=nt(t);if(typeof e=="string"){let s=new URL(e),i=V.get(s.protocol);return i?i(e,n):P(e,n)}else return P(e,n)}r(B,"internalFetch");globalThis.fetch=B;var nt=r(e=>{if(!e||e instanceof Request)return e;let t=e;if(!t.zuplo)return e;let n=e;return n.cf={cacheEverything:t.zuplo?.cacheEverything,cacheTtl:t.zuplo?.cacheTtlSeconds},delete e.zuplo,e},"transformInit");var rt={console:{log:console.log.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console),debug:console.debug.bind(console),assert:console.assert.bind(console),clear:console.clear.bind(console),count:console.count.bind(console),countReset:console.countReset.bind(console),dir:console.dir.bind(console),dirxml:console.dirxml.bind(console),group:console.group.bind(console),groupCollapsed:console.groupCollapsed.bind(console),groupEnd:console.groupEnd.bind(console),table:console.table.bind(console),time:console.time.bind(console),timeEnd:console.timeEnd.bind(console),timeLog:console.timeLog.bind(console),timeStamp:console.timeStamp.bind(console),trace:console.trace.bind(console),profile:console.profile.bind(console),profileEnd:console.profileEnd.bind(console)},fetch:B},I=rt;var Y="2025-02-06",ae=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1,allowCustomPorts:!1,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1,allowCustomPorts:!1,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!1,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!1,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2024-09-02":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!0,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2025-02-06":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!0,removeLegacyLogInitialization:!0,useForwardRedirectsPropOnUrlForwardHandler:!0}});function pe(){return new b({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:Y,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,IS_LOCAL_DEVELOPMENT:!1,COMPATIBILITY_FLAGS:ae[Y]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}r(pe,"getMockEnvironment");var b=class e{static{r(this,"Environment")}config;static#e;static#t=!1;static initialize(t){this.#e||(this.#e=new e(t),this.#t=!0)}static get instance(){return this.#t||(I.console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=pe()),this.#e}constructor({build:t,runtime:n}){let s;try{if(n.ZUPLO_SYSTEM_CONFIGURATIONS){let i=new TextDecoder().decode(se.decode(n.ZUPLO_SYSTEM_CONFIGURATIONS)),u=JSON.parse(i);for(let o of Object.keys(u))n[o]||(n[o]=u[o])}if(n.__ZUPLO_CONFIG){let i=atob(n.__ZUPLO_CONFIG);s=JSON.parse(i)}}catch(i){I.console.error("Failed to parse runtime configuration",i)}this.config=s??{},this.build=t,this.runtime=n,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get zuploEdgeApiUrl(){return this.config.zuplo_edge_api_url??"https://api.zuploedge.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get zuploClientAuthBucketId(){return this.config.zuplo_auth_client_bucket_id??"auth_o8PUdhKxSTOiB794GWPwLQCD"}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get developerApiUrl(){return this.config.developer_api_url??"https://dev.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuploedge.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuploedge.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuploedge.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuploedge.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get authClientId(){return this.config.auth_client_id??this.runtime.__ZUPLO_AUTH_CLIENT_ID}get authClientSecret(){return this.config.auth_client_secret??this.runtime.__ZUPLO_AUTH_CLIENT_SECRET}get authPublicKey(){return this.config.auth_public_key??this.runtime.__ZUPLO_AUTH_PUBLIC_KEY}get authPrivateKey(){return this.config.auth_private_key??this.runtime.__ZUPLO_AUTH_PRIVATE_KEY}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.IS_LOCAL_DEVELOPMENT}get isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};export{r as a,ot as b,it as c,st as d,oe as e,j as f,y as g,W as h,b as i,at as j,me as k,Oe as l,ye as m,pt as n,ft as o,gt as p,Re as q,be as r,Ae as s,xe as t,Le as u,dt as v,_t as w,Et as x,ht as y,mt as z,Ot as A,yt as B,Rt as C,bt as D,At as E,Te as F,Pe as G,Ie as H,Ce as I,we as J,Se as K,Ue as L,Ne as M,xt as N,N as O,De as P,Lt as Q,Tt as R,Pt as S,It as T,Ct as U,wt as V,St as W,I as X};
|
|
36
|
+
/*! For license information please see chunk-DJ47NX57.js.LEGAL.txt */
|
|
@@ -22,4 +22,4 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
import{a as i,i as o}from"./chunk-
|
|
25
|
+
import{a as i,i as o}from"./chunk-DJ47NX57.js";var p=(n=>(n.Build="build-data",n.CorsPreflight="cors-preflight",n.DeveloperPortal="developer-portal",n.ZudokuPortal="zudoku-portal",n.DeveloperPortalLegacy="developer-portal-legacy",n.StripePlugin="stripe-plugin",n.EmptyGatewayCatchall="empty-gateway-catchall",n.Ping="ping",n.UnmatchedPath="unmatched-path",n))(p||{});var g=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function l(e){return e.startsWith("__ZUPLO")||e.startsWith("ZUPLO_")?!g.includes(e)&&!e.startsWith("ZUPLO_PUBLIC_"):!1}i(l,"isRestrictedEnvVariableName");function c(e){return!!e.startsWith("ZUPLO_")}i(c,"isZuploReadableEnvVariableName");var u=new Proxy({},{get(e,t){let r=String(t);switch(r){case"ZUPLO_ENVIRONMENT_TYPE":return o.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return o.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return o.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return o.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return o.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return o.instance.build.BUILD_ID;case"ZUPLO_COMPATIBILITY_DATE":return o.instance.build.COMPATIBILITY_DATE}if(!(l(r)&&!c(r)))return o.instance.runtime[r]}});function f(e,t,r){return`_${a(`${e}_${t}_${r}`)}`}i(f,"getRawOperationDataIdentifierName");function L(e,t,r,s){return`_${a(e.toLowerCase())}_${t.toLowerCase()}_${r.toLowerCase()}_${s.toLowerCase()}`}i(L,"getIdForParameterSchema");function E(e,t,r){return`_${a(e.toLowerCase())}_${t.toLowerCase()}_rb_${a(r.toLowerCase())}`}i(E,"getIdForRequestBodySchema");function C(e,t){return`_${a(e)}_${a(t)}`}i(C,"getIdForRefSchema");function a(e){let t=e.replace(/\[/g,"_LBRACKET_").replace(/\]/g,"_RBRACKET_").replace(/\{/g,"_LCURLY_").replace(/\}/g,"_RCURLY_").replace(/\//g,"_SLASH_").replace(/-/g,"_DASH_").replace(/\./g,"_DOT_").replace(/\+/g,"_PLUS_").replace(/:/g,"_COLON_").replace(/@/g,"_AT_").replace(/\$/g,"_DOLLAR_").replace(/[^a-zA-Z0-9_]/g,"_");return/^[a-zA-Z_]/.test(t)||(t="_"+t),t}i(a,"sanitizedIdentifierName");export{p as a,l as b,c,u as d,f as e,L as f,E as g,C as h,a as i};
|
package/out/esm/index.js
CHANGED
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
import{a as Yt,d as qe,e as cw,f as Sa,g as ka,h as lw,i as dw}from"./chunk-VNF2YIXK.js";import{A as ci,B as li,C as di,D as pi,E as mi,F as fi,G as qf,H as Hf,I as hi,J as gi,K as Ff,L as yi,M as bi,N as Bf,O as Vf,P as Gf,Q as Wf,R as Jf,S as Kf,T as Qf,U as Dn,V as Zn,W as vi,X as G,a as i,b as aw,c as Xt,d as uw,e as Ke,f as xe,g as U,h as g,i as x,j as kf,k as zn,l as Ef,m as Wr,n as Tf,o as $f,p as Of,q as Cf,r as Af,s as Nf,t as Lf,u as zf,v as Df,w as Zf,x as Uf,y as jf,z as Mf}from"./chunk-IALZJEX3.js";var $h=aw(Li=>{"use strict";Object.defineProperty(Li,"__esModule",{value:!0});Li.parse=Hw;Li.serialize=Fw;var Dw=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,Zw=/^[\u0021-\u003A\u003C-\u007E]*$/,Uw=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,jw=/^[\u0020-\u003A\u003D-\u007E]*$/,Mw=Object.prototype.toString,qw=(()=>{let t=i(function(){},"C");return t.prototype=Object.create(null),t})();function Hw(t,e){let r=new qw,n=t.length;if(n<2)return r;let o=e?.decode||Bw,s=0;do{let a=t.indexOf("=",s);if(a===-1)break;let u=t.indexOf(";",s),c=u===-1?n:u;if(a>c){s=t.lastIndexOf(";",a-1)+1;continue}let l=Eh(t,s,a),d=Th(t,a,l),p=t.slice(l,d);if(r[p]===void 0){let m=Eh(t,a+1,c),f=Th(t,c,m),h=o(t.slice(m,f));r[p]=h}s=c+1}while(s<n);return r}i(Hw,"parse");function Eh(t,e,r){do{let n=t.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<r);return r}i(Eh,"startIndex");function Th(t,e,r){for(;e>r;){let n=t.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return r}i(Th,"endIndex");function Fw(t,e,r){let n=r?.encode||encodeURIComponent;if(!Dw.test(t))throw new TypeError(`argument name is invalid: ${t}`);let o=n(e);if(!Zw.test(o))throw new TypeError(`argument val is invalid: ${e}`);let s=t+"="+o;if(!r)return s;if(r.maxAge!==void 0){if(!Number.isInteger(r.maxAge))throw new TypeError(`option maxAge is invalid: ${r.maxAge}`);s+="; Max-Age="+r.maxAge}if(r.domain){if(!Uw.test(r.domain))throw new TypeError(`option domain is invalid: ${r.domain}`);s+="; Domain="+r.domain}if(r.path){if(!jw.test(r.path))throw new TypeError(`option path is invalid: ${r.path}`);s+="; Path="+r.path}if(r.expires){if(!Vw(r.expires)||!Number.isFinite(r.expires.valueOf()))throw new TypeError(`option expires is invalid: ${r.expires}`);s+="; Expires="+r.expires.toUTCString()}if(r.httpOnly&&(s+="; HttpOnly"),r.secure&&(s+="; Secure"),r.partitioned&&(s+="; Partitioned"),r.priority)switch(typeof r.priority=="string"?r.priority.toLowerCase():void 0){case"low":s+="; Priority=Low";break;case"medium":s+="; Priority=Medium";break;case"high":s+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${r.priority}`)}if(r.sameSite)switch(typeof r.sameSite=="string"?r.sameSite.toLowerCase():r.sameSite){case!0:case"strict":s+="; SameSite=Strict";break;case"lax":s+="; SameSite=Lax";break;case"none":s+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${r.sameSite}`)}return s}i(Fw,"serialize");function Bw(t){if(t.indexOf("%")===-1)return t;try{return decodeURIComponent(t)}catch{return t}}i(Bw,"decode");function Vw(t){return Mw.call(t)==="[object Date]"}i(Vw,"isDate")});Function.prototype.toString=function(){return"[native code]"};var wi=globalThis,Xf=wi.caches;if(Xf){let t=Xf.open;wi.caches.open=function(e){let r=x.instance.deploymentName??x.instance.build.BUILD_ID;return t.call(this,`${r}-${e}`)},delete wi.caches.default,Object.freeze(wi.caches)}var xi=new Set,Yf=new Set;function y(t){Yf.has(t)||(Yf.add(t),xi.add(t))}i(y,"trackFeature");function eh(){let t=[...xi];return xi.clear(),t}i(eh,"getUnsentFeatures");function th(t){for(let e of t)xi.add(e)}i(th,"restoreFeatures");function xt(t,e){t.has("Authorization")||t.set("Authorization",`Bearer ${x.instance.authApiJWT}`),t.set("zp-rid",e??`global-${crypto.randomUUID()}`),t.set("zp-dn",x.instance.deploymentName??"unknown"),t.set("User-Agent",x.instance.systemUserAgent),t.set("zp-compat-date",x.instance.build.COMPATIBILITY_DATE??"none")}i(xt,"setZuploHeaders");async function pw(t,e={}){y("utility.zuplo-api-services");let{method:r="GET",data:n}=e,o=new URL(t,x.instance.zuploEdgeApiUrl),s=new Headers(e.headers);xt(s),s.set("Content-Type","application/json");let a={method:r,headers:s};n&&(a.body=JSON.stringify(n));let u=await G.fetch(o,a),c;try{if(!u.ok)throw c=await u.clone().json(),new Error(`Error ${u.status}: ${JSON.stringify(c)||"Request failed"}`);if(u.status===204)return;c=await u.clone().json()}catch(l){throw new Error(l.message)}return c}i(pw,"apiServices");var rh=new Map,Ea=class{static{i(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let r=this.#n.get(e);if(!r)return;let n=Date.now();if(n>r.expiresAt){this.#n.delete(e);return}return r.lastUsed=n,this.#o(),r?.data}put(e,r,n){if(n<=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+n*1e3,data:r};this.#r.push(e),this.#n.set(e,s)}delete(e){let r=this.#r.indexOf(e);r>=0&&this.#r.slice(r,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((r,n)=>{r.expiresAt>=e&&this.#n.delete(n)})}},Rt=class{static{i(this,"MemoryCache")}constructor(e,r={maxSize:1e3}){this.name=e;let n=rh.get(e);n||(n=new Ea(r),rh.set(e,n)),this.#e=n}name;#e;get(e){return this.#e.get(e)}put(e,r,n){return this.#e.put(e,r,n)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var Ta="__zuplo-expiry-header",Un=class{static{i(this,"ZoneCache")}constructor(e,r){this.#t=e,this.#e=r}#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 r=await this.#r(),n=this.#o(e),o=await r.match(n);if(!o)return;let s=o.headers.get(Ta);if(!s){try{await r.delete(n)}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 r.delete(n)}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(r){this.logDebug(r)}}async put(e,r,n){let o=new Headers({"cache-control":`s-maxage=${n}, must-revalidate`,"content-type":"application/json"});o.set(Ta,`${Date.now()+n*1e3}`);let s=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(r),{headers:o});await s.put(a,u)}async delete(e){let r=await this.#r(),n=this.#o(e);try{await r.delete(n)}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 r=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});r.set(Ta,`${Date.now()}`);let n=await this.#r(),o=this.#o(e),s=new Response("",{headers:r});await n.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 ke=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,r){let n=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Rt(n),this.#n=new Un(n,r),this.#r=r}#e;#t;#n;#r;async get(e){let r=this.#t.get(e);if(r)return r;let n=await this.#n.get(e);if(n){let o=Math.floor((n.expires-Date.now())/1e3);if(o>0)return this.#t.put(e,n.data,o),n.data}}put(e,r,n){this.#t.put(e,r,n);let o={data:r,expires:Date.now()+n*1e3},s=this.#n.put(e,o,n).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(s)}async delete(e){this.#t.delete(e),await this.#n.delete(e)}};var $a="__zuplo-expiry-header",Oa=class{static{i(this,"StreamingZoneCache")}constructor(e,r){this.#t=e,this.#e=r}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://streaming-zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let r=await this.#r(),n=this.#o(e),o=await r.match(n);if(!o)return;let s=o.headers.get($a);if(!s){await r.delete(n).catch(u=>{this.logDebug(`StreamingZoneCache: error deleting missing expiry entry ${e}`,u)});return}let a=parseInt(s,10);if(Date.now()>=a){await r.delete(n).catch(u=>{this.logDebug(`StreamingZoneCache: error deleting expired entry ${e}`,u)});return}return o.body??void 0}catch(r){this.logDebug(`get(${e}) failed`,r);return}}async put(e,r,n){let o=new Headers({"cache-control":`s-maxage=${n}, must-revalidate`});o.set($a,`${Date.now()+n*1e3}`);let s=new Response(r,{headers:o}),a=await this.#r(),u=this.#o(e);await a.put(u,s)}async delete(e){try{await(await this.#r()).delete(this.#o(e))}catch(r){this.logDebug(`delete(${e}) fallback needed`,r),await this.deleteFallback(e)}}async deleteFallback(e){let r=new Headers({"Cache-Control":"s-maxage=0, must-revalidate",[$a]:`${Date.now()}`}),n=new Response("",{headers:r}),o=await this.#r(),s=this.#o(e);await o.put(s,n)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`StreamingZoneCache(${this.#t}):`,...e):"log"in this.#e&&this.#e.log.debug(`StreamingZoneCache(${this.#t}):`,...e)}};var Ie=class t{static{i(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,r){t.set(e,this.#t,r)}get(e){return t.get(e,this.#t)}static set(e,r,n){t.#e||(t.#e=new WeakMap);let o=t.#e.get(e);o||(o=new Map),o.set(r,n),t.#e.set(e,o)}static get(e,r){return t.#e||(t.#e=new WeakMap),t.#e.get(e)?.get(r)}};import{trace as sx}from"@opentelemetry/api";import{SpanStatusCode as Sw,trace as kw}from"@opentelemetry/api";import{SpanStatusCode as Ii,trace as Si}from"@opentelemetry/api";var nh=i(t=>(e,r)=>t(e,r),"globalRequestHandlerProxy");function oh(t){nh=t}i(oh,"setTelemetryInitFunction");var ih=i(t=>nh(t),"proxyHandler");var er=class{static{i(this,"RuntimePlugin")}},Me=class extends er{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e){}},Ri=class extends Me{static{i(this,"MeteringPlugin")}},jn=class extends er{static{i(this,"TelemetryPlugin")}};var Mn=class t{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=i(async e=>{let r=e.problem,n=JSON.stringify(r,null,2);return new Response(n,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})},"problemResponseFormat");static setProblemResponseFormat(e){e&&(y("runtime.problem-response-formatter"),t.problemResponseFormat=(r,n,o)=>{try{return e(r,n,o)}catch(s){throw new U("Error in custom 'problemResponseFormat'",{cause:s})}})}},yr=class{static{i(this,"ProblemResponseFormatter")}static async format(e,r,n){return await Mn.problemResponseFormat(e,r,n)}};function _i(t){for(let e in t){let r=t[e];r&&typeof r=="object"&&_i(r)}return Object.freeze(t)}i(_i,"deepFreeze");var ye=class t extends Request{static{i(this,"ZuploRequest")}#e=void 0;#t;constructor(e,r){super(e,r);let n=r?.params;n?this.#t=n:e instanceof t?this.#t=e.#t:this.#t={};let o=r?.user;o?this.user=o:e instanceof t&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},r=new URL(this.url).searchParams;for(let[n,o]of r.entries())e[n]=o;this.#e=e}return _i(this.#e)}get params(){return _i(this.#t)}user};var za={},Lt=[],Ca=[],Aa=[],Na=[],La=[];var Pi={addPlugin(t){Lt.push(t)},addRequestHook(t){Ca.push(t)},addResponseSendingHook(t){Aa.push(t)},addResponseSendingFinalHook(t){Na.push(t)},addPreRoutingHook(t){La.push(t)}},ah=i(async(t,e)=>{if(Ca.length===0)return t;let r=Si.getTracer("extension");return r.startActiveSpan("hook:onRequest",async n=>{try{let o=t;for(let s of Ca){let a=await r.startActiveSpan(s.name,async u=>{let c=await s(o,e);if(c instanceof ye||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:Ii.ERROR}),l}});if(a instanceof ye)o=a;else return a}return o}finally{n.end()}})},"invokeOnRequestExtensions"),uh=i(async(t,e,r)=>{if(Aa.length===0)return t;let n=Si.getTracer("extension");return n.startActiveSpan("hook:onResponseSending",async o=>{try{let s=t;for(let a of Aa)await n.startActiveSpan(a.name,async u=>{let c=await a(t,e,r);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:Ii.ERROR}),u.end(),l}});return s}finally{o.end()}})},"invokeOnResponseSendingExtensions"),ch=i(async(t,e,r)=>{if(Na.length===0)return;let n=Si.getTracer("extension");return n.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let s of Na)await n.startActiveSpan(s.name,async a=>{try{await s(t,e,r)}catch(u){throw a.recordException(u),a.setStatus({code:Ii.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),lh=i(async t=>{if(La.length===0)return t;let e=Si.getTracer("extension");return e.startActiveSpan("hook:preRouting",async r=>{try{let n=t;for(let o of La)n=await e.startActiveSpan(o.name,async a=>{try{let u=await o(n);if(u instanceof Request)return u;{let c=new U(`Invalid state - the PreRouting hook must return a Request. Received ${typeof u}.`);throw a.recordException(c),a.setStatus({code:Ii.ERROR}),c}}finally{a.end()}});return n}finally{r.end()}})},"invokePreRoutingHooks"),sh=!1;async function dh(t){if(!sh){t&&(y("runtime.extensions"),await t(Pi)),za.value=Pi;for(let e of Lt)if(e instanceof jn){let{requestHandlerProxy:r}=e.instrument({accountName:x.instance.build.ACCOUNT_NAME,projectName:x.instance.build.PROJECT_NAME,buildId:x.instance.build.BUILD_ID,zuploVersion:x.instance.build.ZUPLO_VERSION,compatibilityDate:x.instance.build.COMPATIBILITY_DATE,instanceId:x.instance.instanceId,environmentType:x.instance.loggingEnvironmentType,environmentStage:x.instance.loggingEnvironmentStage,deploymentName:x.instance.deploymentName});oh(r)}await Promise.all(Lt.map(async e=>{e instanceof Me&&await e.initialize(Pi)})),Mn.setProblemResponseFormat(Pi.problemResponseFormat),sh=!0}}i(dh,"initializeRuntime");var Da={Json:"application/json",Form:"application/x-www-form-urlencoded"};function Za(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(Da.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(Da.Json)||!e?JSON.stringify(t):t}i(Za,"serialize");function Jr(t){let{developerPortal:e}=Se.instance.runtimeSettings;return e.enabled&&e.basePath&&t.pathname.startsWith(e.basePath)||t.pathname.startsWith("/__zuplo/")||t.pathname.startsWith("/__/zuplo/")}i(Jr,"isSystemRoute");var ki=(O=>(O[O.CONTINUE=100]="CONTINUE",O[O.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",O[O.PROCESSING=102]="PROCESSING",O[O.EARLY_HINTS=103]="EARLY_HINTS",O[O.OK=200]="OK",O[O.CREATED=201]="CREATED",O[O.ACCEPTED=202]="ACCEPTED",O[O.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",O[O.NO_CONTENT=204]="NO_CONTENT",O[O.RESET_CONTENT=205]="RESET_CONTENT",O[O.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",O[O.MULTI_STATUS=207]="MULTI_STATUS",O[O.ALREADY_REPORTED=208]="ALREADY_REPORTED",O[O.IM_USED=226]="IM_USED",O[O.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",O[O.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",O[O.FOUND=302]="FOUND",O[O.SEE_OTHER=303]="SEE_OTHER",O[O.NOT_MODIFIED=304]="NOT_MODIFIED",O[O.USE_PROXY=305]="USE_PROXY",O[O.SWITCH_PROXY=306]="SWITCH_PROXY",O[O.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",O[O.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",O[O.BAD_REQUEST=400]="BAD_REQUEST",O[O.UNAUTHORIZED=401]="UNAUTHORIZED",O[O.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",O[O.FORBIDDEN=403]="FORBIDDEN",O[O.NOT_FOUND=404]="NOT_FOUND",O[O.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",O[O.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",O[O.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",O[O.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",O[O.CONFLICT=409]="CONFLICT",O[O.GONE=410]="GONE",O[O.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",O[O.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",O[O.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",O[O.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",O[O.URI_TOO_LONG=414]="URI_TOO_LONG",O[O.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",O[O.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",O[O.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",O[O.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",O[O.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",O[O.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",O[O.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",O[O.LOCKED=423]="LOCKED",O[O.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",O[O.TOO_EARLY=425]="TOO_EARLY",O[O.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",O[O.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",O[O.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",O[O.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",O[O.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",O[O.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",O[O.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",O[O.BAD_GATEWAY=502]="BAD_GATEWAY",O[O.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",O[O.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",O[O.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",O[O.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",O[O.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",O[O.LOOP_DETECTED=508]="LOOP_DETECTED",O[O.NOT_EXTENDED=510]="NOT_EXTENDED",O[O.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",O))(ki||{}),ph={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 mw={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"},Ua=mw;function fw(t){return`${new URL(t.url).pathname}`}i(fw,"instance");function hw(t,e){let r={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:x.instance.build.BUILD_ID},n=t.headers.get(Wr);return n&&(r.rayId=n),r}i(hw,"trace");var gw=i((t,e,r,n,o)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:fw(e),trace:hw(e,r),...n},additionalHeaders:o,statusText:Ua[t.status]}),"merge"),ja=class{static{i(this,"HttpProblemsBase")}static format=i((e,r,n)=>"problem"in e?yr.format(e,r,n):yr.format({problem:e},r,n),"format");static getProblemFromStatus(e,r){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:ph[e],...r}}},A=class extends ja{static{i(this,"HttpProblems")}static#e(e,r,n,o,s){let a=gw(this.getProblemFromStatus(e),r,n,o,s);return yr.format(a,r,n)}static continue=i((e,r,n,o)=>this.#e(200,e,r,n,o),"continue");static switchingProtocols=i((e,r,n,o)=>this.#e(101,e,r,n,o),"switchingProtocols");static processing=i((e,r,n,o)=>this.#e(102,e,r,n,o),"processing");static earlyHints=i((e,r,n,o)=>this.#e(103,e,r,n,o),"earlyHints");static ok=i((e,r,n,o)=>this.#e(200,e,r,n,o),"ok");static created=i((e,r,n,o)=>this.#e(201,e,r,n,o),"created");static accepted=i((e,r,n,o)=>this.#e(202,e,r,n,o),"accepted");static nonAuthoritativeInformation=i((e,r,n,o)=>this.#e(203,e,r,n,o),"nonAuthoritativeInformation");static noContent=i((e,r,n,o)=>this.#e(204,e,r,n,o),"noContent");static resetContent=i((e,r,n,o)=>this.#e(205,e,r,n,o),"resetContent");static partialContent=i((e,r,n,o)=>this.#e(206,e,r,n,o),"partialContent");static multiStatus=i((e,r,n,o)=>this.#e(207,e,r,n,o),"multiStatus");static alreadyReported=i((e,r,n,o)=>this.#e(208,e,r,n,o),"alreadyReported");static imUsed=i((e,r,n,o)=>this.#e(226,e,r,n,o),"imUsed");static multipleChoices=i((e,r,n,o)=>this.#e(300,e,r,n,o),"multipleChoices");static movedPermanently=i((e,r,n,o)=>this.#e(301,e,r,n,o),"movedPermanently");static found=i((e,r,n,o)=>this.#e(302,e,r,n,o),"found");static seeOther=i((e,r,n,o)=>this.#e(303,e,r,n,o),"seeOther");static notModified=i((e,r,n,o)=>this.#e(304,e,r,n,o),"notModified");static useProxy=i((e,r,n,o)=>this.#e(305,e,r,n,o),"useProxy");static switchProxy=i((e,r,n,o)=>this.#e(306,e,r,n,o),"switchProxy");static temporaryRedirect=i((e,r,n,o)=>this.#e(307,e,r,n,o),"temporaryRedirect");static permanentRedirect=i((e,r,n,o)=>this.#e(308,e,r,n,o),"permanentRedirect");static badRequest=i((e,r,n,o)=>this.#e(400,e,r,n,o),"badRequest");static unauthorized=i((e,r,n,o)=>this.#e(401,e,r,n,o),"unauthorized");static paymentRequired=i((e,r,n,o)=>this.#e(402,e,r,n,o),"paymentRequired");static forbidden=i((e,r,n,o)=>this.#e(403,e,r,n,o),"forbidden");static notFound=i((e,r,n,o)=>this.#e(404,e,r,n,o),"notFound");static methodNotAllowed=i((e,r,n,o)=>this.#e(405,e,r,n,o),"methodNotAllowed");static notAcceptable=i((e,r,n,o)=>this.#e(406,e,r,n,o),"notAcceptable");static proxyAuthenticationRequired=i((e,r,n,o)=>this.#e(407,e,r,n,o),"proxyAuthenticationRequired");static requestTimeout=i((e,r,n,o)=>this.#e(408,e,r,n,o),"requestTimeout");static conflict=i((e,r,n,o)=>this.#e(409,e,r,n,o),"conflict");static gone=i((e,r,n,o)=>this.#e(410,e,r,n,o),"gone");static lengthRequired=i((e,r,n,o)=>this.#e(411,e,r,n,o),"lengthRequired");static preconditionFailed=i((e,r,n,o)=>this.#e(412,e,r,n,o),"preconditionFailed");static contentTooLarge=i((e,r,n,o)=>this.#e(413,e,r,n,o),"contentTooLarge");static uriTooLong=i((e,r,n,o)=>this.#e(414,e,r,n,o),"uriTooLong");static unsupportedMediaType=i((e,r,n,o)=>this.#e(415,e,r,n,o),"unsupportedMediaType");static rangeNotSatisfiable=i((e,r,n,o)=>this.#e(416,e,r,n,o),"rangeNotSatisfiable");static expectationFailed=i((e,r,n,o)=>this.#e(417,e,r,n,o),"expectationFailed");static imATeapot=i((e,r,n,o)=>this.#e(418,e,r,n,o),"imATeapot");static misdirectedRequest=i((e,r,n,o)=>this.#e(421,e,r,n,o),"misdirectedRequest");static unprocessableContent=i((e,r,n,o)=>this.#e(422,e,r,n,o),"unprocessableContent");static locked=i((e,r,n,o)=>this.#e(423,e,r,n,o),"locked");static failedDependency=i((e,r,n,o)=>this.#e(424,e,r,n,o),"failedDependency");static tooEarly=i((e,r,n,o)=>this.#e(425,e,r,n,o),"tooEarly");static upgradeRequired=i((e,r,n,o)=>this.#e(426,e,r,n,o),"upgradeRequired");static preconditionRequired=i((e,r,n,o)=>this.#e(428,e,r,n,o),"preconditionRequired");static tooManyRequests=i((e,r,n,o)=>this.#e(429,e,r,n,o),"tooManyRequests");static requestHeaderFieldsTooLarge=i((e,r,n,o)=>this.#e(431,e,r,n,o),"requestHeaderFieldsTooLarge");static unavailableForLegalReasons=i((e,r,n,o)=>this.#e(451,e,r,n,o),"unavailableForLegalReasons");static internalServerError=i((e,r,n,o)=>this.#e(500,e,r,n,o),"internalServerError");static notImplemented=i((e,r,n,o)=>this.#e(501,e,r,n,o),"notImplemented");static badGateway=i((e,r,n,o)=>this.#e(502,e,r,n,o),"badGateway");static serviceUnavailable=i((e,r,n,o)=>this.#e(503,e,r,n,o),"serviceUnavailable");static gatewayTimeout=i((e,r,n,o)=>this.#e(504,e,r,n,o),"gatewayTimeout");static httpVersionNotSupported=i((e,r,n,o)=>this.#e(505,e,r,n,o),"httpVersionNotSupported");static variantAlsoNegotiates=i((e,r,n,o)=>this.#e(506,e,r,n,o),"variantAlsoNegotiates");static insufficientStorage=i((e,r,n,o)=>this.#e(507,e,r,n,o),"insufficientStorage");static loopDetected=i((e,r,n,o)=>this.#e(508,e,r,n,o),"loopDetected");static notExtended=i((e,r,n,o)=>this.#e(510,e,r,n,o),"notExtended");static networkAuthenticationRequired=i((e,r,n,o)=>this.#e(511,e,r,n,o),"networkAuthenticationRequired")};var{toString:yw}=Object.prototype,{propertyIsEnumerable:bw}=Object.prototype;function Ma(t){return yw.call(t)}i(Ma,"toString");function nt(t){return typeof t=="string"}i(nt,"isString");function Kr(t){return nt(t)&&t!==""}i(Kr,"isNonEmptyString");function mh(t){return Ma(t)==="[object RegExp]"}i(mh,"isRegexp");function fh(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>bw.call(t,e))]}i(fh,"getOwnEnumerableKeys");function br(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof RegExp)&&!(t instanceof Date)}i(br,"isObject");function qa(t){return typeof t=="number"&&!isNaN(t)}i(qa,"isNumber");function Ha(t){return t===!0||t===!1}i(Ha,"isBoolean");function hh(t){return typeof t>"u"}i(hh,"isUndefined");function gh(t){return hh(t)||t===null}i(gh,"isUndefinedOrNull");function qn(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}i(qn,"isErrorLike");var vw=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(t=>[t.name,t]),ww=new Map(vw);var xw=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],Fa=Symbol(".toJSON was called"),Rw=i(t=>{t[Fa]=!0;let e=t.toJSON();return delete t[Fa],e},"toJSON"),_w=i(t=>ww.get(t)??Error,"getErrorConstructor"),yh=i(({from:t,seen:e,to:r,forceEnumerable:n,maxDepth:o,depth:s,useToJSON:a,serialize:u})=>{if(!r)if(Array.isArray(t))r=[];else if(!u&&qn(t)){let l=_w(t.name);r=new l}else r={};if(e.push(t),s>=o)return r;if(a&&typeof t.toJSON=="function"&&t[Fa]!==!0)return Rw(t);let c=i(l=>yh({from:l,seen:[...e],forceEnumerable:n,maxDepth:o,depth:s,useToJSON:a,serialize:u}),"continueDestroyCircular");for(let[l,d]of Object.entries(t)){if(typeof Buffer=="function"&&Buffer.isBuffer(d)){r[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){r[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){r[l]=d;continue}if(!e.includes(t[l])){s++,r[l]=c(t[l]);continue}r[l]="[Circular]"}}for(let{property:l,enumerable:d}of xw)typeof t[l]<"u"&&t[l]!==null&&Object.defineProperty(r,l,{value:qn(t[l])?c(t[l]):t[l],enumerable:n?!0:d,configurable:!0,writable:!0});return r},"destroyCircular");function vr(t,e){let r=e?.maxDepth??Number.POSITIVE_INFINITY,n=e?.useToJSON??!0;return typeof t=="object"&&t!==null?yh({from:t,seen:[],forceEnumerable:!0,maxDepth:r,depth:0,useToJSON:n,serialize:!0}):typeof t=="function"?`[Function: ${t.name??"anonymous"}]`:t}i(vr,"serializeError");var Pw=/file:\/\/\/(.*?)\/dist\//g,Iw="at async Event.respondWith";function Ba(t){return typeof t!="string"?t:t.split(`
|
|
25
|
+
import{a as Yt,d as qe,e as cw,f as Sa,g as ka,h as lw,i as dw}from"./chunk-SEPHSKCD.js";import{A as ci,B as li,C as di,D as pi,E as mi,F as fi,G as qf,H as Hf,I as hi,J as gi,K as Ff,L as yi,M as bi,N as Bf,O as Vf,P as Gf,Q as Wf,R as Jf,S as Kf,T as Qf,U as Dn,V as Zn,W as vi,X as G,a as i,b as aw,c as Xt,d as uw,e as Ke,f as xe,g as U,h as g,i as x,j as kf,k as zn,l as Ef,m as Wr,n as Tf,o as $f,p as Of,q as Cf,r as Af,s as Nf,t as Lf,u as zf,v as Df,w as Zf,x as Uf,y as jf,z as Mf}from"./chunk-DJ47NX57.js";var $h=aw(Li=>{"use strict";Object.defineProperty(Li,"__esModule",{value:!0});Li.parse=Hw;Li.serialize=Fw;var Dw=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,Zw=/^[\u0021-\u003A\u003C-\u007E]*$/,Uw=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,jw=/^[\u0020-\u003A\u003D-\u007E]*$/,Mw=Object.prototype.toString,qw=(()=>{let t=i(function(){},"C");return t.prototype=Object.create(null),t})();function Hw(t,e){let r=new qw,n=t.length;if(n<2)return r;let o=e?.decode||Bw,s=0;do{let a=t.indexOf("=",s);if(a===-1)break;let u=t.indexOf(";",s),c=u===-1?n:u;if(a>c){s=t.lastIndexOf(";",a-1)+1;continue}let l=Eh(t,s,a),d=Th(t,a,l),p=t.slice(l,d);if(r[p]===void 0){let m=Eh(t,a+1,c),f=Th(t,c,m),h=o(t.slice(m,f));r[p]=h}s=c+1}while(s<n);return r}i(Hw,"parse");function Eh(t,e,r){do{let n=t.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<r);return r}i(Eh,"startIndex");function Th(t,e,r){for(;e>r;){let n=t.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return r}i(Th,"endIndex");function Fw(t,e,r){let n=r?.encode||encodeURIComponent;if(!Dw.test(t))throw new TypeError(`argument name is invalid: ${t}`);let o=n(e);if(!Zw.test(o))throw new TypeError(`argument val is invalid: ${e}`);let s=t+"="+o;if(!r)return s;if(r.maxAge!==void 0){if(!Number.isInteger(r.maxAge))throw new TypeError(`option maxAge is invalid: ${r.maxAge}`);s+="; Max-Age="+r.maxAge}if(r.domain){if(!Uw.test(r.domain))throw new TypeError(`option domain is invalid: ${r.domain}`);s+="; Domain="+r.domain}if(r.path){if(!jw.test(r.path))throw new TypeError(`option path is invalid: ${r.path}`);s+="; Path="+r.path}if(r.expires){if(!Vw(r.expires)||!Number.isFinite(r.expires.valueOf()))throw new TypeError(`option expires is invalid: ${r.expires}`);s+="; Expires="+r.expires.toUTCString()}if(r.httpOnly&&(s+="; HttpOnly"),r.secure&&(s+="; Secure"),r.partitioned&&(s+="; Partitioned"),r.priority)switch(typeof r.priority=="string"?r.priority.toLowerCase():void 0){case"low":s+="; Priority=Low";break;case"medium":s+="; Priority=Medium";break;case"high":s+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${r.priority}`)}if(r.sameSite)switch(typeof r.sameSite=="string"?r.sameSite.toLowerCase():r.sameSite){case!0:case"strict":s+="; SameSite=Strict";break;case"lax":s+="; SameSite=Lax";break;case"none":s+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${r.sameSite}`)}return s}i(Fw,"serialize");function Bw(t){if(t.indexOf("%")===-1)return t;try{return decodeURIComponent(t)}catch{return t}}i(Bw,"decode");function Vw(t){return Mw.call(t)==="[object Date]"}i(Vw,"isDate")});Function.prototype.toString=function(){return"[native code]"};var wi=globalThis,Xf=wi.caches;if(Xf){let t=Xf.open;wi.caches.open=function(e){let r=x.instance.deploymentName??x.instance.build.BUILD_ID;return t.call(this,`${r}-${e}`)},delete wi.caches.default,Object.freeze(wi.caches)}var xi=new Set,Yf=new Set;function y(t){Yf.has(t)||(Yf.add(t),xi.add(t))}i(y,"trackFeature");function eh(){let t=[...xi];return xi.clear(),t}i(eh,"getUnsentFeatures");function th(t){for(let e of t)xi.add(e)}i(th,"restoreFeatures");function xt(t,e){t.has("Authorization")||t.set("Authorization",`Bearer ${x.instance.authApiJWT}`),t.set("zp-rid",e??`global-${crypto.randomUUID()}`),t.set("zp-dn",x.instance.deploymentName??"unknown"),t.set("User-Agent",x.instance.systemUserAgent),t.set("zp-compat-date",x.instance.build.COMPATIBILITY_DATE??"none")}i(xt,"setZuploHeaders");async function pw(t,e={}){y("utility.zuplo-api-services");let{method:r="GET",data:n}=e,o=new URL(t,x.instance.zuploEdgeApiUrl),s=new Headers(e.headers);xt(s),s.set("Content-Type","application/json");let a={method:r,headers:s};n&&(a.body=JSON.stringify(n));let u=await G.fetch(o,a),c;try{if(!u.ok)throw c=await u.clone().json(),new Error(`Error ${u.status}: ${JSON.stringify(c)||"Request failed"}`);if(u.status===204)return;c=await u.clone().json()}catch(l){throw new Error(l.message)}return c}i(pw,"apiServices");var rh=new Map,Ea=class{static{i(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let r=this.#n.get(e);if(!r)return;let n=Date.now();if(n>r.expiresAt){this.#n.delete(e);return}return r.lastUsed=n,this.#o(),r?.data}put(e,r,n){if(n<=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+n*1e3,data:r};this.#r.push(e),this.#n.set(e,s)}delete(e){let r=this.#r.indexOf(e);r>=0&&this.#r.slice(r,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((r,n)=>{r.expiresAt>=e&&this.#n.delete(n)})}},Rt=class{static{i(this,"MemoryCache")}constructor(e,r={maxSize:1e3}){this.name=e;let n=rh.get(e);n||(n=new Ea(r),rh.set(e,n)),this.#e=n}name;#e;get(e){return this.#e.get(e)}put(e,r,n){return this.#e.put(e,r,n)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var Ta="__zuplo-expiry-header",Un=class{static{i(this,"ZoneCache")}constructor(e,r){this.#t=e,this.#e=r}#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 r=await this.#r(),n=this.#o(e),o=await r.match(n);if(!o)return;let s=o.headers.get(Ta);if(!s){try{await r.delete(n)}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 r.delete(n)}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(r){this.logDebug(r)}}async put(e,r,n){let o=new Headers({"cache-control":`s-maxage=${n}, must-revalidate`,"content-type":"application/json"});o.set(Ta,`${Date.now()+n*1e3}`);let s=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(r),{headers:o});await s.put(a,u)}async delete(e){let r=await this.#r(),n=this.#o(e);try{await r.delete(n)}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 r=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});r.set(Ta,`${Date.now()}`);let n=await this.#r(),o=this.#o(e),s=new Response("",{headers:r});await n.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 ke=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,r){let n=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Rt(n),this.#n=new Un(n,r),this.#r=r}#e;#t;#n;#r;async get(e){let r=this.#t.get(e);if(r)return r;let n=await this.#n.get(e);if(n){let o=Math.floor((n.expires-Date.now())/1e3);if(o>0)return this.#t.put(e,n.data,o),n.data}}put(e,r,n){this.#t.put(e,r,n);let o={data:r,expires:Date.now()+n*1e3},s=this.#n.put(e,o,n).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(s)}async delete(e){this.#t.delete(e),await this.#n.delete(e)}};var $a="__zuplo-expiry-header",Oa=class{static{i(this,"StreamingZoneCache")}constructor(e,r){this.#t=e,this.#e=r}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://streaming-zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let r=await this.#r(),n=this.#o(e),o=await r.match(n);if(!o)return;let s=o.headers.get($a);if(!s){await r.delete(n).catch(u=>{this.logDebug(`StreamingZoneCache: error deleting missing expiry entry ${e}`,u)});return}let a=parseInt(s,10);if(Date.now()>=a){await r.delete(n).catch(u=>{this.logDebug(`StreamingZoneCache: error deleting expired entry ${e}`,u)});return}return o.body??void 0}catch(r){this.logDebug(`get(${e}) failed`,r);return}}async put(e,r,n){let o=new Headers({"cache-control":`s-maxage=${n}, must-revalidate`});o.set($a,`${Date.now()+n*1e3}`);let s=new Response(r,{headers:o}),a=await this.#r(),u=this.#o(e);await a.put(u,s)}async delete(e){try{await(await this.#r()).delete(this.#o(e))}catch(r){this.logDebug(`delete(${e}) fallback needed`,r),await this.deleteFallback(e)}}async deleteFallback(e){let r=new Headers({"Cache-Control":"s-maxage=0, must-revalidate",[$a]:`${Date.now()}`}),n=new Response("",{headers:r}),o=await this.#r(),s=this.#o(e);await o.put(s,n)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`StreamingZoneCache(${this.#t}):`,...e):"log"in this.#e&&this.#e.log.debug(`StreamingZoneCache(${this.#t}):`,...e)}};var Ie=class t{static{i(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,r){t.set(e,this.#t,r)}get(e){return t.get(e,this.#t)}static set(e,r,n){t.#e||(t.#e=new WeakMap);let o=t.#e.get(e);o||(o=new Map),o.set(r,n),t.#e.set(e,o)}static get(e,r){return t.#e||(t.#e=new WeakMap),t.#e.get(e)?.get(r)}};import{trace as sx}from"@opentelemetry/api";import{SpanStatusCode as Sw,trace as kw}from"@opentelemetry/api";import{SpanStatusCode as Ii,trace as Si}from"@opentelemetry/api";var nh=i(t=>(e,r)=>t(e,r),"globalRequestHandlerProxy");function oh(t){nh=t}i(oh,"setTelemetryInitFunction");var ih=i(t=>nh(t),"proxyHandler");var er=class{static{i(this,"RuntimePlugin")}},Me=class extends er{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e){}},Ri=class extends Me{static{i(this,"MeteringPlugin")}},jn=class extends er{static{i(this,"TelemetryPlugin")}};var Mn=class t{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=i(async e=>{let r=e.problem,n=JSON.stringify(r,null,2);return new Response(n,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})},"problemResponseFormat");static setProblemResponseFormat(e){e&&(y("runtime.problem-response-formatter"),t.problemResponseFormat=(r,n,o)=>{try{return e(r,n,o)}catch(s){throw new U("Error in custom 'problemResponseFormat'",{cause:s})}})}},yr=class{static{i(this,"ProblemResponseFormatter")}static async format(e,r,n){return await Mn.problemResponseFormat(e,r,n)}};function _i(t){for(let e in t){let r=t[e];r&&typeof r=="object"&&_i(r)}return Object.freeze(t)}i(_i,"deepFreeze");var ye=class t extends Request{static{i(this,"ZuploRequest")}#e=void 0;#t;constructor(e,r){super(e,r);let n=r?.params;n?this.#t=n:e instanceof t?this.#t=e.#t:this.#t={};let o=r?.user;o?this.user=o:e instanceof t&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},r=new URL(this.url).searchParams;for(let[n,o]of r.entries())e[n]=o;this.#e=e}return _i(this.#e)}get params(){return _i(this.#t)}user};var za={},Lt=[],Ca=[],Aa=[],Na=[],La=[];var Pi={addPlugin(t){Lt.push(t)},addRequestHook(t){Ca.push(t)},addResponseSendingHook(t){Aa.push(t)},addResponseSendingFinalHook(t){Na.push(t)},addPreRoutingHook(t){La.push(t)}},ah=i(async(t,e)=>{if(Ca.length===0)return t;let r=Si.getTracer("extension");return r.startActiveSpan("hook:onRequest",async n=>{try{let o=t;for(let s of Ca){let a=await r.startActiveSpan(s.name,async u=>{let c=await s(o,e);if(c instanceof ye||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:Ii.ERROR}),l}});if(a instanceof ye)o=a;else return a}return o}finally{n.end()}})},"invokeOnRequestExtensions"),uh=i(async(t,e,r)=>{if(Aa.length===0)return t;let n=Si.getTracer("extension");return n.startActiveSpan("hook:onResponseSending",async o=>{try{let s=t;for(let a of Aa)await n.startActiveSpan(a.name,async u=>{let c=await a(t,e,r);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:Ii.ERROR}),u.end(),l}});return s}finally{o.end()}})},"invokeOnResponseSendingExtensions"),ch=i(async(t,e,r)=>{if(Na.length===0)return;let n=Si.getTracer("extension");return n.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let s of Na)await n.startActiveSpan(s.name,async a=>{try{await s(t,e,r)}catch(u){throw a.recordException(u),a.setStatus({code:Ii.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),lh=i(async t=>{if(La.length===0)return t;let e=Si.getTracer("extension");return e.startActiveSpan("hook:preRouting",async r=>{try{let n=t;for(let o of La)n=await e.startActiveSpan(o.name,async a=>{try{let u=await o(n);if(u instanceof Request)return u;{let c=new U(`Invalid state - the PreRouting hook must return a Request. Received ${typeof u}.`);throw a.recordException(c),a.setStatus({code:Ii.ERROR}),c}}finally{a.end()}});return n}finally{r.end()}})},"invokePreRoutingHooks"),sh=!1;async function dh(t){if(!sh){t&&(y("runtime.extensions"),await t(Pi)),za.value=Pi;for(let e of Lt)if(e instanceof jn){let{requestHandlerProxy:r}=e.instrument({accountName:x.instance.build.ACCOUNT_NAME,projectName:x.instance.build.PROJECT_NAME,buildId:x.instance.build.BUILD_ID,zuploVersion:x.instance.build.ZUPLO_VERSION,compatibilityDate:x.instance.build.COMPATIBILITY_DATE,instanceId:x.instance.instanceId,environmentType:x.instance.loggingEnvironmentType,environmentStage:x.instance.loggingEnvironmentStage,deploymentName:x.instance.deploymentName});oh(r)}await Promise.all(Lt.map(async e=>{e instanceof Me&&await e.initialize(Pi)})),Mn.setProblemResponseFormat(Pi.problemResponseFormat),sh=!0}}i(dh,"initializeRuntime");var Da={Json:"application/json",Form:"application/x-www-form-urlencoded"};function Za(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(Da.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(Da.Json)||!e?JSON.stringify(t):t}i(Za,"serialize");function Jr(t){let{developerPortal:e}=Se.instance.runtimeSettings;return e.enabled&&e.basePath&&t.pathname.startsWith(e.basePath)||t.pathname.startsWith("/__zuplo/")||t.pathname.startsWith("/__/zuplo/")}i(Jr,"isSystemRoute");var ki=(O=>(O[O.CONTINUE=100]="CONTINUE",O[O.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",O[O.PROCESSING=102]="PROCESSING",O[O.EARLY_HINTS=103]="EARLY_HINTS",O[O.OK=200]="OK",O[O.CREATED=201]="CREATED",O[O.ACCEPTED=202]="ACCEPTED",O[O.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",O[O.NO_CONTENT=204]="NO_CONTENT",O[O.RESET_CONTENT=205]="RESET_CONTENT",O[O.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",O[O.MULTI_STATUS=207]="MULTI_STATUS",O[O.ALREADY_REPORTED=208]="ALREADY_REPORTED",O[O.IM_USED=226]="IM_USED",O[O.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",O[O.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",O[O.FOUND=302]="FOUND",O[O.SEE_OTHER=303]="SEE_OTHER",O[O.NOT_MODIFIED=304]="NOT_MODIFIED",O[O.USE_PROXY=305]="USE_PROXY",O[O.SWITCH_PROXY=306]="SWITCH_PROXY",O[O.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",O[O.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",O[O.BAD_REQUEST=400]="BAD_REQUEST",O[O.UNAUTHORIZED=401]="UNAUTHORIZED",O[O.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",O[O.FORBIDDEN=403]="FORBIDDEN",O[O.NOT_FOUND=404]="NOT_FOUND",O[O.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",O[O.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",O[O.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",O[O.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",O[O.CONFLICT=409]="CONFLICT",O[O.GONE=410]="GONE",O[O.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",O[O.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",O[O.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",O[O.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",O[O.URI_TOO_LONG=414]="URI_TOO_LONG",O[O.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",O[O.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",O[O.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",O[O.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",O[O.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",O[O.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",O[O.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",O[O.LOCKED=423]="LOCKED",O[O.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",O[O.TOO_EARLY=425]="TOO_EARLY",O[O.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",O[O.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",O[O.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",O[O.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",O[O.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",O[O.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",O[O.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",O[O.BAD_GATEWAY=502]="BAD_GATEWAY",O[O.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",O[O.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",O[O.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",O[O.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",O[O.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",O[O.LOOP_DETECTED=508]="LOOP_DETECTED",O[O.NOT_EXTENDED=510]="NOT_EXTENDED",O[O.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",O))(ki||{}),ph={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 mw={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"},Ua=mw;function fw(t){return`${new URL(t.url).pathname}`}i(fw,"instance");function hw(t,e){let r={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:x.instance.build.BUILD_ID},n=t.headers.get(Wr);return n&&(r.rayId=n),r}i(hw,"trace");var gw=i((t,e,r,n,o)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:fw(e),trace:hw(e,r),...n},additionalHeaders:o,statusText:Ua[t.status]}),"merge"),ja=class{static{i(this,"HttpProblemsBase")}static format=i((e,r,n)=>"problem"in e?yr.format(e,r,n):yr.format({problem:e},r,n),"format");static getProblemFromStatus(e,r){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:ph[e],...r}}},A=class extends ja{static{i(this,"HttpProblems")}static#e(e,r,n,o,s){let a=gw(this.getProblemFromStatus(e),r,n,o,s);return yr.format(a,r,n)}static continue=i((e,r,n,o)=>this.#e(200,e,r,n,o),"continue");static switchingProtocols=i((e,r,n,o)=>this.#e(101,e,r,n,o),"switchingProtocols");static processing=i((e,r,n,o)=>this.#e(102,e,r,n,o),"processing");static earlyHints=i((e,r,n,o)=>this.#e(103,e,r,n,o),"earlyHints");static ok=i((e,r,n,o)=>this.#e(200,e,r,n,o),"ok");static created=i((e,r,n,o)=>this.#e(201,e,r,n,o),"created");static accepted=i((e,r,n,o)=>this.#e(202,e,r,n,o),"accepted");static nonAuthoritativeInformation=i((e,r,n,o)=>this.#e(203,e,r,n,o),"nonAuthoritativeInformation");static noContent=i((e,r,n,o)=>this.#e(204,e,r,n,o),"noContent");static resetContent=i((e,r,n,o)=>this.#e(205,e,r,n,o),"resetContent");static partialContent=i((e,r,n,o)=>this.#e(206,e,r,n,o),"partialContent");static multiStatus=i((e,r,n,o)=>this.#e(207,e,r,n,o),"multiStatus");static alreadyReported=i((e,r,n,o)=>this.#e(208,e,r,n,o),"alreadyReported");static imUsed=i((e,r,n,o)=>this.#e(226,e,r,n,o),"imUsed");static multipleChoices=i((e,r,n,o)=>this.#e(300,e,r,n,o),"multipleChoices");static movedPermanently=i((e,r,n,o)=>this.#e(301,e,r,n,o),"movedPermanently");static found=i((e,r,n,o)=>this.#e(302,e,r,n,o),"found");static seeOther=i((e,r,n,o)=>this.#e(303,e,r,n,o),"seeOther");static notModified=i((e,r,n,o)=>this.#e(304,e,r,n,o),"notModified");static useProxy=i((e,r,n,o)=>this.#e(305,e,r,n,o),"useProxy");static switchProxy=i((e,r,n,o)=>this.#e(306,e,r,n,o),"switchProxy");static temporaryRedirect=i((e,r,n,o)=>this.#e(307,e,r,n,o),"temporaryRedirect");static permanentRedirect=i((e,r,n,o)=>this.#e(308,e,r,n,o),"permanentRedirect");static badRequest=i((e,r,n,o)=>this.#e(400,e,r,n,o),"badRequest");static unauthorized=i((e,r,n,o)=>this.#e(401,e,r,n,o),"unauthorized");static paymentRequired=i((e,r,n,o)=>this.#e(402,e,r,n,o),"paymentRequired");static forbidden=i((e,r,n,o)=>this.#e(403,e,r,n,o),"forbidden");static notFound=i((e,r,n,o)=>this.#e(404,e,r,n,o),"notFound");static methodNotAllowed=i((e,r,n,o)=>this.#e(405,e,r,n,o),"methodNotAllowed");static notAcceptable=i((e,r,n,o)=>this.#e(406,e,r,n,o),"notAcceptable");static proxyAuthenticationRequired=i((e,r,n,o)=>this.#e(407,e,r,n,o),"proxyAuthenticationRequired");static requestTimeout=i((e,r,n,o)=>this.#e(408,e,r,n,o),"requestTimeout");static conflict=i((e,r,n,o)=>this.#e(409,e,r,n,o),"conflict");static gone=i((e,r,n,o)=>this.#e(410,e,r,n,o),"gone");static lengthRequired=i((e,r,n,o)=>this.#e(411,e,r,n,o),"lengthRequired");static preconditionFailed=i((e,r,n,o)=>this.#e(412,e,r,n,o),"preconditionFailed");static contentTooLarge=i((e,r,n,o)=>this.#e(413,e,r,n,o),"contentTooLarge");static uriTooLong=i((e,r,n,o)=>this.#e(414,e,r,n,o),"uriTooLong");static unsupportedMediaType=i((e,r,n,o)=>this.#e(415,e,r,n,o),"unsupportedMediaType");static rangeNotSatisfiable=i((e,r,n,o)=>this.#e(416,e,r,n,o),"rangeNotSatisfiable");static expectationFailed=i((e,r,n,o)=>this.#e(417,e,r,n,o),"expectationFailed");static imATeapot=i((e,r,n,o)=>this.#e(418,e,r,n,o),"imATeapot");static misdirectedRequest=i((e,r,n,o)=>this.#e(421,e,r,n,o),"misdirectedRequest");static unprocessableContent=i((e,r,n,o)=>this.#e(422,e,r,n,o),"unprocessableContent");static locked=i((e,r,n,o)=>this.#e(423,e,r,n,o),"locked");static failedDependency=i((e,r,n,o)=>this.#e(424,e,r,n,o),"failedDependency");static tooEarly=i((e,r,n,o)=>this.#e(425,e,r,n,o),"tooEarly");static upgradeRequired=i((e,r,n,o)=>this.#e(426,e,r,n,o),"upgradeRequired");static preconditionRequired=i((e,r,n,o)=>this.#e(428,e,r,n,o),"preconditionRequired");static tooManyRequests=i((e,r,n,o)=>this.#e(429,e,r,n,o),"tooManyRequests");static requestHeaderFieldsTooLarge=i((e,r,n,o)=>this.#e(431,e,r,n,o),"requestHeaderFieldsTooLarge");static unavailableForLegalReasons=i((e,r,n,o)=>this.#e(451,e,r,n,o),"unavailableForLegalReasons");static internalServerError=i((e,r,n,o)=>this.#e(500,e,r,n,o),"internalServerError");static notImplemented=i((e,r,n,o)=>this.#e(501,e,r,n,o),"notImplemented");static badGateway=i((e,r,n,o)=>this.#e(502,e,r,n,o),"badGateway");static serviceUnavailable=i((e,r,n,o)=>this.#e(503,e,r,n,o),"serviceUnavailable");static gatewayTimeout=i((e,r,n,o)=>this.#e(504,e,r,n,o),"gatewayTimeout");static httpVersionNotSupported=i((e,r,n,o)=>this.#e(505,e,r,n,o),"httpVersionNotSupported");static variantAlsoNegotiates=i((e,r,n,o)=>this.#e(506,e,r,n,o),"variantAlsoNegotiates");static insufficientStorage=i((e,r,n,o)=>this.#e(507,e,r,n,o),"insufficientStorage");static loopDetected=i((e,r,n,o)=>this.#e(508,e,r,n,o),"loopDetected");static notExtended=i((e,r,n,o)=>this.#e(510,e,r,n,o),"notExtended");static networkAuthenticationRequired=i((e,r,n,o)=>this.#e(511,e,r,n,o),"networkAuthenticationRequired")};var{toString:yw}=Object.prototype,{propertyIsEnumerable:bw}=Object.prototype;function Ma(t){return yw.call(t)}i(Ma,"toString");function nt(t){return typeof t=="string"}i(nt,"isString");function Kr(t){return nt(t)&&t!==""}i(Kr,"isNonEmptyString");function mh(t){return Ma(t)==="[object RegExp]"}i(mh,"isRegexp");function fh(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>bw.call(t,e))]}i(fh,"getOwnEnumerableKeys");function br(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof RegExp)&&!(t instanceof Date)}i(br,"isObject");function qa(t){return typeof t=="number"&&!isNaN(t)}i(qa,"isNumber");function Ha(t){return t===!0||t===!1}i(Ha,"isBoolean");function hh(t){return typeof t>"u"}i(hh,"isUndefined");function gh(t){return hh(t)||t===null}i(gh,"isUndefinedOrNull");function qn(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}i(qn,"isErrorLike");var vw=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(t=>[t.name,t]),ww=new Map(vw);var xw=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],Fa=Symbol(".toJSON was called"),Rw=i(t=>{t[Fa]=!0;let e=t.toJSON();return delete t[Fa],e},"toJSON"),_w=i(t=>ww.get(t)??Error,"getErrorConstructor"),yh=i(({from:t,seen:e,to:r,forceEnumerable:n,maxDepth:o,depth:s,useToJSON:a,serialize:u})=>{if(!r)if(Array.isArray(t))r=[];else if(!u&&qn(t)){let l=_w(t.name);r=new l}else r={};if(e.push(t),s>=o)return r;if(a&&typeof t.toJSON=="function"&&t[Fa]!==!0)return Rw(t);let c=i(l=>yh({from:l,seen:[...e],forceEnumerable:n,maxDepth:o,depth:s,useToJSON:a,serialize:u}),"continueDestroyCircular");for(let[l,d]of Object.entries(t)){if(typeof Buffer=="function"&&Buffer.isBuffer(d)){r[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){r[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){r[l]=d;continue}if(!e.includes(t[l])){s++,r[l]=c(t[l]);continue}r[l]="[Circular]"}}for(let{property:l,enumerable:d}of xw)typeof t[l]<"u"&&t[l]!==null&&Object.defineProperty(r,l,{value:qn(t[l])?c(t[l]):t[l],enumerable:n?!0:d,configurable:!0,writable:!0});return r},"destroyCircular");function vr(t,e){let r=e?.maxDepth??Number.POSITIVE_INFINITY,n=e?.useToJSON??!0;return typeof t=="object"&&t!==null?yh({from:t,seen:[],forceEnumerable:!0,maxDepth:r,depth:0,useToJSON:n,serialize:!0}):typeof t=="function"?`[Function: ${t.name??"anonymous"}]`:t}i(vr,"serializeError");var Pw=/file:\/\/\/(.*?)\/dist\//g,Iw="at async Event.respondWith";function Ba(t){return typeof t!="string"?t:t.split(`
|
|
26
26
|
`).filter(e=>!e.trim().startsWith("at async file")).map((e,r)=>{let n=e.replaceAll(Pw,"").replaceAll(Iw,"").trim();return r===0||n.length===0?n:` ${n}`}).filter(e=>e.length>0).join(`
|
|
27
27
|
`)}i(Ba,"cleanStack");function _t(t,e,r,n){e.log.error(r,n);let o={};if(x.instance.isLocalDevelopment||x.instance.isWorkingCopy)if(n instanceof U&&n.extensionMembers)o=n.extensionMembers;else if(n.cause){let s=vr(n.cause);"stack"in s&&(s.stack=Ba(s.stack)),o={cause:s}}else{let s=vr(n);"stack"in s&&(s.stack=Ba(s.stack)),o={cause:s}}return A.internalServerError(t,e,{detail:n.message,...o})}i(_t,"errorHandler");var Ze=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=i(e=>async(r,n)=>kw.getTracer("pipeline").startActiveSpan(`handler:${n.route.handler.export}`,async s=>{try{return await e(r,n)}catch(a){let u=_t(r,n,"Error executing request handler.",a);return s.setStatus({code:Sw.ERROR}),u}finally{s.end()}}),"#errorWrappedHandler");#t=i(({processors:e,handler:r})=>async(n,o)=>{let s=Ve.getContextExtensions(o),a=[...e],u=i(async h=>{let v=a.pop();if(!v){let k=await this.#e(async I=>{let L=await r(I,o);return Ew(L)})(h,o);try{await s.onHandlerResponse(k,h,o)}catch(I){return _t(n,o,"Error invoking 'context.onHandlerResponse' hook",I)}return k}return v(n,o,u)},"nextPipe"),l=await u(n),d=new URL(n.url);if(Jr(d)&&x.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new Hn(n,l);o.dispatchEvent(p);let m=s.latestRequest,f;try{f=await p.mutableResponse}catch(h){return _t(n,o,"Error retrieving mutableResponse",h)}try{f=await s.onResponseSending(f,m,o)}catch(h){return _t(n,o,"Error invoking 'context.onResponseSending' hook",h)}try{f=await uh(f,m,o)}catch(h){return _t(n,o,"Error invoking 'context.onResponseSending' hook",h)}o.dispatchEvent(new Fn(n,f));try{await s.onResponseSendingFinal(l,m,o)}catch(h){throw o.log.error("Error invoking 'runtime.onResponseSending' hook",h),h}try{await ch(l,m,o)}catch(h){throw o.log.error("Error invoking 'runtime.onResponseSending' hook",h),h}return f},"#toZuploPipeline")};function Ew(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response(Za(t),{headers:{"content-type":"application/json"}})}i(Ew,"resultToResponse");var Pt=class extends er{static{i(this,"MetricsPlugin")}};var pe=class t{static{i(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let r=t.#e.get(e);if(!r){let n=`No system logger found for context with requestId '${e.requestId}'`;throw G.console.error(n),new xe(n)}return r}static addLogger(e,r){t.#e.set(e,r)}};var me=class{static{i(this,"BatchDispatch")}constructor(e,r,n,o){this.#t=e,this.#i=r,this.#r=n,this.#n=o??G.console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=i(e=>{this.#o.push(e),this.#e||(this.#e=new Promise(r=>{setTimeout(()=>{if(this.#o.length>0){let n=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(n).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{r()})}},this.#i)}))},"enqueue");waitUntilFlushed=i(async()=>{if(this.#e)return this.#e},"waitUntilFlushed")};var Ei=class{static{i(this,"ZuploMetricsTransport")}#e;#t;constructor(e){this.#e=e,this.#t=new me("zuplo-metrics-transport",10,this.dispatchFunction,pe.getLogger(e))}pushMetrics(e,r){this.#t.enqueue(e),r.waitUntil(this.#t.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let{remoteLogURL:r,deploymentName:n}=x.instance,{ACCOUNT_NAME:o,PROJECT_NAME:s}=x.instance.build,a=e.map(p=>{let m=Object.assign({},p);return delete m.requestContentLength,delete m.responseContentLength,m}),u=eh(),c={metadata:{timestamp:new Date,accountName:o,projectName:s,deploymentName:n},metrics:a,features:u},l=new Headers({"content-type":"application/json"});xt(l);let d=await G.fetch(`${r}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(c),headers:l});if(!d.ok){let p=await d.text();pe.getLogger(this.#e).error(`Metrics POST responded ${d.status}: ${d.statusText}`,p),th(u)}}catch(r){pe.getLogger(this.#e).error("Failed to send Zuplo metrics.",r)}},"dispatchFunction")};var Ue=class{static{i(this,"SystemRouteConfiguration")}constructor({label:e,path:r,methods:n,systemRouteName:o,corsPolicy:s="none"}){this.label=e,this.path=r,this.methods=n,this.corsPolicy=s,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;policies;systemRouteName;metadata;raw(){return{}}};var Va="x-real-ip",Tw="true-client-ip",$w="cf-connecting-ip",Ow="x-forwarded-for";function ct(t){let e=t.headers,r=e.get(Va)??e.get(Tw)??e.get($w);if(r)return r;let n=e.get(Ow);if(n){let o=n.split(/,\s*/).map(s=>s.trim()).find(s=>s.length>0);if(o)return o}}i(ct,"getClientIp");var Ge=i(async(t,e,r)=>{let n=new Date,o=Date.now(),s=await r(t),a=t.headers.get(Wr)??void 0,u=ct(t),c=e.incomingRequestProperties,l;e.route instanceof Ue&&(l=e.route.systemRouteName);let d=Ve.getContextExtensions(e).latestRequest,p={timestamp:n,statusCode:s.status,durationMs:Date.now()-o,requestContentLength:t.headers.get("content-length")?Number(t.headers.get("content-length")):void 0,responseContentLength:s.headers.get("content-length")?Number(s.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:l,contextId:e.contextId,parentContextId:e.parentContext?.contextId,requestId:e.requestId,parentRequestId:e.parentContext?.requestId,method:t.method,asn:c.asn,asOrganization:c.asOrganization,colo:c.colo,continent:c.continent,country:c.country,city:c.city,latitude:c.latitude,longitude:c.longitude,rayId:a,instanceId:x.instance.instanceId,userSub:d.user?.sub,clientIp:u},m=[];return!x.instance.isLocalDevelopment&&x.instance.remoteLogURL&&x.instance.remoteLogToken&&x.instance.loggingId&&m.push(new Ei(e)),Lt.forEach(f=>{if(f instanceof Pt){let h=f.getTransport();m.push(h)}}),m.forEach(f=>{f.pushMetrics(p,e)}),s},"metricsProcessor");var Ga=i(t=>{let e=i(async(o,s)=>{let a=new URL(o.url),u=x.instance.build,c={buildId:u.BUILD_ID,zuploVersion:u.ZUPLO_VERSION,compatibilityDate:u.COMPATIBILITY_DATE,apiVersion:u.API_VERSION,gitSha:u.GIT_SHA,timestamp:u.TIMESTAMP,isProduction:u.ENVIRONMENT_TYPE==="PRODUCTION"};if(a.searchParams.get("system_log")==="true"&&pe.getLogger(s).error("Test System Log",c),a.searchParams.get("error")==="true")throw new Error("this is an unhandled error");return new Response(JSON.stringify(c,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new Ze({processors:[Ge],handler:e}),n=new Ue({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});t.addRoute(n,r.execute)},"registerBuildRoute");var bh=new Map;function It(t){if(Array.isArray(t)&&!t.some(o=>typeof o!="number"))return t;if(typeof t!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(t))throw new g("Malformed input string");let e=bh.get(t);if(e)return e;let r=t.split(","),n=[];for(let o of r){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++)n.push(c)}else n.push(parseInt(o,10))}return bh.set(t,n),n}i(It,"statusCodesStringToNumberArray");function zt(t,e,r){if(!e.startsWith("."))throw new g(`Invalid ${r} - must start with '.' - '${e}' does not`);let n=e.split(".").splice(1),o=t;return n.forEach(s=>{if(o===void 0)throw new U(`Error applying ${r} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i(zt,"getValueFromRequestUser");function vh(t,e){if(!e.startsWith("."))throw new g(`Invalid selector. must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),n=t;return r.forEach(o=>{if(n===void 0)throw new U(`Error applying'${e}', reading '${o}'`);if(n&&typeof n=="object")n=Reflect.get(n,o);else throw new U(`Error applying'${e}', reading '${o}'`)}),`${n}`}i(vh,"selectPropertyUsingJsonPath");function Dt(t){if(Array.isArray(t)){if(t.includes(r=>typeof r!="string"))throw new g("Received an array that contains non-string values.");return t}if(nt(t))return t.includes(",")?t.split(",").map(r=>r.trim()).filter(r=>r!==","&&r!==""):[t];throw new g(`Expected type of string, received type '${typeof t}'`)}i(Dt,"parseValueToStringArray");function wh(t){if(t==null)return[];if(!Array.isArray(t))throw new g(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof t}'`);return t.map(r=>{if(!br(r))throw new g(`Invalid custom cors policy is set. Expected an object, received '${typeof r}'`);if(!Kr(r.name))throw new g("Value of 'name' on custom cors policies must be a non-empty string.");if(r.maxAge!==void 0&&!qa(r.maxAge))throw new g(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof r.maxAge}'`);if(r.allowCredentials!==void 0&&!Ha(r.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 n=Wa(r,"allowedHeaders"),o=Wa(r,"allowedMethods"),s=Wa(r,"exposeHeaders"),a;try{a=Dt(r.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:r.name,allowCredentials:typeof r.allowCredentials=="boolean"?String(r.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:n?n.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:s?s.join(", "):void 0,maxAge:typeof r.maxAge=="number"?r.maxAge.toString():void 0}})}i(wh,"parseCorsPolicies");function Wa(t,e){let r;if(t[e]!==void 0)try{r=Dt(t[e])}catch(n){throw new g(`Value of '${e}' on custom cors policies is invalid. ${n.message} If using an environment variable, check that it is set correctly.`)}return r}i(Wa,"parseOptionalProperty");var Ti=i((t,e)=>{if(e===null)return;if(t.find(a=>a==="*"))return e;let n=t.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return n.find(a=>a===o)},"findMatchingOrigin"),$i=i((t,e)=>{let r={"access-control-allow-origin":e};t.allowedHeaders&&(r["access-control-allow-headers"]=t.allowedHeaders),t.allowedMethods&&(r["access-control-allow-methods"]=t.allowedMethods),t.exposeHeaders&&(r["access-control-expose-headers"]=t.exposeHeaders);let n=t.allowCredentials;n&&(r["access-control-allow-credentials"]=n);let o=t.maxAge?.toString()??void 0;return o&&(r["access-control-max-age"]=o),r},"generateCorsHeaders"),Oi=i((t,e)=>{if(!t)return!1;let{developerPortal:r}=e;return r.enabled&&r.type==="zudoku"&&r.urls?r.urls.urls.includes(t):!1},"isDevPortalOrigin");var Ja=i((t,e,r)=>{let n=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 A.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});if(Oi(p,e)){let v={"access-control-allow-origin":p,"access-control-allow-methods":l,"access-control-allow-headers":d??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"};return new Response(void 0,{status:200,statusText:"OK",headers:v})}let m=t.lookup(c,l);if(!m)return A.notFound(a,u);let f=m.routeConfiguration,h=Cw({requestedMethod:l,requestedHeaders:d,requestedOrigin:p,routeConfig:f,customPolicies:r});return h.isValid?new Response(void 0,{status:200,statusText:"OK",headers:h.headers}):(h.error&&u.log.warn(h.error),A.notFound(a,u))},"optionsHandler"),o=new Ze({processors:[Ge],handler:n}),s=new Ue({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});t.addRoute(s,o.execute)},"registerCorsRoute"),Cw=i(({requestedMethod:t,requestedHeaders:e,requestedOrigin:r,routeConfig:n,customPolicies:o})=>{let s={isValid:!1,headers:{}};if(n.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":r,"access-control-allow-methods":t,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(n.corsPolicy==="none")return{...s,error:`No CORS policy set for the route '${n.pathPattern}'`};let a=o?.find(l=>l.name===n.corsPolicy);if(!a)throw new g(`Invalid Configuration - corsPolicy '${n.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=Ti(a.allowedOrigins,r);return u?{isValid:!0,headers:$i(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${r}'`}},"validateAndBuildResponseHeaders");var xh=i(t=>{let e=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new Ze({processors:[Ge],handler:e}),n=new Ue({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});t.addRoute(n,r.execute)},"registerNoRoutes");var tr=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.mcp=e.mcp,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,this.metadata=e.metadata,this.raw=e.raw}raw;get summary(){return this.raw()?.summary}get operationId(){return this.raw()?.operationId}get tags(){return this.raw()?.tags}get parameters(){return this.raw()?.parameters}get responses(){return this.raw()?.responses}label;key;path;excludeFromOpenApi;pathPattern;metadata;custom;mcp;methods;handler;corsPolicy;policies};var Aw=new Ue({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Rh=i(t=>{let e=i(async(n,o)=>{let s=za.value?.notFoundHandler;if(s){let a=new URL(n.url);return s(n,o,{get routesMatchedByPathOnly(){return t.lookupByPathOnly(a.pathname).map(c=>c.routeConfiguration).filter(c=>c instanceof tr)}})}return A.notFound(n,o)},"notFoundHandler"),r=new Ze({processors:[Ge],handler:e});t.addRoute(Aw,r.execute)},"registerNotMatchedHandler");var Nw=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],_h=i(t=>{Nw.forEach(e=>t.delete(e))},"stripCorsHeaders"),Ci=i(async(t,e,r)=>{let n=e.route,o=t.headers.get("origin"),s=Oi(o,Se.instance.runtimeSettings);if((!n.corsPolicy||n.corsPolicy==="none")&&!s){let p=await r(t),m=new Headers(p.headers);return _h(m),new Response(p.body,{status:p.status,statusText:p.statusText,headers:m,webSocket:p.webSocket})}let a=await r(t);if(!(a instanceof Response))throw new xe(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof a}'`);let u=Lw(n,Se.instance.routeData.corsPolicies,s),c=zw(o,u),l=new Headers(a.headers);return _h(l),Object.entries(c).forEach(([p,m])=>{l.set(p,m)}),new Response(a.body,{status:a.status,statusText:a.statusText,headers:l,webSocket:a.webSocket})},"corsProcessor"),Lw=i((t,e,r)=>{if(t.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:t.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};if(r)return{name:"dev-portal-anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:t.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let n=e?.find(o=>o.name===t.corsPolicy);if(n===void 0)throw new g(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return n},"getCorsPolicy"),zw=i((t,e)=>{let r=Ti(e.allowedOrigins,t);return r?$i(e,r):{}},"getCorsHeaders");var Ka=i(t=>{let e=i(async()=>new Response(JSON.stringify({buildId:x.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new Ze({processors:[Ci],handler:e}),n=new Ue({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});t.addRoute(n,r.execute)},"registerPingRoute");import{SpanStatusCode as Ph,trace as Ih}from"@opentelemetry/api";var Zt={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 Ai=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,r){if(!nt(r))throw new U(`The name of a policy must be a string. Received '${r}' of type '${typeof r}'`);this.options=e,this.policyName=r,this.policyType=Object.getPrototypeOf(this).constructor.name}},Ne=class extends Ai{static{i(this,"InboundPolicy")}},rr=class extends Ai{static{i(this,"OutboundPolicy")}};var Ya=class extends Ne{static{i(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,r,n){super(r,n),this.policyType=e.name,this.#e=e}handler(e,r){return this.#e(e,r,this.options,this.policyName)}},eu=class extends rr{static{i(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,r,n){super(r,n),this.policyType=e.name,this.#e=e}handler(e,r,n){return this.#e(e,r,n,this.options,this.policyName)}},Qa=new Map;function Bn(t,e){let r,n;return Array.isArray(t)?r=t:(r=t.policies?.inbound??[],n=t.path),r.filter(s=>!Qa.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}' ${n&&`on route '${n}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new g(`Invalid state - invalid policy '${s}' on route '${n}' (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 '${n}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new g(`Invalid state - invalid policy '${s}' on route '${n}' (typeof module '${typeof u}')`);if(u.prototype instanceof Ne)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new Ya(u,a.handler.options,a.name);else throw new g(`Invalid state - invalid policy '${s}' on route '${n}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new g(`Invalid state - invalid handler on policy '${s}' on route '${n}' (typeof handler '${typeof c.handler}')`);Qa.set(a.name,c)}),r.map(s=>{let a=Qa.get(s);if(a===void 0)throw new U("Internal error. Policy not found in cache.");return a})}i(Bn,"getInboundPolicyInstances");var Xa=new Map;function Vn(t,e){let r,n;return Array.isArray(t)?r=t:(r=t.policies?.outbound??[],n=t.path),r.filter(s=>!Xa.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 '${n}' was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new g(`Invalid state - invalid policy '${s}' on route '${n}' (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 '${n}' (typeof module '${typeof u}')`);if(u.prototype instanceof rr)c=new u(a.handler.options??{},a.name);else if(typeof u=="function")c=new eu(u,a.handler.options??{},a.name);else throw new g(`Invalid state - invalid policy '${s}' on route '${n}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new g(`Invalid state - invalid handler on policy '${s}' on route '${n}'`);Xa.set(a.name,c)}),r.map(s=>{let a=Xa.get(s);if(a===void 0)throw new U("Internal error. Policy not found in cache.");return a})}i(Vn,"getOutboundPolicyInstances");var tu=i(t=>async(e,r)=>{let n=Ve.getContextExtensions(r),o=Ih.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async s=>{try{let a=[...t],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,r);if(p instanceof Request||p instanceof ye||p instanceof Response)return d.end(),p instanceof Response||p instanceof ye?p:new ye(p);{let m=new g(`Invalid state - invalid handler on policy '${c.policyName}' on route '${r.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:Ph.ERROR}),d.recordException(m),m}});if(l instanceof ye)u=l;else if(l instanceof Request)u=new ye(l);else if(l instanceof Response)return l;n.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),ru=i(t=>async(e,r,n)=>{let o=Ih.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async s=>{try{let a=[...t],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(Zt.PolicyName,c.policyName),d.setAttribute(Zt.PolicyType,c.policyType);let p=await c.handler(u,r,n);if(p instanceof Response)return p;{let m=new g(`Invalid state - invalid handler on policy '${c.policyName}' on route '${n.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:Ph.ERROR}),d.recordException(m),m}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),Ni=i(async(t,e,r)=>{let n=Bn(e.route,Se.instance.routeData.policies),o=Vn(e.route,Se.instance.routeData.policies);return kh({request:t,context:e,inboundPolicies:n,outboundPolicies:o,next:r})},"policyProcessor");function Sh({inboundPolicies:t=[],outboundPolicies:e=[]}){return i(async(n,o,s)=>kh({request:n,context:o,inboundPolicies:t,outboundPolicies:e,next:s}),"policyProcessor")}i(Sh,"createInternalPolicyProcessor");async function kh({request:t,context:e,inboundPolicies:r,outboundPolicies:n,next:o}){let s=tu(r);try{let a=await s(t,e);if(a instanceof Response)return a;let u=await o(a),c=ru(n),l;return x.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?l=c(u,t,e):l=u.ok?c(u,t,e):u,l}catch(a){return _t(t,e,"Error executing policies",a)}}i(kh,"executePolicyProcessor");var Oh=uw($h(),1);function Ch(t,e){try{let r=/v\d+(-\d+)?/g,o=(0,Oh.parse)(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&r.test(o)?`https://dev-portal-${o}.zuplo.com`:t}catch{}return t}i(Ch,"devPortalBaseURL");var Ah="/__zuplo/dev-portal",Gw="dev-portal-id",Ww="dev-portal-host",Jw="zp-account",Kw="zp-project",Qw="dev-portal-build",Xw=`
|
|
28
28
|
<!DOCTYPE html>
|
|
@@ -22,4 +22,4 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
import{b as e,c as t,e as a,f as o,g as r,h as i,i as n}from"../chunk-
|
|
25
|
+
import{b as e,c as t,e as a,f as o,g as r,h as i,i as n}from"../chunk-SEPHSKCD.js";import"../chunk-DJ47NX57.js";export{o as getIdForParameterSchema,i as getIdForRefSchema,r as getIdForRequestBodySchema,a as getRawOperationDataIdentifierName,e as isRestrictedEnvVariableName,t as isZuploReadableEnvVariableName,n as sanitizedIdentifierName};
|
package/out/esm/mocks/index.js
CHANGED
|
@@ -22,4 +22,4 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
import{X as n,a as t}from"../chunk-
|
|
25
|
+
import{X as n,a as t}from"../chunk-DJ47NX57.js";function m(u={request:new Request("https://api.example.com")}){let e=[];function o(i){e.push(Promise.resolve(i))}return t(o,"waitUntil"),{context:new s({event:{waitUntil:o},route:u.route}),invokeResponse:t(async()=>{await Promise.all(e)},"invokeResponse")}}t(m,"createMockContext");var l={path:"/",methods:["GET"],handler:{module:{},export:"default"},raw:t(()=>({}),"raw")},s=class extends EventTarget{static{t(this,"MockZuploContext")}#e;contextId;requestId;log;route;custom;incomingRequestProperties;parentContext;constructor({event:e,route:o=l,parentContext:r}){super(),this.requestId=crypto.randomUUID(),this.contextId=crypto.randomUUID(),this.log={info:n.console.info,log:n.console.log,debug:n.console.debug,warn:n.console.warn,error:n.console.error},this.custom={},this.route=o,this.incomingRequestProperties={asn:1234,asOrganization:"ORGANIZATION",city:"Seattle",region:"Washington",regionCode:"WA",colo:"SEA",continent:"NA",country:"US",postalCode:"98004",metroCode:"SEA",latitude:void 0,longitude:void 0,timezone:void 0,httpProtocol:void 0},this.parentContext=r,this.#e=e}waitUntil(e){this.#e.waitUntil(e)}invokeInboundPolicy(e,o){throw new Error("Not implemented")}invokeOutboundPolicy(e,o,r){throw new Error("Not implemented")}invokeRoute(e,o){throw new Error("Not implemented")}addResponseSendingHook(e){throw new Error("Not implemented")}addResponseSendingFinalHook(e){throw new Error("Not implemented")}addEventListener(e,o,r){let d=t(i=>{try{typeof o=="function"?o(i):o.handleEvent(i)}catch(p){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),p}},"wrapped");super.addEventListener(e,d,r)}};export{s as MockZuploContext,m as createMockContext};
|
package/package.json
CHANGED
|
File without changes
|