@zuplo/cli 7.11.6 → 7.11.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/node_modules/@zuplo/core/package.json +1 -1
  2. package/node_modules/@zuplo/core/zeno.js +5 -4
  3. package/node_modules/@zuplo/graphql/package.json +1 -1
  4. package/node_modules/@zuplo/openapi-tools/package.json +1 -1
  5. package/node_modules/@zuplo/otel/package.json +1 -1
  6. package/node_modules/@zuplo/runtime/out/esm/{chunk-5SHD5VGF.js → chunk-7WJVPTYD.js} +3 -3
  7. package/node_modules/@zuplo/runtime/out/esm/chunk-7WJVPTYD.js.map +1 -0
  8. package/node_modules/@zuplo/runtime/out/esm/index.js +1 -1
  9. package/node_modules/@zuplo/runtime/out/esm/mcp-gateway/index.js +1 -1
  10. package/node_modules/@zuplo/runtime/out/esm/mocks/index.js +1 -1
  11. package/node_modules/@zuplo/runtime/out/esm/mocks/index.js.map +1 -1
  12. package/node_modules/@zuplo/runtime/out/types/index.d.ts +18 -43
  13. package/node_modules/@zuplo/runtime/out/types/internal/index.d.ts +17 -42
  14. package/node_modules/@zuplo/runtime/out/types/mcp/messages/index.d.ts +17 -42
  15. package/node_modules/@zuplo/runtime/out/types/mcp-gateway/index.d.ts +17 -42
  16. package/node_modules/@zuplo/runtime/out/types/mocks/index.d.ts +17 -42
  17. package/node_modules/@zuplo/runtime/out/types/sdks/aws/index.d.ts +17 -42
  18. package/node_modules/@zuplo/runtime/package.json +1 -1
  19. package/node_modules/qs/.github/THREAT_MODEL.md +4 -2
  20. package/node_modules/qs/CHANGELOG.md +38 -14
  21. package/node_modules/qs/README.md +31 -3
  22. package/node_modules/qs/dist/qs.js +20 -20
  23. package/node_modules/qs/lib/parse.js +94 -4
  24. package/node_modules/qs/lib/stringify.js +4 -4
  25. package/node_modules/qs/lib/utils.js +130 -6
  26. package/node_modules/qs/package.json +4 -4
  27. package/node_modules/qs/test/parse.js +174 -0
  28. package/node_modules/qs/test/stringify.js +263 -33
  29. package/node_modules/qs/test/utils.js +184 -0
  30. package/package.json +11 -11
  31. package/node_modules/@zuplo/runtime/out/esm/chunk-5SHD5VGF.js.map +0 -1
  32. /package/node_modules/@zuplo/runtime/out/esm/{chunk-5SHD5VGF.js.LEGAL.txt → chunk-7WJVPTYD.js.LEGAL.txt} +0 -0
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zuplo/core",
3
- "version": "7.11.6",
3
+ "version": "7.11.8",
4
4
  "repository": "https://github.com/zuplo/zuplo",
5
5
  "author": "Zuplo, Inc.",
6
6
  "type": "module",
@@ -22,7 +22,8 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- var Ue=Object.defineProperty;var n=(t,e)=>Ue(t,"name",{value:e,configurable:!0});import{scheduler as Ge}from"node:timers/promises";Object.defineProperty(globalThis,"scheduler",{value:Ge,writable:!1,enumerable:!0,configurable:!1});function q(t){let e=0;for(let s of t)e+=s.length;let r=new Uint8Array(e),o=0;for(let s of t)r.set(s,o),o+=s.length;return r}n(q,"concat");var $=new TextEncoder,se=new TextDecoder,$e=42,We=124,je=40,ze=33,Ve=35,Ke=36,Je=44,Xe=45,Ze=58,qe=37,Ye=95,Qe=62,et=126,tt=43,rt=61,J=$.encode(`\r
26
- `),nt=$.encode("*"),ot=$.encode("$");function oe(t){let e=[nt,$.encode(t.length.toString()),J];for(let r of t){let o=r instanceof Uint8Array?r:$.encode(r.toString());e.push(ot,$.encode(o.byteLength.toString()),J,o,J)}return q(e)}n(oe,"createRequest");async function*st(t){let e=new Uint8Array;for await(let r of t){e=q([e,r]);let o;for(;(o=e.indexOf(J[0]))!==-1&&e[o+1]===J[1];)yield e.subarray(0,o),e=e.subarray(o+2)}}n(st,"readLines");function K(t,e,r=!1){return Array.fromAsync({length:e},()=>X(t,r))}n(K,"readNReplies");function v(t){return se.decode(t.slice(1))}n(v,"parseLine");function it(t){let e=[];for(let r=0;r<t.length;r+=2)e.push(t.slice(r,r+2));return e}n(it,"chunk");async function X(t,e=!1){let{value:r}=await t.next();switch(r[0]){case $e:case Qe:{let o=Number(v(r));return o===-1?null:await K(t,o)}case We:{let o=Number(v(r))*2;return await K(t,o),X(t,e)}case je:return BigInt(v(r));case ze:{let{value:o}=await t.next();return Promise.reject(se.decode(o))}case Ve:return v(r)==="t";case Ke:case rt:return v(r)==="-1"?null:X(t,e);case Je:case Ze:switch(v(r)){case"inf":return 1/0;case"-inf":return-1/0;default:return Number(v(r))}case Xe:return Promise.reject(v(r));case qe:{let o=Number(v(r))*2,s=await K(t,o);return Object.fromEntries(it(s))}case Ye:return null;case et:return new Set(await K(t,Number(v(r)),e));case tt:return v(r);default:return e?r:se.decode(r)}}n(X,"readReply");var Y=class{static{n(this,"RedisClient")}#t;#n;#e=Promise.resolve();constructor(e){this.#t=e.writable.getWriter(),this.#n=st(e.readable)}#r(e){return this.#e=this.#e.then(e),this.#e}sendCommand(e,r=!1){return this.#r(()=>(this.#t.write(oe(e)),X(this.#n,r)))}writeCommand(e){return this.#r(()=>this.#t.write(oe(e)))}async*readReplies(e=!1){for(;;)yield X(this.#n,e)}pipelineCommands(e,r=!1){return this.#r(()=>{let o=q(e.map(oe));return this.#t.write(o),K(this.#n,e.length,r)})}};var R=globalThis.Deno?.build.os==="windows"||globalThis.navigator?.platform?.startsWith("Win")||globalThis.process?.platform?.startsWith("win")||!1;function E(t){if(typeof t!="string")throw new TypeError(`Path must be a string, received "${JSON.stringify(t)}"`)}n(E,"assertPath");function k(t){return t===47}n(k,"isPosixPathSeparator");function b(t){return t===47||t===92}n(b,"isPathSeparator");function B(t){return t>=97&&t<=122||t>=65&&t<=90}n(B,"isWindowsDeviceRoot");function ee(t){if(E(t),t.length===0)return"."}n(ee,"assertArg");function W(t,e,r,o){let s="",a=0,f=-1,c=0,u;for(let i=0;i<=t.length;++i){if(i<t.length)u=t.charCodeAt(i);else{if(o(u))break;u=47}if(o(u)){if(!(f===i-1||c===1))if(f!==i-1&&c===2){if(s.length<2||a!==2||s.charCodeAt(s.length-1)!==46||s.charCodeAt(s.length-2)!==46){if(s.length>2){let p=s.lastIndexOf(r);p===-1?(s="",a=0):(s=s.slice(0,p),a=s.length-1-s.lastIndexOf(r)),f=i,c=0;continue}else if(s.length===2||s.length===1){s="",a=0,f=i,c=0;continue}}e&&(s.length>0?s+=`${r}..`:s="..",a=2)}else s.length>0?s+=r+t.slice(f+1,i):s=t.slice(f+1,i),a=i-f-1;f=i,c=0}else u===46&&c!==-1?++c:c=-1}return s}n(W,"normalizeString");function te(t){ee(t);let e=k(t.charCodeAt(0)),r=k(t.charCodeAt(t.length-1));return t=W(t,!e,"/",k),t.length===0&&!e&&(t="."),t.length>0&&r&&(t+="/"),e?`/${t}`:t}n(te,"normalize");function ae(...t){if(t.length===0)return".";t.forEach(r=>E(r));let e=t.filter(r=>r.length>0).join("/");return e===""?".":te(e)}n(ae,"join");function re(t){ee(t);let e=t.length,r=0,o,s=!1,a=t.charCodeAt(0);if(e>1)if(b(a))if(s=!0,b(t.charCodeAt(1))){let c=2,u=c;for(;c<e&&!b(t.charCodeAt(c));++c);if(c<e&&c!==u){let i=t.slice(u,c);for(u=c;c<e&&b(t.charCodeAt(c));++c);if(c<e&&c!==u){for(u=c;c<e&&!b(t.charCodeAt(c));++c);if(c===e)return`\\\\${i}\\${t.slice(u)}\\`;c!==u&&(o=`\\\\${i}\\${t.slice(u,c)}`,r=c)}}}else r=1;else B(a)&&t.charCodeAt(1)===58&&(o=t.slice(0,2),r=2,e>2&&b(t.charCodeAt(2))&&(s=!0,r=3));else if(b(a))return"\\";let f;return r<e?f=W(t.slice(r),!s,"\\",b):f="",f.length===0&&!s&&(f="."),f.length>0&&b(t.charCodeAt(e-1))&&(f+="\\"),o===void 0?s?f.length>0?`\\${f}`:"\\":f:s?f.length>0?`${o}\\${f}`:`${o}\\`:o+f}n(re,"normalize");function le(...t){if(t.forEach(a=>E(a)),t=t.filter(a=>a.length>0),t.length===0)return".";let e=!0,r=0,o=t[0];if(b(o.charCodeAt(0))){++r;let a=o.length;a>1&&b(o.charCodeAt(1))&&(++r,a>2&&(b(o.charCodeAt(2))?++r:e=!1))}let s=t.join("\\");if(e){for(;r<s.length&&b(s.charCodeAt(r));++r);r>=2&&(s=`\\${s.slice(r)}`)}return re(s)}n(le,"join");function N(...t){return R?le(...t):ae(...t)}n(N,"join");function St(t){if(t.length>=255)throw new TypeError("Alphabet too long");let e=new Uint8Array(256);for(let i=0;i<e.length;i++)e[i]=255;for(let i=0;i<t.length;i++){let p=t.charAt(i),g=p.charCodeAt(0);if(e[g]!==255)throw new TypeError(p+" is ambiguous");e[g]=i}let r=t.length,o=t.charAt(0),s=Math.log(r)/Math.log(256),a=Math.log(256)/Math.log(r);function f(i){if(i instanceof Uint8Array||(ArrayBuffer.isView(i)?i=new Uint8Array(i.buffer,i.byteOffset,i.byteLength):Array.isArray(i)&&(i=Uint8Array.from(i))),!(i instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(i.length===0)return"";let p=0,g=0,y=0,x=i.length;for(;y!==x&&i[y]===0;)y++,p++;let w=(x-y)*a+1>>>0,S=new Uint8Array(w);for(;y!==x;){let T=i[y],_=0;for(let D=w-1;(T!==0||_<g)&&D!==-1;D--,_++)T+=256*S[D]>>>0,S[D]=T%r>>>0,T=T/r>>>0;if(T!==0)throw new Error("Non-zero carry");g=_,y++}let P=w-g;for(;P!==w&&S[P]===0;)P++;let C=o.repeat(p);for(;P<w;++P)C+=t.charAt(S[P]);return C}n(f,"encode");function c(i){if(typeof i!="string")throw new TypeError("Expected String");if(i.length===0)return new Uint8Array;let p=0,g=0,y=0;for(;i[p]===o;)g++,p++;let x=(i.length-p)*s+1>>>0,w=new Uint8Array(x);for(;p<i.length;){let T=i.charCodeAt(p);if(T>255)return;let _=e[T];if(_===255)return;let D=0;for(let d=x-1;(_!==0||D<y)&&d!==-1;d--,D++)_+=r*w[d]>>>0,w[d]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");y=D,p++}let S=x-y;for(;S!==x&&w[S]===0;)S++;let P=new Uint8Array(g+(x-S)),C=g;for(;S!==x;)P[C++]=w[S++];return P}n(c,"decodeUnsafe");function u(i){let p=c(i);if(p)return p;throw new Error("Non-base"+r+" character")}return n(u,"decode"),{encode:f,decodeUnsafe:c,decode:u}}n(St,"base");var Te=St;var _t="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",be=Te(_t);import{pathToFileURL as xe}from"node:url";import Ce from"dotenv";var ce=class{static{n(this,"ZenoLogger")}prefix="[ZENO]:";logLevel;originalConsole={debug:console.debug,info:console.info,warn:console.warn,error:console.error};constructor(e="info"){this.logLevel=e}debug(...e){(this.shouldLog("debug")||Deno.env.get("ZENO_DEBUG"))&&this.originalConsole.debug(this.prefix,"[DEBUG]",...e)}info(...e){this.shouldLog("info")&&this.originalConsole.info(this.prefix,"[INFO]",...e)}warn(...e){this.shouldLog("warn")&&this.originalConsole.warn(this.prefix,"[WARN]",...e)}error(...e){this.shouldLog("error")&&this.originalConsole.error(this.prefix,"[ERROR]",...e)}shouldLog(e){let r=["debug","info","warn","error"],o=r.indexOf(this.logLevel);return r.indexOf(e)>=o}setLogLevel(e){this.logLevel=e}},A=new ce;async function Re(t){let e={};for(let[r,o]of Object.entries(Deno.env.toObject()))o!==void 0&&(e[r]=o);try{let r=N(t,".env.zuplo"),o=new TextDecoder("utf-8"),s=await Deno.readFile(xe(r)),a=o.decode(s),f=Ce.parse(a);for(let[c,u]of Object.entries(f))if(e[c]=u,c==="ZUPLO_SYSTEM_CONFIGURATIONS")try{let i=new TextDecoder().decode(be.decode(u)),p=JSON.parse(i);for(let[g,y]of Object.entries(p))e[g]=String(y)}catch(i){Deno.build.standalone||A.error("Failed to parse ZUPLO_SYSTEM_CONFIGURATIONS from .env.zuplo:",i)}}catch(r){r instanceof Deno.errors.NotFound||A.error("Failed to load .env.zuplo file:",r)}try{let r=N(t,".env"),o=new TextDecoder("utf-8"),s=await Deno.readFile(xe(r)),a=o.decode(s),f=Ce.parse(a);for(let[c,u]of Object.entries(f))e[c]=u}catch(r){r instanceof Deno.errors.NotFound||A.error("Failed to load .env.zuplo file:",r)}for(let[r,o]of Object.entries(e))o===void 0&&delete e[r];return e.__ZUPLO_IS_MANAGED_DEDICATED="true",e}n(Re,"loadEnvironment");function Ee(t){return t?["true","1","yes","y"].includes(t.toLowerCase()):!1}n(Ee,"parseEnvBool");var fe=class{static{n(this,"CacheStorage")}#t;constructor(){this.#t=new Map}async open(e){let r=this.#t.get(e);return r||(r=new de,this.#t.set(e,r)),r}async has(e){return this.#t.has(e)}async delete(e){throw new Error("caches.delete is not supported")}};async function Nt(){let t=Deno.env.get("ZUPLO_CACHE_REDIS_HOSTNAME");if(t===void 0)throw new Error("ZUPLO_CACHE_REDIS_HOSTNAME is not set");let e=parseInt(Deno.env.get("ZUPLO_CACHE_REDIS_PORT")||"6379"),r=await Deno.connect({hostname:t,port:e});return new Y(r)}n(Nt,"getRedisClient");function Pt(t){let e={};return t&&t.split(",").forEach(o=>{let[s,a]=o.trim().split("=");e[s.toLowerCase()]=a?a.trim():!0}),e}n(Pt,"parseHeaderValue");function Dt(t){let e={};for(let[r,o]of t.entries())e[r]=o;return e}n(Dt,"objectifyHeaders");async function Ot(t){let e=await t.arrayBuffer(),r=new Uint8Array(e),o="";for(let s=0;s<r.length;s++)o+=String.fromCharCode(r[s]);return btoa(o)}n(Ot,"serializeResponseBody");function vt(t){let e=atob(t),r=e.length,o=new Uint8Array(r);for(let s=0;s<r;s++)o[s]=e.charCodeAt(s);return o}n(vt,"deserializeResponseBody");var de=class{static{n(this,"Cache")}#t;#n;#e;constructor(e="default",r={}){this.#t=e;let o=Deno.env.get("ZUPLO_CACHE_REDIS_HOSTNAME")&&Deno.env.get("ZUPLO_CACHE_REDIS_PORT");this.#n=!o||!Ee(Deno.env.get("USE_ZENO_ZONE_CACHE")),this.#e=r.getRedisClient||Nt}#r(e){return`${this.#t}:${e.url}`}async match(e,r){if(this.#n)return;let o=this.#r(e),s=await this.#e();await s.sendCommand(["HELLO",3]);let a=await s.sendCommand(["TTL",o]);if(a!==-2){if(a<2)return;{let f=await s.sendCommand(["HGETALL",o]),c=f.status,u=f.status,i=new Headers(JSON.parse(f.headers));return new Response(vt(f.body),{status:c,statusText:u,headers:i})}}}async put(e,r){if(this.#n)return;let o=1*60*60,s=Pt(r.headers.get("cache-control")),a=parseInt(s["s-maxage"]),f=parseInt(s["max-age"]),c=s["no-store"],u=s["no-cache"],i=a||f||0;if(i===0&&!c&&!u&&(i=o,r.headers.append("cache-control",`s-maxage=${o}`)),i>0){let p=this.#r(e),g=await this.#e();await g.sendCommand(["HELLO",3]),await g.sendCommand(["HSET",p,"maxage",i,"status",r.status,"statusText",r.statusText,"headers",JSON.stringify(Dt(r.headers)),"body",await Ot(r)]),await g.sendCommand(["EXPIRE",p,i])}}async delete(e){if(this.#n)return;let r=this.#r(e);if(await(await this.#e()).sendCommand(["DEL",r])!==1)throw new Error("Failed to delete cache entry")}},kt=new fe;Object.defineProperty(globalThis,"caches",{value:kt,writable:!1,enumerable:!0,configurable:!1});var ne=class{static{n(this,"WorkerServer")}#t;#n;#e;#r=n(()=>({waitUntil:n(e=>{e.catch(r=>{console.error("Error in waitUntil:",r)})},"waitUntil")}),"#createContext");constructor(e){this.#e=e}async start(){let{port:e,workerModule:r,env:o}=this.#e,s=e+1;this.#n=Deno.serve({port:s,onListen:n(()=>{A.debug(`Stats server running at http://localhost:${s}`)},"onListen")},a=>a.url.endsWith("/__zuplo/internal_memory_metrics")?new Response(JSON.stringify(Deno.memoryUsage()),{headers:{"content-type":"application/json"}}):new Response("Not Found",{status:404})),this.#t=Deno.serve({port:e,onListen:n(()=>{A.debug(`Server running at http://localhost:${e}`)},"onListen")},async a=>{try{return await r.default.fetch(a,o,this.#r())}catch(f){return A.error("Error handling request:",f),new Response("Internal Server Error",{status:500})}}),await this.#t.finished,await this.#n.finished}async stop(){await this.#t?.shutdown()}};import{pathToFileURL as Lt}from"node:url";var we=N("dist","worker.js");function Se(){if(Deno.build.standalone)return N("..",we);let t=Deno.cwd();return N(t,we)}n(Se,"getDefaultWorkerPath");function Bt(t){return typeof t=="object"&&t!==null&&"default"in t&&typeof t.default=="object"&&"fetch"in t.default&&typeof t.default.fetch=="function"}n(Bt,"isWorkerModule");async function ue(t){let e;if(Deno.build.standalone?(A.debug("Loading worker module from: ",t),e=await import(t)):(A.debug("Loading dev worker module from: ",t),e=await import(Lt(t).href)),!Bt(e))throw new Error("Invalid worker module");return e}n(ue,"importWorkerModule");function _e(){A.info("Enabling fetch host header override");let t=globalThis.fetch,e=Deno.createHttpClient({allowHost:!0,http2:!1});return globalThis.fetch=(r,o)=>{let s={...o??{},client:e};return t(r,s)},e}n(_e,"setFetchHostOverride");function Ne(t){if(new.target)throw new TypeError("Cannot create an instance: parse is not a constructor");return new pe(t).parse()}n(Ne,"parse");var pe=class{static{n(this,"JsoncParser")}#t=new Set(` \r
27
- `);#n=new Set([..."[]{}:,/",...this.#t]);#e;#r;#s;constructor(e){this.#e=`${e}`,this.#r=this.#e.length,this.#s=this.#l()}parse(){let e=this.#o(),r=this.#i(e),{done:o,value:s}=this.#s.next();if(!o)throw new SyntaxError(I(s));return r}#o(){let{done:e,value:r}=this.#s.next();if(e)throw new SyntaxError("Cannot parse JSONC: unexpected end of JSONC input");return r}*#l(){for(let e=0;e<this.#r;e++)if(!this.#t.has(this.#e[e])){if(this.#e[e]==="/"&&this.#e[e+1]==="*"){e+=2;let r=!1;for(;e<this.#r;e++)if(this.#e[e]==="*"&&this.#e[e+1]==="/"){r=!0;break}if(!r)throw new SyntaxError("Cannot parse JSONC: unexpected end of JSONC input");e++;continue}if(this.#e[e]==="/"&&this.#e[e+1]==="/"){for(e+=2;e<this.#r&&!(this.#e[e]===`
28
- `||this.#e[e]==="\r");e++);continue}switch(this.#e[e]){case"{":yield{type:"BeginObject",position:e};break;case"}":yield{type:"EndObject",position:e};break;case"[":yield{type:"BeginArray",position:e};break;case"]":yield{type:"EndArray",position:e};break;case":":yield{type:"NameSeparator",position:e};break;case",":yield{type:"ValueSeparator",position:e};break;case'"':{let r=e,o=!1;for(e++;e<this.#r&&!(this.#e[e]==='"'&&!o);e++)o=this.#e[e]==="\\"&&!o;yield{type:"String",sourceText:this.#e.substring(r,e+1),position:r};break}default:{let r=e;for(;e<this.#r&&!this.#n.has(this.#e[e]);e++);e--,yield{type:"NullOrTrueOrFalseOrNumber",sourceText:this.#e.substring(r,e+1),position:r}}}}}#i(e){switch(e.type){case"BeginObject":return this.#c();case"BeginArray":return this.#f();case"NullOrTrueOrFalseOrNumber":return this.#d(e);case"String":return this.#a(e);default:throw new SyntaxError(I(e))}}#c(){let e={};for(;;){let r=this.#o();if(r.type==="EndObject")return e;if(r.type!=="String")throw new SyntaxError(I(r));let o=this.#a(r),s=this.#o();if(s.type!=="NameSeparator")throw new SyntaxError(I(s));let a=this.#o();Object.defineProperty(e,o,{value:this.#i(a),writable:!0,enumerable:!0,configurable:!0});let f=this.#o();if(f.type==="EndObject")return e;if(f.type!=="ValueSeparator")throw new SyntaxError(I(f))}}#f(){let e=[];for(;;){let r=this.#o();if(r.type==="EndArray")return e;e.push(this.#i(r));let o=this.#o();if(o.type==="EndArray")return e;if(o.type!=="ValueSeparator")throw new SyntaxError(I(o))}}#a(e){let r;try{r=JSON.parse(e.sourceText)}catch{throw new SyntaxError(I(e))}if(typeof r!="string")throw new TypeError(`Parsed value is not a string: ${r}`);return r}#d(e){if(e.sourceText==="null")return null;if(e.sourceText==="true")return!0;if(e.sourceText==="false")return!1;let r;try{r=JSON.parse(e.sourceText)}catch{throw new SyntaxError(I(e))}if(typeof r!="number")throw new TypeError(`Parsed value is not a number: ${r}`);return r}};function I({type:t,sourceText:e,position:r}){let o="";switch(t){case"BeginObject":o="{";break;case"EndObject":o="}";break;case"BeginArray":o="[";break;case"EndArray":o="]";break;case"NameSeparator":o=":";break;case"ValueSeparator":o=",";break;case"NullOrTrueOrFalseOrNumber":case"String":o=30<e.length?`${e.slice(0,30)}...`:e;break}return`Cannot parse JSONC: unexpected token "${o}" in JSONC at position ${r}`}n(I,"buildErrorMessage");var Pe="zuplo.jsonc";function De(t){let e=N(t,Pe),r;try{r=Deno.readTextFileSync(e)}catch(a){A.warn(a,`Failed to read ${Pe}`);return}let o=Ne(r);if(o===null)return;let s;return typeof o=="object"&&"managedDedicatedFlags"in o?s=o.managedDedicatedFlags:typeof o=="object"&&"flags"in o&&typeof o.flags=="object"&&o.flags!==null&&"managedDedicatedFlags"in o.flags?s=o.flags.managedDedicatedFlags:typeof o=="object"&&("projectType"in o||"allowHostHeaderOverride"in o)&&(s={useZeno:"projectType"in o&&o.projectType!=="managed-edge",allowFetchHostHeaderOverride:"allowHostHeaderOverride"in o&&o.allowHostHeaderOverride===!0}),s}n(De,"getManagedDedicatedSettings");var Mt=globalThis.fetch.bind(globalThis);function Oe(){return globalThis.__managedDedicatedMtlsClientState||(globalThis.__managedDedicatedMtlsClientState={clientsByName:{},bindingsByName:{},loadPromise:void 0}),globalThis.managedDedicatedMtlsClients||(globalThis.managedDedicatedMtlsClients=globalThis.__managedDedicatedMtlsClientState.clientsByName),globalThis.managedDedicatedMtlsBindings||(globalThis.managedDedicatedMtlsBindings=globalThis.__managedDedicatedMtlsClientState.bindingsByName),globalThis.__managedDedicatedMtlsClientState}n(Oe,"getMtlsClientState");function Ft(t,e){return e.map(r=>({certName:r,certPath:N(t,r,"tls.crt"),keyPath:N(t,r,"tls.key")}))}n(Ft,"getCertPaths");async function Ht(t,e,r){let o=Ft(t,e);return(await Promise.all(o.map(async({certName:a,certPath:f,keyPath:c})=>{A.info(`Loading mTLS certificate ${a}`);try{let u=await Deno.readTextFile(f),i=await Deno.readTextFile(c),p;return r?p=Deno.createHttpClient({cert:u,key:i,allowHost:!0,http2:!1}):p=Deno.createHttpClient({cert:u,key:i}),A.info(`Successfully loaded mTLS certificate ${a}`),{certName:a,client:p}}catch(u){return A.warn(`Failed to load mTLS certificate ${a}: ${u}`),null}}))).filter(a=>a!==null)}n(Ht,"loadMtlsClientEntries");function ve(t,e,r){let o=Oe();return o.loadPromise||(o.loadPromise=Ht(t,e,r).then(s=>{let a={},f={};for(let{certName:c,client:u}of s)a[c]=u,f[c]={fetch:n((i,p)=>{let g={...p??{},client:u};return Mt(i,g)},"fetch")};return o.clientsByName=a,o.bindingsByName=f,globalThis.managedDedicatedMtlsClients=a,globalThis.managedDedicatedMtlsBindings=f,a}).catch(s=>{throw o.loadPromise=void 0,s})),o.loadPromise}n(ve,"initializeGlobalMtlsClients");function ke(){let t=Oe();for(let e of Object.values(t.clientsByName))e.close();t.clientsByName={},t.bindingsByName={},globalThis.managedDedicatedMtlsClients=t.clientsByName,globalThis.managedDedicatedMtlsBindings=t.bindingsByName,t.loadPromise=void 0}n(ke,"closeGlobalMtlsClients");var It=/^(?:-(?:(?<doubleDash>-)(?<negated>no-)?)?)(?<key>.+?)(?:=(?<value>.+?))?$/s,Ut=/[A-Za-z]/,Gt=/-?\d+(\.\d*)?(e-?\d+)?$/,$t=/^(-|--)[^-]/,Wt=/=(?<value>.+)/,jt=/^--[^=]+$/,zt=/\W/,Vt=/\S/;function Le(t){return Vt.test(t)&&Number.isFinite(Number(t))}n(Le,"isNumber");function j(t,e,r,o=!1){e=[...e];let s=e.pop();if(e.forEach(a=>t=t[a]??={}),o){let a=t[s];if(Array.isArray(a)){a.push(r);return}r=a?[a,r]:[r]}t[s]=r}n(j,"setNested");function ge(t,e){for(let r of e){let o=t[r];if(!Object.hasOwn(t,r))return!1;t=o}return!0}n(ge,"hasNested");function Be(t,e,r){let o=t.get(r);if(o===void 0)return!1;for(let s of o)if(e.has(s))return!0;return!1}n(Be,"aliasIsBoolean");function Me(t){return t==="true"||t==="false"}n(Me,"isBooleanString");function me(t){return t!=="false"}n(me,"parseBooleanString");function Fe(t,e){let{"--":r=!1,alias:o={},boolean:s=!1,default:a={},stopEarly:f=!1,string:c=[],collect:u=[],negatable:i=[],unknown:p=n(d=>d,"unknownFn")}=e??{},g=new Map,y=new Set,x=new Set,w=new Set,S=new Set,P=!1;if(o)for(let[d,l]of Object.entries(o)){if(l===void 0)throw new TypeError("Alias value must be defined");let m=Array.isArray(l)?l:[l];g.set(d,new Set(m)),m.forEach(M=>g.set(M,new Set([d,...m.filter(G=>G!==M)])))}if(s)if(typeof s=="boolean")P=s;else{let d=Array.isArray(s)?s:[s];for(let l of d.filter(Boolean))y.add(l),g.get(l)?.forEach(m=>{y.add(m)})}if(c){let d=Array.isArray(c)?c:[c];for(let l of d.filter(Boolean))x.add(l),g.get(l)?.forEach(m=>x.add(m))}if(u){let d=Array.isArray(u)?u:[u];for(let l of d.filter(Boolean))w.add(l),g.get(l)?.forEach(m=>w.add(m))}if(i){let d=Array.isArray(i)?i:[i];for(let l of d.filter(Boolean))S.add(l),g.get(l)?.forEach(m=>S.add(m))}let C={_:[]};function T(d,l,m,M){if(!y.has(d)&&!x.has(d)&&!g.has(d)&&!(P&&jt.test(m))&&p?.(m,d,l)===!1)return;typeof l=="string"&&!x.has(d)&&(l=Le(l)?Number(l):l);let G=M&&w.has(d);j(C,d.split("."),l,G),g.get(d)?.forEach(h=>{j(C,h.split("."),l,G)})}n(T,"setArgument");let _=[],D=t.indexOf("--");D!==-1&&(_=t.slice(D+1),t=t.slice(0,D));e:for(let d=0;d<t.length;d++){let l=t[d],m=l.match(It)?.groups;if(m){let{doubleDash:M,negated:G}=m,h=m.key,L=m.value;if(M){if(L){y.has(h)&&(L=me(L)),T(h,L,l,!0);continue}if(G){if(S.has(h)){T(h,!1,l,!1);continue}h=`no-${h}`}let O=t[d+1];if(O){if(!y.has(h)&&!P&&!O.startsWith("-")&&(!g.has(h)||!Be(g,y,h))){L=O,d++,T(h,L,l,!0);continue}if(Me(O)){L=me(O),d++,T(h,L,l,!0);continue}}L=x.has(h)?"":!0,T(h,L,l,!0);continue}let he=l.slice(1,-1).split("");for(let[O,U]of he.entries()){let V=l.slice(O+2);if(V==="-"){T(U,V,l,!0);continue}if(Ut.test(U)){let Ae=Wt.exec(V)?.groups;if(Ae){T(U,Ae.value,l,!0);continue e}if(Gt.test(V)){T(U,V,l,!0);continue e}}if(he[O+1]?.match(zt)){T(U,l.slice(O+2),l,!0);continue e}T(U,x.has(U)?"":!0,l,!0)}if(h=l.slice(-1),h==="-")continue;let z=t[d+1];if(z){if(!$t.test(z)&&!y.has(h)&&(!g.has(h)||!Be(g,y,h))){T(h,z,l,!0),d++;continue}if(Me(z)){let O=me(z);T(h,O,l,!0),d++;continue}}T(h,x.has(h)?"":!0,l,!0);continue}if(p?.(l)!==!1&&C._.push(x.has("_")||!Le(l)?l:Number(l)),f){C._.push(...t.slice(d+1));break}}for(let[d,l]of Object.entries(a)){let m=d.split(".");ge(C,m)||(j(C,m,l),g.get(d)?.forEach(M=>j(C,M.split("."),l)))}for(let d of y.keys()){let l=d.split(".");if(!ge(C,l)){let m=w.has(d)?[]:!1;j(C,l,m)}}for(let d of x.keys()){let l=d.split(".");!ge(C,l)&&w.has(d)&&j(C,l,[])}return r?C["--"]=_:C._.push(..._),C}n(Fe,"parseArgs");var He="__ZUPLO_MTLS_CLIENT_CERT_NAMES",Ie="__ZUPLO_MTLS_CLIENT_CERT_BASE_DIR";function Kt(t){return t?[...new Set(t.split(",").map(e=>e.trim()).filter(e=>e.length>0))]:[]}n(Kt,"getMtlsCertNames");async function Jt(){let t;A.debug("Starting Zeno server...");let e=Fe(Deno.args,{boolean:["help"],string:["port","dir"],default:{port:9e3}}),r=Number(e.port);(isNaN(r)||r<1||r>65535)&&(A.error(`Invalid port: ${e.port}. Port must be a number between 1 and 65535.`),Deno.exit(1));let o=r;try{let s=e.dir?e.dir:Deno.cwd(),a=N(s,"dist","worker.js"),f;Deno.build.standalone?f=await ue(Se()):f=await ue(a);let c=await Re(s),u=De(s);u?.allowFetchHostHeaderOverride&&(t=_e());let i=Kt(c[He]),p=c[Ie];p&&i.length>0&&(A.info(`Initializing ${i.length} mTLS client(s)`),await ve(p,i,u?.allowFetchHostHeaderOverride??!1)),await new ne({port:o,workerModule:f,env:c}).start()}catch(s){A.error("Failed to start server:",s)}finally{ke(),t&&t.close()}}n(Jt,"main");import.meta.main&&await Jt();export{Jt as main};
25
+ var ft=Object.defineProperty;var o=(r,e)=>ft(r,"name",{value:e,configurable:!0});import{scheduler as ut}from"node:timers/promises";Object.defineProperty(globalThis,"scheduler",{value:ut,writable:!1,enumerable:!0,configurable:!1});function ee(r){let e=0;for(let s of r)e+=s.length;let t=new Uint8Array(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return t}o(ee,"concat");var z=new TextEncoder,pe=new TextDecoder,pt=42,mt=124,gt=40,ht=33,yt=35,bt=36,At=44,Tt=45,Ct=58,xt=37,Rt=95,_t=62,Et=126,wt=43,St=61,X=z.encode(`\r
26
+ `),Nt=z.encode("*"),vt=z.encode("$");function ue(r){let e=[Nt,z.encode(r.length.toString()),X];for(let t of r){let n=t instanceof Uint8Array?t:z.encode(t.toString());e.push(vt,z.encode(n.byteLength.toString()),X,n,X)}return ee(e)}o(ue,"createRequest");async function*Pt(r){let e=new Uint8Array;for await(let t of r){e=ee([e,t]);let n;for(;(n=e.indexOf(X[0]))!==-1&&e[n+1]===X[1];)yield e.subarray(0,n),e=e.subarray(n+2)}}o(Pt,"readLines");function J(r,e,t=!1){return Array.fromAsync({length:e},()=>q(r,t))}o(J,"readNReplies");function k(r){return pe.decode(r.slice(1))}o(k,"parseLine");function Ot(r){let e=[];for(let t=0;t<r.length;t+=2)e.push(r.slice(t,t+2));return e}o(Ot,"chunk");async function q(r,e=!1){let{value:t}=await r.next();switch(t[0]){case pt:case _t:{let n=Number(k(t));return n===-1?null:await J(r,n)}case mt:{let n=Number(k(t))*2;return await J(r,n),q(r,e)}case gt:return BigInt(k(t));case ht:{let{value:n}=await r.next();return Promise.reject(pe.decode(n))}case yt:return k(t)==="t";case bt:case St:return k(t)==="-1"?null:q(r,e);case At:case Ct:switch(k(t)){case"inf":return 1/0;case"-inf":return-1/0;default:return Number(k(t))}case Tt:return Promise.reject(k(t));case xt:{let n=Number(k(t))*2,s=await J(r,n);return Object.fromEntries(Ot(s))}case Rt:return null;case Et:return new Set(await J(r,Number(k(t)),e));case wt:return k(t);default:return e?t:pe.decode(t)}}o(q,"readReply");var te=class{static{o(this,"RedisClient")}#e;#r;#t=Promise.resolve();constructor(e){this.#e=e.writable.getWriter(),this.#r=Pt(e.readable)}#n(e){return this.#t=this.#t.then(e),this.#t}sendCommand(e,t=!1){return this.#n(()=>(this.#e.write(ue(e)),q(this.#r,t)))}writeCommand(e){return this.#n(()=>this.#e.write(ue(e)))}async*readReplies(e=!1){for(;;)yield q(this.#r,e)}pipelineCommands(e,t=!1){return this.#n(()=>{let n=ee(e.map(ue));return this.#e.write(n),J(this.#r,e.length,t)})}};var R=globalThis.Deno?.build.os==="windows"||globalThis.navigator?.platform?.startsWith("Win")||globalThis.process?.platform?.startsWith("win")||!1;function _(r){if(typeof r!="string")throw new TypeError(`Path must be a string, received "${JSON.stringify(r)}"`)}o(_,"assertPath");function M(r){return r===47}o(M,"isPosixPathSeparator");function T(r){return r===47||r===92}o(T,"isPathSeparator");function H(r){return r>=97&&r<=122||r>=65&&r<=90}o(H,"isWindowsDeviceRoot");function ne(r){if(_(r),r.length===0)return"."}o(ne,"assertArg");function V(r,e,t,n){let s="",i=0,l=-1,a=0,d;for(let c=0;c<=r.length;++c){if(c<r.length)d=r.charCodeAt(c);else{if(n(d))break;d=47}if(n(d)){if(!(l===c-1||a===1))if(l!==c-1&&a===2){if(s.length<2||i!==2||s.charCodeAt(s.length-1)!==46||s.charCodeAt(s.length-2)!==46){if(s.length>2){let p=s.lastIndexOf(t);p===-1?(s="",i=0):(s=s.slice(0,p),i=s.length-1-s.lastIndexOf(t)),l=c,a=0;continue}else if(s.length===2||s.length===1){s="",i=0,l=c,a=0;continue}}e&&(s.length>0?s+=`${t}..`:s="..",i=2)}else s.length>0?s+=t+r.slice(l+1,c):s=r.slice(l+1,c),i=c-l-1;l=c,a=0}else d===46&&a!==-1?++a:a=-1}return s}o(V,"normalizeString");function oe(r){ne(r);let e=M(r.charCodeAt(0)),t=M(r.charCodeAt(r.length-1));return r=V(r,!e,"/",M),r.length===0&&!e&&(r="."),r.length>0&&t&&(r+="/"),e?`/${r}`:r}o(oe,"normalize");function ge(...r){if(r.length===0)return".";r.forEach(t=>_(t));let e=r.filter(t=>t.length>0).join("/");return e===""?".":oe(e)}o(ge,"join");function se(r){ne(r);let e=r.length,t=0,n,s=!1,i=r.charCodeAt(0);if(e>1)if(T(i))if(s=!0,T(r.charCodeAt(1))){let a=2,d=a;for(;a<e&&!T(r.charCodeAt(a));++a);if(a<e&&a!==d){let c=r.slice(d,a);for(d=a;a<e&&T(r.charCodeAt(a));++a);if(a<e&&a!==d){for(d=a;a<e&&!T(r.charCodeAt(a));++a);if(a===e)return`\\\\${c}\\${r.slice(d)}\\`;a!==d&&(n=`\\\\${c}\\${r.slice(d,a)}`,t=a)}}}else t=1;else H(i)&&r.charCodeAt(1)===58&&(n=r.slice(0,2),t=2,e>2&&T(r.charCodeAt(2))&&(s=!0,t=3));else if(T(i))return"\\";let l;return t<e?l=V(r.slice(t),!s,"\\",T):l="",l.length===0&&!s&&(l="."),l.length>0&&T(r.charCodeAt(e-1))&&(l+="\\"),n===void 0?s?l.length>0?`\\${l}`:"\\":l:s?l.length>0?`${n}\\${l}`:`${n}\\`:n+l}o(se,"normalize");function he(...r){if(r.forEach(i=>_(i)),r=r.filter(i=>i.length>0),r.length===0)return".";let e=!0,t=0,n=r[0];if(T(n.charCodeAt(0))){++t;let i=n.length;i>1&&T(n.charCodeAt(1))&&(++t,i>2&&(T(n.charCodeAt(2))?++t:e=!1))}let s=r.join("\\");if(e){for(;t<s.length&&T(s.charCodeAt(t));++t);t>=2&&(s=`\\${s.slice(t)}`)}return se(s)}o(he,"join");function N(...r){return R?he(...r):ge(...r)}o(N,"join");function qt(r){if(r.length>=255)throw new TypeError("Alphabet too long");let e=new Uint8Array(256);for(let c=0;c<e.length;c++)e[c]=255;for(let c=0;c<r.length;c++){let p=r.charAt(c),g=p.charCodeAt(0);if(e[g]!==255)throw new TypeError(p+" is ambiguous");e[g]=c}let t=r.length,n=r.charAt(0),s=Math.log(t)/Math.log(256),i=Math.log(256)/Math.log(t);function l(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 p=0,g=0,h=0,C=c.length;for(;h!==C&&c[h]===0;)h++,p++;let E=(C-h)*i+1>>>0,w=new Uint8Array(E);for(;h!==C;){let A=c[h],S=0;for(let O=E-1;(A!==0||S<g)&&O!==-1;O--,S++)A+=256*w[O]>>>0,w[O]=A%t>>>0,A=A/t>>>0;if(A!==0)throw new Error("Non-zero carry");g=S,h++}let v=E-g;for(;v!==E&&w[v]===0;)v++;let x=n.repeat(p);for(;v<E;++v)x+=r.charAt(w[v]);return x}o(l,"encode");function a(c){if(typeof c!="string")throw new TypeError("Expected String");if(c.length===0)return new Uint8Array;let p=0,g=0,h=0;for(;c[p]===n;)g++,p++;let C=(c.length-p)*s+1>>>0,E=new Uint8Array(C);for(;p<c.length;){let A=c.charCodeAt(p);if(A>255)return;let S=e[A];if(S===255)return;let O=0;for(let u=C-1;(S!==0||O<h)&&u!==-1;u--,O++)S+=t*E[u]>>>0,E[u]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");h=O,p++}let w=C-h;for(;w!==C&&E[w]===0;)w++;let v=new Uint8Array(g+(C-w)),x=g;for(;w!==C;)v[x++]=E[w++];return v}o(a,"decodeUnsafe");function d(c){let p=a(c);if(p)return p;throw new Error("Non-base"+t+" character")}return o(d,"decode"),{encode:l,decodeUnsafe:a,decode:d}}o(qt,"base");var Me=qt;var Yt="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",Le=Me(Yt);import{pathToFileURL as He}from"node:url";import Ie from"dotenv";var ye=class{static{o(this,"ZenoLogger")}prefix="[ZENO]:";logLevel;originalConsole={debug:console.debug,info:console.info,warn:console.warn,error:console.error};constructor(e="info"){this.logLevel=e}debug(...e){(this.shouldLog("debug")||Deno.env.get("ZENO_DEBUG"))&&this.originalConsole.debug(this.prefix,"[DEBUG]",...e)}info(...e){this.shouldLog("info")&&this.originalConsole.info(this.prefix,"[INFO]",...e)}warn(...e){this.shouldLog("warn")&&this.originalConsole.warn(this.prefix,"[WARN]",...e)}error(...e){this.shouldLog("error")&&this.originalConsole.error(this.prefix,"[ERROR]",...e)}shouldLog(e){let t=["debug","info","warn","error"],n=t.indexOf(this.logLevel);return t.indexOf(e)>=n}setLogLevel(e){this.logLevel=e}},m=new ye;async function Be(r){let e={};for(let[t,n]of Object.entries(Deno.env.toObject()))n!==void 0&&(e[t]=n);try{let t=N(r,".env.zuplo"),n=new TextDecoder("utf-8"),s=await Deno.readFile(He(t)),i=n.decode(s),l=Ie.parse(i);for(let[a,d]of Object.entries(l))if(e[a]=d,a==="ZUPLO_SYSTEM_CONFIGURATIONS")try{let c=new TextDecoder().decode(Le.decode(d)),p=JSON.parse(c);for(let[g,h]of Object.entries(p))e[g]=String(h)}catch(c){Deno.build.standalone||m.error("Failed to parse ZUPLO_SYSTEM_CONFIGURATIONS from .env.zuplo:",c)}}catch(t){t instanceof Deno.errors.NotFound||m.error("Failed to load .env.zuplo file:",t)}try{let t=N(r,".env"),n=new TextDecoder("utf-8"),s=await Deno.readFile(He(t)),i=n.decode(s),l=Ie.parse(i);for(let[a,d]of Object.entries(l))e[a]=d}catch(t){t instanceof Deno.errors.NotFound||m.error("Failed to load .env.zuplo file:",t)}for(let[t,n]of Object.entries(e))n===void 0&&delete e[t];return e.__ZUPLO_IS_MANAGED_DEDICATED="true",e}o(Be,"loadEnvironment");function $e(r){return r?["true","1","yes","y"].includes(r.toLowerCase()):!1}o($e,"parseEnvBool");var be=class{static{o(this,"CacheStorage")}#e;constructor(){this.#e=new Map}async open(e){let t=this.#e.get(e);return t||(t=new Ae,this.#e.set(e,t)),t}async has(e){return this.#e.has(e)}async delete(e){throw new Error("caches.delete is not supported")}};async function Qt(){let r=Deno.env.get("ZUPLO_CACHE_REDIS_HOSTNAME");if(r===void 0)throw new Error("ZUPLO_CACHE_REDIS_HOSTNAME is not set");let e=parseInt(Deno.env.get("ZUPLO_CACHE_REDIS_PORT")||"6379"),t=await Deno.connect({hostname:r,port:e});return new te(t)}o(Qt,"getRedisClient");function er(r){let e={};return r&&r.split(",").forEach(n=>{let[s,i]=n.trim().split("=");e[s.toLowerCase()]=i?i.trim():!0}),e}o(er,"parseHeaderValue");function tr(r){let e={};for(let[t,n]of r.entries())e[t]=n;return e}o(tr,"objectifyHeaders");async function rr(r){let e=await r.arrayBuffer(),t=new Uint8Array(e),n="";for(let s=0;s<t.length;s++)n+=String.fromCharCode(t[s]);return btoa(n)}o(rr,"serializeResponseBody");function nr(r){let e=atob(r),t=e.length,n=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=e.charCodeAt(s);return n}o(nr,"deserializeResponseBody");var Ae=class{static{o(this,"Cache")}#e;#r;#t;constructor(e="default",t={}){this.#e=e;let n=Deno.env.get("ZUPLO_CACHE_REDIS_HOSTNAME")&&Deno.env.get("ZUPLO_CACHE_REDIS_PORT");this.#r=!n||!$e(Deno.env.get("USE_ZENO_ZONE_CACHE")),this.#t=t.getRedisClient||Qt}#n(e){return`${this.#e}:${e.url}`}async match(e,t){if(this.#r)return;let n=this.#n(e),s=await this.#t();await s.sendCommand(["HELLO",3]);let i=await s.sendCommand(["TTL",n]);if(i!==-2){if(i<2)return;{let l=await s.sendCommand(["HGETALL",n]),a=l.status,d=l.status,c=new Headers(JSON.parse(l.headers));return new Response(nr(l.body),{status:a,statusText:d,headers:c})}}}async put(e,t){if(this.#r)return;let n=1*60*60,s=er(t.headers.get("cache-control")),i=parseInt(s["s-maxage"]),l=parseInt(s["max-age"]),a=s["no-store"],d=s["no-cache"],c=i||l||0;if(c===0&&!a&&!d&&(c=n,t.headers.append("cache-control",`s-maxage=${n}`)),c>0){let p=this.#n(e),g=await this.#t();await g.sendCommand(["HELLO",3]),await g.sendCommand(["HSET",p,"maxage",c,"status",t.status,"statusText",t.statusText,"headers",JSON.stringify(tr(t.headers)),"body",await rr(t)]),await g.sendCommand(["EXPIRE",p,c])}}async delete(e){if(this.#r)return;let t=this.#n(e);if(await(await this.#t()).sendCommand(["DEL",t])!==1)throw new Error("Failed to delete cache entry")}},or=new be;Object.defineProperty(globalThis,"caches",{value:or,writable:!1,enumerable:!0,configurable:!1});var Ge="text/plain; version=0.0.4; charset=utf-8",P=Object.freeze({nameLength:200,helpLength:1024,labelNames:16,labelNameLength:100,labelValueLength:256,buckets:50,defaultMaxSeries:500,expositionBytes:1024*1024}),sr=/^[a-zA-Z_:][a-zA-Z0-9_:]*$/,ir=/^[a-zA-Z_][a-zA-Z0-9_]*$/,Te=24,ar=Object.freeze({inc(){}}),lr=Object.freeze({set(){},inc(){},dec(){}}),cr=Object.freeze({observe(){}}),Ce=class{static{o(this,"ExpositionBudget")}#e=0;#r;constructor(e){this.#r=e}tryCharge(e){return this.#e+e>this.#r?!1:(this.#e+=e,!0)}refund(e){this.#e=Math.max(0,this.#e-e)}},ie=class{static{o(this,"Metric")}name;help;labelNames;series=new Map;#e;#r;#t;#n=!1;exposeZeroWhenEmpty=!0;constructor(e,t){this.name=e.name,this.help=e.help,this.labelNames=Object.freeze([...e.labelNames??[]]),this.#e=e.maxSeries??P.defaultMaxSeries,this.#r=t}child(e){if(e!==void 0&&(typeof e!="object"||e===null))return this.#o("labels must be an object");if(this.labelNames.length===0)return e!==void 0&&pr(e)?this.#o("this metric has no labels"):(this.#t===void 0&&(this.#t=this.#s("",[])),this.#t??this.noopChild());if(e===void 0)return this.#o("labels are required");let t=new Array(this.labelNames.length);for(let i=0;i<this.labelNames.length;i++){let l=e[this.labelNames[i]];if(typeof l!="string")return this.#o(`label "${this.labelNames[i]}" is missing`);if(l.length>P.labelValueLength)return this.#o(`label "${this.labelNames[i]}" is longer than ${P.labelValueLength} characters`);t[i]=l}if(mr(e)!==this.labelNames.length)return this.#o("unexpected label names");let n=ur(t),s=this.series.get(n);return s!==void 0?s.child:this.#s(n,t)??this.noopChild()}reset(){let e=0;for(let{cost:t}of this.series.values())e+=t;this.#r.budget?.refund(e),this.series.clear(),this.#t=void 0}matches(e,t){let n=t.labelNames??[];return e===this.type&&n.length===this.labelNames.length&&n.every((s,i)=>s===this.labelNames[i])}render(e){e.push(`# HELP ${this.name} ${gr(this.help)}`),e.push(`# TYPE ${this.name} ${this.type}`),this.exposeZeroWhenEmpty&&this.labelNames.length===0&&this.series.size===0&&this.child();for(let{labelText:t,child:n}of this.series.values())this.renderSeries(e,t,n)}#s(e,t){if(this.series.size>=this.#e){this.#r.onDrop(this.name,"series_limit");return}let n="";for(let l=0;l<t.length;l++)l>0&&(n+=","),n+=`${this.labelNames[l]}="${hr(t[l])}"`;let s=this.seriesCost(n);if(this.#r.budget!==void 0&&!this.#r.budget.tryCharge(s)){this.#r.onDrop(this.name,"budget");return}let i=this.createChild();return this.series.set(e,{labelText:n,child:i,cost:s}),i}#o(e){return this.#n||(this.#n=!0,m.warn(`Metric ${this.name} expects labels [${this.labelNames.join(", ")}] (${e}); dropping these observations`)),this.noopChild()}},ae=class{static{o(this,"ValueSeries")}value=0;#e;constructor(e){this.#e=e}set(e){typeof e=="number"&&(this.value=e)}inc(e=1){typeof e!="number"||this.#e&&!(e>=0)||(this.value+=e)}dec(e=1){typeof e=="number"&&(this.value-=e)}},le=class extends ie{static{o(this,"ValueMetric")}#e;#r=!1;constructor(e,t){super(e,t),this.#e=e.collect,this.exposeZeroWhenEmpty=e.collect===void 0}render(e){if(this.#e!==void 0){this.reset();try{this.#e((t,n)=>{this.child(n).set(t)})}catch(t){this.#r||(this.#r=!0,m.warn(`Failed to collect metric ${this.name}:`,t))}}super.render(e)}seriesCost(e){return this.name.length+e.length+Te+4}renderSeries(e,t,n){let{value:s}=n;e.push(`${this.name}${ze(t)} ${Q(s)}`)}},ce=class extends le{static{o(this,"Counter")}type="counter";inc(e){this.child().inc(e)}createChild(){return new ae(!0)}noopChild(){return ar}},xe=class extends le{static{o(this,"Gauge")}type="gauge";set(e){this.child().set(e)}inc(e){this.child().inc(e)}dec(e){this.child().dec(e)}createChild(){return new ae(!1)}noopChild(){return lr}},Re=class{static{o(this,"HistogramSeries")}#e;counts;sum=0;count=0;constructor(e){this.#e=e,this.counts=new Float64Array(e.length+1)}observe(e){if(typeof e!="number"||Number.isNaN(e))return;let t=this.#e,n=0;for(;n<t.length&&e>t[n];)n++;this.counts[n]++,this.sum+=e,this.count++}},_e=class extends ie{static{o(this,"Histogram")}type="histogram";#e;#r;#t;constructor(e,t){super(e,t),this.#e=Float64Array.from(e.buckets),this.#r=[...e.buckets.map(Q),"+Inf"],this.#t=this.#r.reduce((n,s)=>n+s.length,0)}observe(e){this.child().observe(e)}matches(e,t){let n=t.buckets??[];return super.matches(e,t)&&n.length===this.#e.length&&n.every((s,i)=>s===this.#e[i])}createChild(){return new Re(this.#e)}noopChild(){return cr}seriesCost(e){let n=this.#r.length*(this.name.length+e.length+16+Te)+this.#t,s=2*(this.name.length+e.length+10+Te);return n+s}renderSeries(e,t,n){let s=n,i=t===""?"{":`{${t},`,l=0;for(let d=0;d<s.counts.length;d++)l+=s.counts[d],e.push(`${this.name}_bucket${i}le="${this.#r[d]}"} ${Q(l)}`);let a=ze(t);e.push(`${this.name}_sum${a} ${Q(s.sum)}`),e.push(`${this.name}_count${a} ${Q(s.count)}`)}},Fe={name:"zeno_metrics_series_dropped_total",help:"Observations dropped because a metric reached its series limit or the /metrics size budget.",labelNames:["metric","reason"],maxSeries:1/0},de=class{static{o(this,"Registry")}#e=new Map;#r=new Map;#t;#n=new Set;#s;constructor(e={}){this.#t=new Ce(e.expositionBytes??P.expositionBytes)}counter(e){return this.#o("counter",e,t=>new ce(e,t),this.#t)}gauge(e){return this.#o("gauge",e,t=>new xe(e,t),this.#t)}histogram(e){return this.#o("histogram",e,t=>new _e(e,t),this.#t)}render(){let e=[],t=[];for(let n of this.#e.values()){t.length=0;try{n.render(t)}catch(s){this.#n.has(n)||(this.#n.add(n),m.warn(`Failed to render metric ${n.name}:`,s));continue}for(let s of t)e.push(s)}return e.push(""),e.join(`
27
+ `)}#o(e,t,n,s){fr(e,t);let i=this.#e.get(t.name);if(i!==void 0){if(!i.matches(e,t))throw new Error(`Metric ${t.name} is already registered with a different type, labels or buckets`);return i}let l=dr(e,t.name);for(let c of l){let p=this.#r.get(c);if(p!==void 0)throw new Error(`Metric ${t.name} would expose ${c}, which ${p.type} ${p.name} already uses`)}let a=2*t.name.length+2*t.help.length+32;if(s!==void 0&&!s.tryCharge(a))throw new Error(`Metric ${t.name} not registered: the /metrics size budget is exhausted`);let d=n({budget:s,onDrop:this.#i});this.#e.set(d.name,d);for(let c of l)this.#r.set(c,d);return d}#i=o((e,t)=>{this.#s??=this.#o("counter",Fe,n=>new ce(Fe,n),void 0),this.#s.child({metric:e,reason:t}).inc()},"#onDrop")};function dr(r,e){return r==="histogram"?[e,`${e}_bucket`,`${e}_sum`,`${e}_count`]:[e]}o(dr,"exposedNames");function fr(r,e){if(typeof e!="object"||e===null)throw new Error("Metric definition must be an object");let{name:t,help:n,labelNames:s,maxSeries:i}=e;if(typeof t!="string"||t.length>P.nameLength||!sr.test(t))throw new Error(`Invalid metric name ${Ue(t)}: use [a-zA-Z_:][a-zA-Z0-9_:]*, at most ${P.nameLength} characters`);if(typeof n!="string"||n.length>P.helpLength)throw new Error(`Metric ${t} needs a help string of at most ${P.helpLength} characters`);if(s!==void 0){if(!Array.isArray(s)||s.length>P.labelNames)throw new Error(`Metric ${t} labelNames must be an array of at most ${P.labelNames} names`);for(let a of s){if(typeof a!="string"||a.length>P.labelNameLength||!ir.test(a)||a.startsWith("__"))throw new Error(`Invalid label name ${Ue(a)} on metric ${t}`);if(r==="histogram"&&a==="le")throw new Error(`Histogram ${t} cannot use the label "le"`)}if(new Set(s).size!==s.length)throw new Error(`Duplicate label names on metric ${t}`)}if(i!==void 0&&(typeof i!="number"||!(i>=0)))throw new Error(`Metric ${t} maxSeries must be a non-negative number`);if(r!=="histogram"){let{collect:a}=e;if(a!==void 0&&typeof a!="function")throw new Error(`Metric ${t} collect must be a function`);return}let{buckets:l}=e;if(!Array.isArray(l)||l.length===0||l.length>P.buckets)throw new Error(`Histogram ${t} needs between 1 and ${P.buckets} buckets`);for(let a=0;a<l.length;a++){if(typeof l[a]!="number"||!Number.isFinite(l[a]))throw new Error(`Histogram ${t} has a non-finite bucket`);if(a>0&&l[a]<=l[a-1])throw new Error(`Histogram ${t} buckets must be strictly ascending`)}}o(fr,"validateOptions");function ur(r){if(r.length===1)return r[0];let e="";for(let t of r)e+=`${t.length}:${t}`;return e}o(ur,"seriesKey");function pr(r){for(let e in r)if(Object.hasOwn(r,e))return!0;return!1}o(pr,"hasOwnKeys");function mr(r){let e=0;for(let t in r)Object.hasOwn(r,t)&&e++;return e}o(mr,"countOwnKeys");function ze(r){return r===""?"":`{${r}}`}o(ze,"braces");function Ue(r){let e=typeof r=="string"?r:typeof r;return e.length>64?`"${e.slice(0,64)}\u2026"`:`"${e}"`}o(Ue,"preview");function Q(r){return Number.isNaN(r)?"NaN":r===1/0?"+Inf":r===-1/0?"-Inf":String(r)}o(Q,"formatNumber");function gr(r){return r.replace(/\\/g,"\\\\").replace(/\n/g,"\\n")}o(gr,"escapeHelp");function hr(r){return r.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n")}o(hr,"escapeLabelValue");var W="ZUPLO_METRICS_PORT",Ee=0;function Ve(r){let{port:e,flag:t,env:n}=r,[s,i]=t!==void 0?["--metrics-port",t]:n!==void 0?[W,n]:[void 0,void 0];if(s===void 0){let d=e+1;return d>65535?(m.warn(`Stats server disabled: the default metrics port is the gateway port + 1, and port ${e} leaves no room for it. Set --metrics-port or ${W} to a free port.`),Ee):d}let l=i.trim(),a=Number(l);if(l===""||!Number.isInteger(a)||a<0||a>65535)throw new Error(`Invalid ${s} "${i}". Use a port between 1 and 65535, or 0 to disable the stats server.`);if(a===e)throw new Error(`Invalid ${s} "${i}": it is the same as the gateway port. Pick a different free port, or 0 to disable the stats server.`);return a}o(Ve,"resolveMetricsPort");import We from"node:v8";import je from"node:process";var yr=[.001,.005,.01,.025,.05,.1,.25,.5,1,2.5],br=100;function Ke(r){r.counter({name:"process_cpu_user_seconds_total",help:"User CPU time spent by the process, in seconds.",collect:o(t=>t(je.cpuUsage().user/1e6),"collect")}),r.counter({name:"process_cpu_system_seconds_total",help:"System CPU time spent by the process, in seconds.",collect:o(t=>t(je.cpuUsage().system/1e6),"collect")}),r.gauge({name:"process_resident_memory_bytes",help:"Resident set size of the process, in bytes.",collect:o(t=>t(Deno.memoryUsage().rss),"collect")});let e=performance.timeOrigin/1e3;r.gauge({name:"process_start_time_seconds",help:"Start time of the process since the Unix epoch, in seconds.",collect:o(t=>t(e),"collect")}),Ar(r),r.gauge({name:"zeno_build_info",help:"Always 1. Labels carry the Deno and V8 versions.",labelNames:["deno_version","v8_version"],collect:o(t=>t(1,{deno_version:Deno.version.deno,v8_version:Deno.version.v8}),"collect")})}o(Ke,"registerProcessMetrics");function Ar(r){let e=o((n,s,i)=>r.gauge({name:n,help:s,collect:o(l=>l(i(We.getHeapStatistics())),"collect")}),"heapStat");e("v8_heap_size_limit_bytes","Maximum size the V8 heap can grow to, in bytes.",n=>n.heap_size_limit),e("v8_heap_total_bytes","Total size of the V8 heap, in bytes.",n=>n.total_heap_size),e("v8_heap_used_bytes","Used size of the V8 heap, in bytes.",n=>n.used_heap_size),e("v8_heap_available_bytes","Bytes the V8 heap can still allocate before reaching its limit.",n=>n.total_available_size),e("v8_heap_physical_bytes","Committed physical memory of the V8 heap, in bytes.",n=>n.total_physical_size),e("v8_malloced_memory_bytes","Memory V8 allocated outside the heap with malloc, in bytes.",n=>n.malloced_memory),e("v8_peak_malloced_memory_bytes","Peak memory V8 allocated outside the heap with malloc, in bytes.",n=>n.peak_malloced_memory),e("v8_native_contexts","Number of live V8 native contexts.",n=>n.number_of_native_contexts),e("v8_detached_contexts","Number of detached V8 contexts. Growth indicates a leak.",n=>n.number_of_detached_contexts),r.gauge({name:"v8_external_memory_bytes",help:"Memory held by JS objects bound to native memory, such as ArrayBuffers, in bytes.",collect:o(n=>n(Deno.memoryUsage().external),"collect")});let t=o((n,s,i)=>r.gauge({name:n,help:s,labelNames:["space"],collect:o(l=>{for(let a of We.getHeapSpaceStatistics())l(i(a),{space:a.space_name})},"collect")}),"heapSpaceStat");t("v8_heap_space_size_bytes","Size of each V8 heap space, in bytes.",n=>n.space_size),t("v8_heap_space_used_bytes","Used size of each V8 heap space, in bytes.",n=>n.space_used_size),t("v8_heap_space_available_bytes","Available size of each V8 heap space, in bytes.",n=>n.space_available_size)}o(Ar,"registerHeapMetrics");function Ze(r){return r.histogram({name:"deno_event_loop_lag_seconds",help:"How late a timer scheduled every 100ms fired, in seconds. Measures event loop blocking.",buckets:yr})}o(Ze,"registerEventLoopLag");function Je(r,e=br){let t,n=!1,s=o(()=>{let i=performance.now()+e,l=setTimeout(()=>{r.observe(Math.max(0,performance.now()-i)/1e3),n||s()},e);Deno.unrefTimer(l),t=l},"schedule");return s(),()=>{n=!0,clearTimeout(t)}}o(Je,"startEventLoopLagSampler");var Tr=[.005,.01,.025,.05,.1,.25,.5,1,2.5,5,10,30,60],we=["1xx","2xx","3xx","4xx","5xx"];function Cr(r){let e=r.gauge({name:"zeno_http_requests_in_flight",help:"Requests the worker module is currently handling."}),t=r.histogram({name:"zeno_http_request_duration_seconds",help:"Time until the worker module returned response headers, in seconds. Excludes body streaming.",labelNames:["code"],buckets:Tr}),n=r.counter({name:"zeno_errors_total",help:"Errors Zeno caught outside the runtime's own error handling.",labelNames:["kind"]});return{inFlight:e,durationByStatusClass:we.map(s=>t.child({code:s})),handlerErrors:n.child({kind:"handler"}),waitUntilErrors:n.child({kind:"wait_until"})}}o(Cr,"createServerMetrics");var xr={inFlight:{inc(){},dec(){}},durationByStatusClass:we.map(()=>({observe(){}})),handlerErrors:{inc(){}},waitUntilErrors:{inc(){}}};function Rr(r){try{Ke(r)}catch(e){m.error("Failed to register process metrics:",e)}try{return Cr(r)}catch(e){return m.error("Failed to register request metrics:",e),xr}}o(Rr,"registerBuiltinMetrics");var fe=class{static{o(this,"WorkerServer")}#e;#r;#t;#n;#s;#o;#i=o(()=>({waitUntil:o(e=>{e.catch(t=>{this.#o.waitUntilErrors.inc(),console.error("Error in waitUntil:",t)})},"waitUntil")}),"#createContext");constructor(e){this.#n=e,this.#s=e.registry??new de,this.#o=Rr(this.#s)}async start(){let{port:e,workerModule:t,env:n}=this.#n,s=this.#o;try{this.#t=Je(Ze(this.#s))}catch(i){m.error("Failed to start the event loop lag sampler:",i)}this.#r=this.#a(this.#n.metricsPort??e+1),this.#e=Deno.serve({port:e,onListen:o(()=>{m.debug(`Server running at http://localhost:${e}`)},"onListen")},async i=>{let l=performance.now();s.inFlight.inc();let a=500;try{let d=await t.default.fetch(i,n,this.#i());return a=d.status,d}catch(d){return s.handlerErrors.inc(),m.error("Error handling request:",d),new Response("Internal Server Error",{status:500})}finally{s.inFlight.dec(),s.durationByStatusClass[_r(a)].observe((performance.now()-l)/1e3)}}),await this.#e.finished,await this.#r?.finished}async stop(){this.#t?.(),await Promise.all([this.#e?.shutdown(),this.#r?.shutdown()])}#a(e){if(e===Ee){m.info("Stats server disabled (metrics port is 0)");return}try{return Deno.serve({port:e,onListen:o(()=>{m.debug(`Stats server running at http://localhost:${e}`)},"onListen")},t=>this.#l(t))}catch(t){m.error(`Could not start the stats server on port ${e}; serving traffic without /metrics. Set --metrics-port or ${W} to a free port, or to 0 to disable it.`,t);return}}#l(e){let{pathname:t}=new URL(e.url);return t==="/metrics"?new Response(this.#s.render(),{headers:{"content-type":Ge}}):t==="/__zuplo/internal_memory_metrics"?new Response(JSON.stringify(Deno.memoryUsage()),{headers:{"content-type":"application/json"}}):new Response("Not Found",{status:404})}};function _r(r){let e=Math.floor(r/100)-1;return e>=0&&e<we.length?e:4}o(_r,"statusClassIndex");import{pathToFileURL as Er}from"node:url";var Xe=N("dist","worker.js");function qe(){if(Deno.build.standalone)return N("..",Xe);let r=Deno.cwd();return N(r,Xe)}o(qe,"getDefaultWorkerPath");function wr(r){return typeof r=="object"&&r!==null&&"default"in r&&typeof r.default=="object"&&"fetch"in r.default&&typeof r.default.fetch=="function"}o(wr,"isWorkerModule");async function Se(r){let e;if(Deno.build.standalone?(m.debug("Loading worker module from: ",r),e=await import(r)):(m.debug("Loading dev worker module from: ",r),e=await import(Er(r).href)),!wr(e))throw new Error("Invalid worker module");return e}o(Se,"importWorkerModule");function Ye(){m.info("Enabling fetch host header override");let r=globalThis.fetch,e=Deno.createHttpClient({allowHost:!0,http2:!1});return globalThis.fetch=(t,n)=>{let s={...n??{},client:e};return r(t,s)},e}o(Ye,"setFetchHostOverride");function Qe(r){if(new.target)throw new TypeError("Cannot create an instance: parse is not a constructor");return new Ne(r).parse()}o(Qe,"parse");var Ne=class{static{o(this,"JsoncParser")}#e=new Set(` \r
28
+ `);#r=new Set([..."[]{}:,/",...this.#e]);#t;#n;#s;constructor(e){this.#t=`${e}`,this.#n=this.#t.length,this.#s=this.#i()}parse(){let e=this.#o(),t=this.#a(e),{done:n,value:s}=this.#s.next();if(!n)throw new SyntaxError(F(s));return t}#o(){let{done:e,value:t}=this.#s.next();if(e)throw new SyntaxError("Cannot parse JSONC: unexpected end of JSONC input");return t}*#i(){for(let e=0;e<this.#n;e++)if(!this.#e.has(this.#t[e])){if(this.#t[e]==="/"&&this.#t[e+1]==="*"){e+=2;let t=!1;for(;e<this.#n;e++)if(this.#t[e]==="*"&&this.#t[e+1]==="/"){t=!0;break}if(!t)throw new SyntaxError("Cannot parse JSONC: unexpected end of JSONC input");e++;continue}if(this.#t[e]==="/"&&this.#t[e+1]==="/"){for(e+=2;e<this.#n&&!(this.#t[e]===`
29
+ `||this.#t[e]==="\r");e++);continue}switch(this.#t[e]){case"{":yield{type:"BeginObject",position:e};break;case"}":yield{type:"EndObject",position:e};break;case"[":yield{type:"BeginArray",position:e};break;case"]":yield{type:"EndArray",position:e};break;case":":yield{type:"NameSeparator",position:e};break;case",":yield{type:"ValueSeparator",position:e};break;case'"':{let t=e,n=!1;for(e++;e<this.#n&&!(this.#t[e]==='"'&&!n);e++)n=this.#t[e]==="\\"&&!n;yield{type:"String",sourceText:this.#t.substring(t,e+1),position:t};break}default:{let t=e;for(;e<this.#n&&!this.#r.has(this.#t[e]);e++);e--,yield{type:"NullOrTrueOrFalseOrNumber",sourceText:this.#t.substring(t,e+1),position:t}}}}}#a(e){switch(e.type){case"BeginObject":return this.#l();case"BeginArray":return this.#d();case"NullOrTrueOrFalseOrNumber":return this.#f(e);case"String":return this.#c(e);default:throw new SyntaxError(F(e))}}#l(){let e={};for(;;){let t=this.#o();if(t.type==="EndObject")return e;if(t.type!=="String")throw new SyntaxError(F(t));let n=this.#c(t),s=this.#o();if(s.type!=="NameSeparator")throw new SyntaxError(F(s));let i=this.#o();Object.defineProperty(e,n,{value:this.#a(i),writable:!0,enumerable:!0,configurable:!0});let l=this.#o();if(l.type==="EndObject")return e;if(l.type!=="ValueSeparator")throw new SyntaxError(F(l))}}#d(){let e=[];for(;;){let t=this.#o();if(t.type==="EndArray")return e;e.push(this.#a(t));let n=this.#o();if(n.type==="EndArray")return e;if(n.type!=="ValueSeparator")throw new SyntaxError(F(n))}}#c(e){let t;try{t=JSON.parse(e.sourceText)}catch{throw new SyntaxError(F(e))}if(typeof t!="string")throw new TypeError(`Parsed value is not a string: ${t}`);return t}#f(e){if(e.sourceText==="null")return null;if(e.sourceText==="true")return!0;if(e.sourceText==="false")return!1;let t;try{t=JSON.parse(e.sourceText)}catch{throw new SyntaxError(F(e))}if(typeof t!="number")throw new TypeError(`Parsed value is not a number: ${t}`);return t}};function F({type:r,sourceText:e,position:t}){let n="";switch(r){case"BeginObject":n="{";break;case"EndObject":n="}";break;case"BeginArray":n="[";break;case"EndArray":n="]";break;case"NameSeparator":n=":";break;case"ValueSeparator":n=",";break;case"NullOrTrueOrFalseOrNumber":case"String":n=30<e.length?`${e.slice(0,30)}...`:e;break}return`Cannot parse JSONC: unexpected token "${n}" in JSONC at position ${t}`}o(F,"buildErrorMessage");var et="zuplo.jsonc";function tt(r){let e=N(r,et),t;try{t=Deno.readTextFileSync(e)}catch(i){m.warn(i,`Failed to read ${et}`);return}let n=Qe(t);if(n===null)return;let s;return typeof n=="object"&&"managedDedicatedFlags"in n?s=n.managedDedicatedFlags:typeof n=="object"&&"flags"in n&&typeof n.flags=="object"&&n.flags!==null&&"managedDedicatedFlags"in n.flags?s=n.flags.managedDedicatedFlags:typeof n=="object"&&("projectType"in n||"allowHostHeaderOverride"in n)&&(s={useZeno:"projectType"in n&&n.projectType!=="managed-edge",allowFetchHostHeaderOverride:"allowHostHeaderOverride"in n&&n.allowHostHeaderOverride===!0}),s}o(tt,"getManagedDedicatedSettings");var Sr=globalThis.fetch.bind(globalThis);function rt(){return globalThis.__managedDedicatedMtlsClientState||(globalThis.__managedDedicatedMtlsClientState={clientsByName:{},bindingsByName:{},loadPromise:void 0}),globalThis.managedDedicatedMtlsClients||(globalThis.managedDedicatedMtlsClients=globalThis.__managedDedicatedMtlsClientState.clientsByName),globalThis.managedDedicatedMtlsBindings||(globalThis.managedDedicatedMtlsBindings=globalThis.__managedDedicatedMtlsClientState.bindingsByName),globalThis.__managedDedicatedMtlsClientState}o(rt,"getMtlsClientState");function Nr(r,e){return e.map(t=>({certName:t,certPath:N(r,t,"tls.crt"),keyPath:N(r,t,"tls.key")}))}o(Nr,"getCertPaths");async function vr(r,e,t){let n=Nr(r,e);return(await Promise.all(n.map(async({certName:i,certPath:l,keyPath:a})=>{m.info(`Loading mTLS certificate ${i}`);try{let d=await Deno.readTextFile(l),c=await Deno.readTextFile(a),p;return t?p=Deno.createHttpClient({cert:d,key:c,allowHost:!0,http2:!1}):p=Deno.createHttpClient({cert:d,key:c}),m.info(`Successfully loaded mTLS certificate ${i}`),{certName:i,client:p}}catch(d){return m.warn(`Failed to load mTLS certificate ${i}: ${d}`),null}}))).filter(i=>i!==null)}o(vr,"loadMtlsClientEntries");function nt(r,e,t){let n=rt();return n.loadPromise||(n.loadPromise=vr(r,e,t).then(s=>{let i={},l={};for(let{certName:a,client:d}of s)i[a]=d,l[a]={fetch:o((c,p)=>{let g={...p??{},client:d};return Sr(c,g)},"fetch")};return n.clientsByName=i,n.bindingsByName=l,globalThis.managedDedicatedMtlsClients=i,globalThis.managedDedicatedMtlsBindings=l,i}).catch(s=>{throw n.loadPromise=void 0,s})),n.loadPromise}o(nt,"initializeGlobalMtlsClients");function ot(){let r=rt();for(let e of Object.values(r.clientsByName))e.close();r.clientsByName={},r.bindingsByName={},globalThis.managedDedicatedMtlsClients=r.clientsByName,globalThis.managedDedicatedMtlsBindings=r.bindingsByName,r.loadPromise=void 0}o(ot,"closeGlobalMtlsClients");var Pr=/^(?:-(?:(?<doubleDash>-)(?<negated>no-)?)?)(?<key>.+?)(?:=(?<value>.+?))?$/s,Or=/[A-Za-z]/,Dr=/-?\d+(\.\d*)?(e-?\d+)?$/,kr=/^(-|--)[^-]/,Mr=/=(?<value>.+)/,Lr=/^--[^=]+$/,Hr=/\W/,Ir=/\S/;function st(r){return Ir.test(r)&&Number.isFinite(Number(r))}o(st,"isNumber");function j(r,e,t,n=!1){e=[...e];let s=e.pop();if(e.forEach(i=>r=r[i]??={}),n){let i=r[s];if(Array.isArray(i)){i.push(t);return}t=i?[i,t]:[t]}r[s]=t}o(j,"setNested");function ve(r,e){for(let t of e){let n=r[t];if(!Object.hasOwn(r,t))return!1;r=n}return!0}o(ve,"hasNested");function it(r,e,t){let n=r.get(t);if(n===void 0)return!1;for(let s of n)if(e.has(s))return!0;return!1}o(it,"aliasIsBoolean");function at(r){return r==="true"||r==="false"}o(at,"isBooleanString");function Pe(r){return r!=="false"}o(Pe,"parseBooleanString");function lt(r,e){let{"--":t=!1,alias:n={},boolean:s=!1,default:i={},stopEarly:l=!1,string:a=[],collect:d=[],negatable:c=[],unknown:p=o(u=>u,"unknownFn")}=e??{},g=new Map,h=new Set,C=new Set,E=new Set,w=new Set,v=!1;if(n)for(let[u,f]of Object.entries(n)){if(f===void 0)throw new TypeError("Alias value must be defined");let y=Array.isArray(f)?f:[f];g.set(u,new Set(y)),y.forEach(I=>g.set(I,new Set([u,...y.filter(G=>G!==I)])))}if(s)if(typeof s=="boolean")v=s;else{let u=Array.isArray(s)?s:[s];for(let f of u.filter(Boolean))h.add(f),g.get(f)?.forEach(y=>{h.add(y)})}if(a){let u=Array.isArray(a)?a:[a];for(let f of u.filter(Boolean))C.add(f),g.get(f)?.forEach(y=>C.add(y))}if(d){let u=Array.isArray(d)?d:[d];for(let f of u.filter(Boolean))E.add(f),g.get(f)?.forEach(y=>E.add(y))}if(c){let u=Array.isArray(c)?c:[c];for(let f of u.filter(Boolean))w.add(f),g.get(f)?.forEach(y=>w.add(y))}let x={_:[]};function A(u,f,y,I){if(!h.has(u)&&!C.has(u)&&!g.has(u)&&!(v&&Lr.test(y))&&p?.(y,u,f)===!1)return;typeof f=="string"&&!C.has(u)&&(f=st(f)?Number(f):f);let G=I&&E.has(u);j(x,u.split("."),f,G),g.get(u)?.forEach(b=>{j(x,b.split("."),f,G)})}o(A,"setArgument");let S=[],O=r.indexOf("--");O!==-1&&(S=r.slice(O+1),r=r.slice(0,O));e:for(let u=0;u<r.length;u++){let f=r[u],y=f.match(Pr)?.groups;if(y){let{doubleDash:I,negated:G}=y,b=y.key,L=y.value;if(I){if(L){h.has(b)&&(L=Pe(L)),A(b,L,f,!0);continue}if(G){if(w.has(b)){A(b,!1,f,!1);continue}b=`no-${b}`}let D=r[u+1];if(D){if(!h.has(b)&&!v&&!D.startsWith("-")&&(!g.has(b)||!it(g,h,b))){L=D,u++,A(b,L,f,!0);continue}if(at(D)){L=Pe(D),u++,A(b,L,f,!0);continue}}L=C.has(b)?"":!0,A(b,L,f,!0);continue}let Oe=f.slice(1,-1).split("");for(let[D,U]of Oe.entries()){let Z=f.slice(D+2);if(Z==="-"){A(U,Z,f,!0);continue}if(Or.test(U)){let De=Mr.exec(Z)?.groups;if(De){A(U,De.value,f,!0);continue e}if(Dr.test(Z)){A(U,Z,f,!0);continue e}}if(Oe[D+1]?.match(Hr)){A(U,f.slice(D+2),f,!0);continue e}A(U,C.has(U)?"":!0,f,!0)}if(b=f.slice(-1),b==="-")continue;let K=r[u+1];if(K){if(!kr.test(K)&&!h.has(b)&&(!g.has(b)||!it(g,h,b))){A(b,K,f,!0),u++;continue}if(at(K)){let D=Pe(K);A(b,D,f,!0),u++;continue}}A(b,C.has(b)?"":!0,f,!0);continue}if(p?.(f)!==!1&&x._.push(C.has("_")||!st(f)?f:Number(f)),l){x._.push(...r.slice(u+1));break}}for(let[u,f]of Object.entries(i)){let y=u.split(".");ve(x,y)||(j(x,y,f),g.get(u)?.forEach(I=>j(x,I.split("."),f)))}for(let u of h.keys()){let f=u.split(".");if(!ve(x,f)){let y=E.has(u)?[]:!1;j(x,f,y)}}for(let u of C.keys()){let f=u.split(".");!ve(x,f)&&E.has(u)&&j(x,f,[])}return t?x["--"]=S:x._.push(...S),x}o(lt,"parseArgs");var ct="__ZUPLO_MTLS_CLIENT_CERT_NAMES",dt="__ZUPLO_MTLS_CLIENT_CERT_BASE_DIR";function Br(r){return r?[...new Set(r.split(",").map(e=>e.trim()).filter(e=>e.length>0))]:[]}o(Br,"getMtlsCertNames");async function $r(){let r;m.debug("Starting Zeno server...");let e=lt(Deno.args,{boolean:["help"],string:["port","dir","metrics-port"],default:{port:9e3}}),t=Number(e.port);(isNaN(t)||t<1||t>65535)&&(m.error(`Invalid port: ${e.port}. Port must be a number between 1 and 65535.`),Deno.exit(1));let n=t,s;try{s=Ve({port:n,flag:e["metrics-port"],env:Deno.env.get(W)})}catch(i){m.error(i.message),Deno.exit(1)}try{let i=e.dir?e.dir:Deno.cwd(),l=N(i,"dist","worker.js"),a;Deno.build.standalone?a=await Se(qe()):a=await Se(l);let d=await Be(i),c=tt(i);c?.allowFetchHostHeaderOverride&&(r=Ye());let p=Br(d[ct]),g=d[dt];g&&p.length>0&&(m.info(`Initializing ${p.length} mTLS client(s)`),await nt(g,p,c?.allowFetchHostHeaderOverride??!1)),await new fe({port:n,metricsPort:s,workerModule:a,env:d}).start()}catch(i){m.error("Failed to start server:",i)}finally{ot(),r&&r.close()}}o($r,"main");import.meta.main&&await $r();export{$r as main};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@zuplo/graphql",
3
3
  "type": "module",
4
- "version": "7.11.6",
4
+ "version": "7.11.8",
5
5
  "repository": "https://github.com/zuplo/zuplo",
6
6
  "author": "Zuplo, Inc.",
7
7
  "exports": {
@@ -2,7 +2,7 @@
2
2
  "name": "@zuplo/openapi-tools",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "7.11.6",
5
+ "version": "7.11.8",
6
6
  "description": "Tooling for OpenAPI files",
7
7
  "repository": {
8
8
  "type": "git",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@zuplo/otel",
3
3
  "type": "module",
4
- "version": "7.11.6",
4
+ "version": "7.11.8",
5
5
  "repository": "https://github.com/zuplo/zuplo",
6
6
  "author": "Zuplo, Inc.",
7
7
  "exports": {
@@ -58,7 +58,7 @@ import{c as Xe,d as ET,e as $r,f as je,h as dy,i as py}from"./chunk-NUVXDVLJ.js"
58
58
  </div>
59
59
  </body>
60
60
  </html>
61
- `,sP=i((t,e)=>{let n=O.instance.deploymentName,o=O.instance.devPortalBaseUrl,r=i(async(c,u)=>{if(O.instance.isLocalDevelopment)return new Response(Mj,{headers:{"content-type":"text/html"}});if(!n)return G.internalServerError(c,u,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let l=new URL(c.url),d=rP(o,c.headers),p=new URL(`${l.pathname}${l.search}`,d),{headers:f,method:h,body:y}=c,w=O.instance.accountName;w&&f.set(_j,w);let R=O.instance.projectName;return R&&f.set(xj,R),f.set(Aj,n),f.set(kj,l.host),f.set(Oj,O.instance.build.BUILD_ID),await J.fetch(p.toString(),{headers:f,method:h,body:y,redirect:"manual"})},"devPortalRoute"),s=new an({processors:[jn,ym],handler:r}),a=new Yt({label:"SYSTEM_API_DOCS_V3_ROUTE",methods:["GET","PUT","POST","DELETE","PATCH","HEAD"],path:`(${e}|/_next)(.*)`,systemRouteName:"developer-portal"});t.addRoute(a,s.execute)},"registerDevPortalV3Route"),aP=i((t,e)=>{let n=i(async s=>{let a=new URL(s.url);return a.pathname=`${e}${a.pathname.substring(iP.length)}`,Response.redirect(a.toString(),302)},"devPortalRedirectRoute"),o=new an({processors:[jn],handler:n}),r=new Yt({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${iP}(.*)`,systemRouteName:"developer-portal-legacy"});t.addRoute(r,o.execute)},"registerDevPortalLegacyRedirectRoute");var fb=0,uu=class{static{i(this,"CoreLogger")}constructor(e,n,o,r,s){this.#o=n,this.#n=o??"local",this.#r=r,this.#i=s,this.#e(e)}#e=i(e=>{let n=["error","warn","info","debug"],o=!1,r=i(()=>{},"emptyFunction"),s=i((a,c)=>{this.#i.forEach(u=>{u.log(a,c)})},"pushFunction");n.forEach(a=>{this.#t[a]=o?r:s,a==e&&(o=!0)})},"#setupMethods");#t={};#o;#n;#r;#i;log(e,n,o,r,s,a){fb>=Number.MAX_SAFE_INTEGER&&(fb=0);let c={logId:crypto.randomUUID(),requestId:o,rayId:r,level:e,logSource:n,messages:s,timestamp:new Date,logOwner:this.#o,loggingId:this.#n,buildId:this.#r,vectorClock:fb++};this.#t[e](c,a)}};var Rm=class{static{i(this,"LoggingContext")}constructor(e,n,o,r){this.#e=e,this.custom=n,this.originalRequest=o,this.route=r}#e;custom;originalRequest;route;properties={};waitUntil=i(e=>{this.#e.waitUntil(e)},"waitUntil");setProperties(e){Object.assign(this.properties,e)}};var cP={maxKeys:64,maxKeyLength:128,maxValueLength:2048,maxKeysPerCall:256,maxReportedProblems:10},uP=64;function lP(t,e){let n=new gb(cP.maxReportedProblems),o;try{o=Array.isArray(e)}catch(p){return n.add(()=>`could not read properties: ${hb(p)}`),n.toArray()}if(e===null||typeof e!="object"||o)return n.add(()=>`expected an object of properties, got ${o?"an array":typeof e}`),n.toArray();let r;try{r=Object.keys(e)}catch(p){return n.add(()=>`could not read properties: ${hb(p)}`),n.toArray()}let{maxKeys:s,maxKeyLength:a,maxValueLength:c,maxKeysPerCall:u}=cP,l=0;for(let p=0;p<r.length;p++){let f=r[p];if(p>=u&&!t.has(f)){l++;continue}let h;try{h=e[f]}catch(w){n.add(()=>`could not read property ${wm(f)}: ${hb(w)}`);continue}if(h==null)continue;if(f.length===0||f.length>a){n.add(()=>`dropped a property whose key is ${f.length===0?"empty":`longer than ${a} characters`}`);continue}let y;if(typeof h=="string")y=h;else if(typeof h=="number"||typeof h=="boolean")y=String(h);else{n.add(()=>`dropped property ${wm(f)}: value must be a string, number or boolean, got ${typeof h}`);continue}if(!t.has(f)&&t.size>=s){n.add(()=>`dropped property ${wm(f)}: a request can have at most ${s} properties`);continue}y.length>c&&(n.add(()=>`truncated property ${wm(f)} to ${c} characters`),y=y.slice(0,c)),t.set(f,y)}let d=n.toArray();return l>0&&d.push(`ignored ${l} new keys past the first ${u} of one call`),d}i(lP,"mergeRequestLogProperties");var gb=class{static{i(this,"ProblemList")}#e;#t=[];#o=0;constructor(e){this.#e=e}add(e){this.#t.length<this.#e?this.#t.push(e()):this.#o++}toArray(){return this.#o>0?[...this.#t,`${this.#o} more problems not shown`]:[...this.#t]}};function wm(t){return`'${dP(t)}'`}i(wm,"quote");function dP(t){return t.length>uP?`${t.slice(0,uP)}...`:t}i(dP,"truncate");function hb(t){try{let e=t instanceof Error?t.message:String(t);return typeof e=="string"?dP(e):"unknown error"}catch{return"unknown error"}}i(hb,"describeError");var lu=class{static{i(this,"RequestLogger")}constructor(e,n,o,r){this.#t=e,this.#o=n,this.#n=o,this.#r=r}#e="request";#t;#o;#n;#r;debug=i((...e)=>{this.#n.log("debug",this.#e,this.#t,this.#o,e,this.#r)},"debug");info=i((...e)=>{this.#n.log("info",this.#e,this.#t,this.#o,e,this.#r)},"info");log=i((...e)=>{this.#n.log("info",this.#e,this.#t,this.#o,e,this.#r)},"log");warn=i((...e)=>{this.#n.log("warn",this.#e,this.#t,this.#o,e,this.#r)},"warn");error=i((...e)=>{this.#n.log("error",this.#e,this.#t,this.#o,e,this.#r)},"error");setLogProperties=i(e=>{this.#r.setProperties(e)},"setLogProperties");#i;#s;#a=!1;bindRequestLogProperties=i((e,n)=>{this.#i=e,this.#s=n},"bindRequestLogProperties");setRequestProperties=i(e=>{if(!this.#i)return;let n;try{n=lP(this.#i,e)}catch{n=["could not read properties"]}if(n.length>0&&!this.#a){this.#a=!0;try{this.#s?.warn(`context.log.setRequestProperties: ${n.join("; ")}. Further problems on this request are not logged.`)}catch{}}},"setRequestProperties")};var Sm="gcp";function Cm(t){let e={allMessages:Po(t.messages)},n="zuplo-production",o=zs(e.allMessages),r={logName:`projects/${n}/logs/runtime-user`,message:o,severity:Ny[t.level],timestamp:t.timestamp,"logging.googleapis.com/labels":{buildId:t.buildId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},"logging.googleapis.com/trace":`projects/${n}/traces/${t.requestId}`,allMessages:e.allMessages};return t.rayId&&(r["logging.googleapis.com/labels"].rayId=t.rayId),r}i(Cm,"gcpLogFormat");var du=class{static{i(this,"ConsoleTransport")}constructor(e,n){this.#e=e??J.console,this.#t=n}#e;#t;log(e,n){if(this.#t===Sm){if(e.messages.length===0)return;this.#e[e.level](Cm(e))}else{let o={...e,url:n.originalRequest.url,method:n.originalRequest.method,route:n.route.pathPattern??n.route.path,messages:Po(e.messages)};this.#e[e.level](JSON.stringify(o))}}};import{logs as Lj}from"@opentelemetry/api-logs";var Nj="zuplo";function Uj(t){return{timestamp:t.timestamp,observedTimestamp:t.observerdTimestamp,severityText:t.severityText,severityNumber:t.severityNumber,body:t.body,attributes:t.attributes}}i(Uj,"unifiedLogEntryToLogRecord");var vm=class{static{i(this,"OTelTransport")}log(e,n){let o=Lj.getLogger(Nj),r=em(O.instance),s=Uj(r(e));n.properties&&(s.attributes=Object.assign(s.attributes??{},n.properties)),o.emit(s)}};var pu=class{static{i(this,"ProcessTransport")}constructor(e,n){this.#e=e,this.#t=n}#e;#t;log(e){if(this.#t===Sm){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Cm(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId,vectorClock:e.vectorClock}])}};var yb=st("zuplo:logging"),Im=class t{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:n}){this.systemCoreLogger=e,this.userCoreLogger=n}static async init(e){let n=await t.setupSystemCoreLogger(O.instance,e),o=await t.setupUserCoreLogger(O.instance,e);return new t({systemCoreLogger:n,userCoreLogger:o})}static async setupSystemCoreLogger(e,n){let{build:o}=e;yb("Gateway.setupSystemCoreLogger");let r=[],s=n.getService(jp);return s?r.push(new pu(s.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new du(J.console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new Wc(e)),await Promise.all(r.map(async a=>{a.init&&await a.init()})),new uu(e.systemLogLevel,"system",e.loggingId,o.BUILD_ID,r)}static async setupUserCoreLogger(e,n){yb("Gateway.setupUserCoreLogger");let o=[],{runtime:r,build:s}=e,a=n.getService(jp);if(a&&a.captureUserLogs===!0?o.push(new pu(a.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new du(J.console,e.logFormat)),(e.isCloudflare||e.isManagedDedicated)&&e.deploymentName&&e.remoteLogToken&&o.push(new Wc(e)),!O.instance.build.COMPATIBILITY_FLAGS.removeLegacyLogInitialization&&(r.GCP_USER_LOG_NAME&&r.GCP_USER_LOG_SVC_ACCT_JSON&&(de("logging.google.legacy-initialization"),o.push(new Yc({serviceAccountJson:r.GCP_USER_LOG_SVC_ACCT_JSON,logName:r.GCP_USER_LOG_NAME}))),r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY)){de("logging.datadog.legacy-initialization");let c=r.ZUPLO_USER_LOGGER_DATA_DOG_URL;o.push(new Qc({apiKey:r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:c}))}return to.forEach(c=>{c instanceof _t&&o.push(c.getTransport()),c instanceof Pi&&o.push(new vm)}),await Promise.all(o.map(async c=>{c.init&&await c.init()})),new uu(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,o)}createRequestLoggers(e,n,o,r,s,a){yb("Gateway.createRequestLoggers");let c=new Rm(o,r,s,a),u=new lu(e,n,this.systemCoreLogger,c);return{userRequestLogger:new lu(e,n,this.userCoreLogger,c),systemRequestLogger:u}}};var pP=i(async(t,e,n)=>{let o=await n(t),r=e.analyticsContext.flushAnalyticsEvents();return Br()?.pushEvents(r,e),o},"analyticsEventProcessor");function Ws(t,e){if(!!!t)throw new Error(e)}i(Ws,"devAssert");function mP(t){return typeof t=="object"&&t!==null}i(mP,"isObjectLike");function fP(t,e){if(!!!t)throw new Error(e??"Unexpected invariant triggered.")}i(fP,"invariant");var qj=/\r\n|[\n\r]/g;function Ys(t,e){let n=0,o=1;for(let r of t.body.matchAll(qj)){if(typeof r.index=="number"||fP(!1),r.index>=e)break;n=r.index+r[0].length,o+=1}return{line:o,column:e+1-n}}i(Ys,"getLocation");function bb(t){return Tm(t.source,Ys(t.source,t.start))}i(bb,"printLocation");function Tm(t,e){let n=t.locationOffset.column-1,o="".padStart(n)+t.body,r=e.line-1,s=t.locationOffset.line-1,a=e.line+s,c=e.line===1?n:0,u=e.column+c,l=`${t.name}:${a}:${u}
61
+ `,sP=i((t,e)=>{let n=O.instance.deploymentName,o=O.instance.devPortalBaseUrl,r=i(async(c,u)=>{if(O.instance.isLocalDevelopment)return new Response(Mj,{headers:{"content-type":"text/html"}});if(!n)return G.internalServerError(c,u,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let l=new URL(c.url),d=rP(o,c.headers),p=new URL(`${l.pathname}${l.search}`,d),{headers:f,method:h,body:y}=c,w=O.instance.accountName;w&&f.set(_j,w);let R=O.instance.projectName;return R&&f.set(xj,R),f.set(Aj,n),f.set(kj,l.host),f.set(Oj,O.instance.build.BUILD_ID),await J.fetch(p.toString(),{headers:f,method:h,body:y,redirect:"manual"})},"devPortalRoute"),s=new an({processors:[jn,ym],handler:r}),a=new Yt({label:"SYSTEM_API_DOCS_V3_ROUTE",methods:["GET","PUT","POST","DELETE","PATCH","HEAD"],path:`(${e}|/_next)(.*)`,systemRouteName:"developer-portal"});t.addRoute(a,s.execute)},"registerDevPortalV3Route"),aP=i((t,e)=>{let n=i(async s=>{let a=new URL(s.url);return a.pathname=`${e}${a.pathname.substring(iP.length)}`,Response.redirect(a.toString(),302)},"devPortalRedirectRoute"),o=new an({processors:[jn],handler:n}),r=new Yt({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${iP}(.*)`,systemRouteName:"developer-portal-legacy"});t.addRoute(r,o.execute)},"registerDevPortalLegacyRedirectRoute");var fb=0,uu=class{static{i(this,"CoreLogger")}constructor(e,n,o,r,s){this.#o=n,this.#n=o??"local",this.#r=r,this.#i=s,this.#e(e)}#e=i(e=>{let n=["error","warn","info","debug"],o=!1,r=i(()=>{},"emptyFunction"),s=i((a,c)=>{this.#i.forEach(u=>{u.log(a,c)})},"pushFunction");n.forEach(a=>{this.#t[a]=o?r:s,a==e&&(o=!0)})},"#setupMethods");#t={};#o;#n;#r;#i;log(e,n,o,r,s,a){fb>=Number.MAX_SAFE_INTEGER&&(fb=0);let c={logId:crypto.randomUUID(),requestId:o,rayId:r,level:e,logSource:n,messages:s,timestamp:new Date,logOwner:this.#o,loggingId:this.#n,buildId:this.#r,vectorClock:fb++};this.#t[e](c,a)}};var Rm=class{static{i(this,"LoggingContext")}constructor(e,n,o,r){this.#e=e,this.custom=n,this.originalRequest=o,this.route=r}#e;custom;originalRequest;route;properties={};waitUntil=i(e=>{this.#e.waitUntil(e)},"waitUntil");setProperties(e){Object.assign(this.properties,e)}};var cP={maxKeys:64,maxKeyLength:128,maxValueLength:2048,maxKeysPerCall:256,maxReportedProblems:10},uP=64;function lP(t,e){let n=new gb(cP.maxReportedProblems),o;try{o=Array.isArray(e)}catch(p){return n.add(()=>`could not read properties: ${hb(p)}`),n.toArray()}if(e===null||typeof e!="object"||o)return n.add(()=>`expected an object of properties, got ${o?"an array":typeof e}`),n.toArray();let r;try{r=Object.keys(e)}catch(p){return n.add(()=>`could not read properties: ${hb(p)}`),n.toArray()}let{maxKeys:s,maxKeyLength:a,maxValueLength:c,maxKeysPerCall:u}=cP,l=0;for(let p=0;p<r.length;p++){let f=r[p];if(p>=u&&!t.has(f)){l++;continue}let h;try{h=e[f]}catch(w){n.add(()=>`could not read property ${wm(f)}: ${hb(w)}`);continue}if(h==null)continue;if(f==="__proto__"){n.add(()=>"dropped property '__proto__': the key is reserved");continue}if(f.length===0||f.length>a){n.add(()=>`dropped a property whose key is ${f.length===0?"empty":`longer than ${a} characters`}`);continue}let y;if(typeof h=="string")y=h;else if(typeof h=="number"||typeof h=="boolean")y=String(h);else{n.add(()=>`dropped property ${wm(f)}: value must be a string, number or boolean, got ${typeof h}`);continue}if(!t.has(f)&&t.size>=s){n.add(()=>`dropped property ${wm(f)}: a request can have at most ${s} properties`);continue}y.length>c&&(n.add(()=>`truncated property ${wm(f)} to ${c} characters`),y=y.slice(0,c)),t.set(f,y)}let d=n.toArray();return l>0&&d.push(`ignored ${l} new keys past the first ${u} of one call`),d}i(lP,"mergeRequestLogProperties");var gb=class{static{i(this,"ProblemList")}#e;#t=[];#o=0;constructor(e){this.#e=e}add(e){this.#t.length<this.#e?this.#t.push(e()):this.#o++}toArray(){return this.#o>0?[...this.#t,`${this.#o} more problems not shown`]:[...this.#t]}};function wm(t){return`'${dP(t)}'`}i(wm,"quote");function dP(t){return t.length>uP?`${t.slice(0,uP)}...`:t}i(dP,"truncate");function hb(t){try{let e=t instanceof Error?t.message:String(t);return typeof e=="string"?dP(e):"unknown error"}catch{return"unknown error"}}i(hb,"describeError");var lu=class{static{i(this,"RequestLogger")}constructor(e,n,o,r){this.#t=e,this.#o=n,this.#n=o,this.#r=r}#e="request";#t;#o;#n;#r;debug=i((...e)=>{this.#n.log("debug",this.#e,this.#t,this.#o,e,this.#r)},"debug");info=i((...e)=>{this.#n.log("info",this.#e,this.#t,this.#o,e,this.#r)},"info");log=i((...e)=>{this.#n.log("info",this.#e,this.#t,this.#o,e,this.#r)},"log");warn=i((...e)=>{this.#n.log("warn",this.#e,this.#t,this.#o,e,this.#r)},"warn");error=i((...e)=>{this.#n.log("error",this.#e,this.#t,this.#o,e,this.#r)},"error");setLogProperties=i(e=>{this.#r.setProperties(e),this.#c(e)},"setLogProperties");#i;#s;#a=!1;bindRequestLogProperties=i((e,n)=>{this.#i=e,this.#s=n},"bindRequestLogProperties");#c(e){if(!this.#i)return;let n;try{n=lP(this.#i,e)}catch{n=["could not read properties"]}if(n.length>0&&!this.#a){this.#a=!0;try{this.#s?.warn(`context.log.setLogProperties (request row): ${n.join("; ")}. Further problems on this request are not logged.`)}catch{}}}};var Sm="gcp";function Cm(t){let e={allMessages:Po(t.messages)},n="zuplo-production",o=zs(e.allMessages),r={logName:`projects/${n}/logs/runtime-user`,message:o,severity:Ny[t.level],timestamp:t.timestamp,"logging.googleapis.com/labels":{buildId:t.buildId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},"logging.googleapis.com/trace":`projects/${n}/traces/${t.requestId}`,allMessages:e.allMessages};return t.rayId&&(r["logging.googleapis.com/labels"].rayId=t.rayId),r}i(Cm,"gcpLogFormat");var du=class{static{i(this,"ConsoleTransport")}constructor(e,n){this.#e=e??J.console,this.#t=n}#e;#t;log(e,n){if(this.#t===Sm){if(e.messages.length===0)return;this.#e[e.level](Cm(e))}else{let o={...e,url:n.originalRequest.url,method:n.originalRequest.method,route:n.route.pathPattern??n.route.path,messages:Po(e.messages)};this.#e[e.level](JSON.stringify(o))}}};import{logs as Lj}from"@opentelemetry/api-logs";var Nj="zuplo";function Uj(t){return{timestamp:t.timestamp,observedTimestamp:t.observerdTimestamp,severityText:t.severityText,severityNumber:t.severityNumber,body:t.body,attributes:t.attributes}}i(Uj,"unifiedLogEntryToLogRecord");var vm=class{static{i(this,"OTelTransport")}log(e,n){let o=Lj.getLogger(Nj),r=em(O.instance),s=Uj(r(e));n.properties&&(s.attributes=Object.assign(s.attributes??{},n.properties)),o.emit(s)}};var pu=class{static{i(this,"ProcessTransport")}constructor(e,n){this.#e=e,this.#t=n}#e;#t;log(e){if(this.#t===Sm){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Cm(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId,vectorClock:e.vectorClock}])}};var yb=st("zuplo:logging"),Im=class t{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:n}){this.systemCoreLogger=e,this.userCoreLogger=n}static async init(e){let n=await t.setupSystemCoreLogger(O.instance,e),o=await t.setupUserCoreLogger(O.instance,e);return new t({systemCoreLogger:n,userCoreLogger:o})}static async setupSystemCoreLogger(e,n){let{build:o}=e;yb("Gateway.setupSystemCoreLogger");let r=[],s=n.getService(jp);return s?r.push(new pu(s.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new du(J.console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new Wc(e)),await Promise.all(r.map(async a=>{a.init&&await a.init()})),new uu(e.systemLogLevel,"system",e.loggingId,o.BUILD_ID,r)}static async setupUserCoreLogger(e,n){yb("Gateway.setupUserCoreLogger");let o=[],{runtime:r,build:s}=e,a=n.getService(jp);if(a&&a.captureUserLogs===!0?o.push(new pu(a.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new du(J.console,e.logFormat)),(e.isCloudflare||e.isManagedDedicated)&&e.deploymentName&&e.remoteLogToken&&o.push(new Wc(e)),!O.instance.build.COMPATIBILITY_FLAGS.removeLegacyLogInitialization&&(r.GCP_USER_LOG_NAME&&r.GCP_USER_LOG_SVC_ACCT_JSON&&(de("logging.google.legacy-initialization"),o.push(new Yc({serviceAccountJson:r.GCP_USER_LOG_SVC_ACCT_JSON,logName:r.GCP_USER_LOG_NAME}))),r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY)){de("logging.datadog.legacy-initialization");let c=r.ZUPLO_USER_LOGGER_DATA_DOG_URL;o.push(new Qc({apiKey:r.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:c}))}return to.forEach(c=>{c instanceof _t&&o.push(c.getTransport()),c instanceof Pi&&o.push(new vm)}),await Promise.all(o.map(async c=>{c.init&&await c.init()})),new uu(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,o)}createRequestLoggers(e,n,o,r,s,a){yb("Gateway.createRequestLoggers");let c=new Rm(o,r,s,a),u=new lu(e,n,this.systemCoreLogger,c);return{userRequestLogger:new lu(e,n,this.userCoreLogger,c),systemRequestLogger:u}}};var pP=i(async(t,e,n)=>{let o=await n(t),r=e.analyticsContext.flushAnalyticsEvents();return Br()?.pushEvents(r,e),o},"analyticsEventProcessor");function Ws(t,e){if(!!!t)throw new Error(e)}i(Ws,"devAssert");function mP(t){return typeof t=="object"&&t!==null}i(mP,"isObjectLike");function fP(t,e){if(!!!t)throw new Error(e??"Unexpected invariant triggered.")}i(fP,"invariant");var qj=/\r\n|[\n\r]/g;function Ys(t,e){let n=0,o=1;for(let r of t.body.matchAll(qj)){if(typeof r.index=="number"||fP(!1),r.index>=e)break;n=r.index+r[0].length,o+=1}return{line:o,column:e+1-n}}i(Ys,"getLocation");function bb(t){return Tm(t.source,Ys(t.source,t.start))}i(bb,"printLocation");function Tm(t,e){let n=t.locationOffset.column-1,o="".padStart(n)+t.body,r=e.line-1,s=t.locationOffset.line-1,a=e.line+s,c=e.line===1?n:0,u=e.column+c,l=`${t.name}:${a}:${u}
62
62
  `,d=o.split(/\r\n|[\n\r]/g),p=d[r];if(p.length>120){let f=Math.floor(u/80),h=u%80,y=[];for(let w=0;w<p.length;w+=80)y.push(p.slice(w,w+80));return l+hP([[`${a} |`,y[0]],...y.slice(1,f+1).map(w=>["|",w]),["|","^".padStart(h)],["|",y[f+1]]])}return l+hP([[`${a-1} |`,d[r-1]],[`${a} |`,p],["|","^".padStart(u)],[`${a+1} |`,d[r+1]]])}i(Tm,"printSourceLocation");function hP(t){let e=t.filter(([o,r])=>r!==void 0),n=Math.max(...e.map(([o])=>o.length));return e.map(([o,r])=>o.padStart(n)+(r?" "+r:"")).join(`
63
63
  `)}i(hP,"printPrefixedLines");function Dj(t){let e=t[0];return e==null||"kind"in e||"length"in e?{nodes:e,source:t[1],positions:t[2],path:t[3],originalError:t[4],extensions:t[5]}:e}i(Dj,"toNormalizedOptions");var er=class t extends Error{static{i(this,"GraphQLError")}constructor(e,...n){var o,r,s;let{nodes:a,source:c,positions:u,path:l,originalError:d,extensions:p}=Dj(n);super(e),this.name="GraphQLError",this.path=l??void 0,this.originalError=d??void 0,this.nodes=gP(Array.isArray(a)?a:a?[a]:void 0);let f=gP((o=this.nodes)===null||o===void 0?void 0:o.map(y=>y.loc).filter(y=>y!=null));this.source=c??(f==null||(r=f[0])===null||r===void 0?void 0:r.source),this.positions=u??f?.map(y=>y.start),this.locations=u&&c?u.map(y=>Ys(c,y)):f?.map(y=>Ys(y.source,y.start));let h=mP(d?.extensions)?d?.extensions:void 0;this.extensions=(s=p??h)!==null&&s!==void 0?s:Object.create(null),Object.defineProperties(this,{message:{writable:!0,enumerable:!0},name:{enumerable:!1},nodes:{enumerable:!1},source:{enumerable:!1},positions:{enumerable:!1},originalError:{enumerable:!1}}),d!=null&&d.stack?Object.defineProperty(this,"stack",{value:d.stack,writable:!0,configurable:!0}):Error.captureStackTrace?Error.captureStackTrace(this,t):Object.defineProperty(this,"stack",{value:Error().stack,writable:!0,configurable:!0})}get[Symbol.toStringTag](){return"GraphQLError"}toString(){let e=this.message;if(this.nodes)for(let n of this.nodes)n.loc&&(e+=`
64
64
 
@@ -408,5 +408,5 @@ Signature verification is impossible without access to the original signed mater
408
408
  `);let b=new v("!xml"),T=b,_="";this.matcher.reset(),this.entityExpansionCount=0,this.currentExpandedLength=0;let L=new E(this.options.processEntities);for(let k=0;k<g.length;k++)if(g[k]==="<")if(g[k+1]==="/"){let W=wn(g,">",k,"Closing Tag is not closed."),j=g.substring(k+2,W).trim();if(this.options.removeNSPrefix){let Ee=j.indexOf(":");Ee!==-1&&(j=j.substr(Ee+1))}j=Gn(this.options.transformTagName,j,"",this.options).tagName,T&&(_=this.saveTextToParentTag(_,T,this.matcher));let we=this.matcher.getCurrentTag();if(j&&this.options.unpairedTags.indexOf(j)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${j}>`);we&&this.options.unpairedTags.indexOf(we)!==-1&&(this.matcher.pop(),this.tagsNodeStack.pop()),this.matcher.pop(),this.isCurrentNodeStopNode=!1,T=this.tagsNodeStack.pop(),_="",k=W}else if(g[k+1]==="?"){let W=xn(g,k,!1,"?>");if(!W)throw new Error("Pi Tag is not closed.");if(_=this.saveTextToParentTag(_,T,this.matcher),!(this.options.ignoreDeclaration&&W.tagName==="?xml"||this.options.ignorePiTags)){let j=new v(W.tagName);j.add(this.options.textNodeName,""),W.tagName!==W.tagExp&&W.attrExpPresent&&(j[":@"]=this.buildAttributesMap(W.tagExp,this.matcher,W.tagName)),this.addChild(T,j,this.matcher,k)}k=W.closeIndex+1}else if(g.substr(k+1,3)==="!--"){let W=wn(g,"-->",k+4,"Comment is not closed.");if(this.options.commentPropName){let j=g.substring(k+4,W-2);_=this.saveTextToParentTag(_,T,this.matcher),T.add(this.options.commentPropName,[{[this.options.textNodeName]:j}])}k=W}else if(g.substr(k+1,2)==="!D"){let W=L.readDocType(g,k);this.docTypeEntities=W.entities,k=W.i}else if(g.substr(k+1,2)==="!["){let W=wn(g,"]]>",k,"CDATA is not closed.")-2,j=g.substring(k+9,W);_=this.saveTextToParentTag(_,T,this.matcher);let we=this.parseTextData(j,T.tagname,this.matcher,!0,!1,!0,!0);we==null&&(we=""),this.options.cdataPropName?T.add(this.options.cdataPropName,[{[this.options.textNodeName]:j}]):T.add(this.options.textNodeName,we),k=W+2}else{let W=xn(g,k,this.options.removeNSPrefix);if(!W){let on=g.substring(Math.max(0,k-50),Math.min(g.length,k+50));throw new Error(`readTagExp returned undefined at position ${k}. Context: "${on}"`)}let j=W.tagName,we=W.rawTagName,Ee=W.tagExp,ze=W.attrExpPresent,bt=W.closeIndex;if({tagName:j,tagExp:Ee}=Gn(this.options.transformTagName,j,Ee,this.options),this.options.strictReservedNames&&(j===this.options.commentPropName||j===this.options.cdataPropName||j===this.options.textNodeName||j===this.options.attributesGroupName))throw new Error(`Invalid tag name: ${j}`);T&&_&&T.tagname!=="!xml"&&(_=this.saveTextToParentTag(_,T,this.matcher,!1));let hn=T;hn&&this.options.unpairedTags.indexOf(hn.tagname)!==-1&&(T=this.tagsNodeStack.pop(),this.matcher.pop());let Mr=!1;Ee.length>0&&Ee.lastIndexOf("/")===Ee.length-1&&(Mr=!0,j[j.length-1]==="/"?(j=j.substr(0,j.length-1),Ee=j):Ee=Ee.substr(0,Ee.length-1),ze=j!==Ee);let Rt=null,Mn={},Lr;Lr=te(we),j!==b.tagname&&this.matcher.push(j,{},Lr),j!==Ee&&ze&&(Rt=this.buildAttributesMap(Ee,this.matcher,j),Rt&&(Mn=ie(Rt,this.options))),j!==b.tagname&&(this.isCurrentNodeStopNode=this.isItStopNode(this.stopNodeExpressions,this.matcher));let Cn=k;if(this.isCurrentNodeStopNode){let on="";if(Mr)k=W.closeIndex;else if(this.options.unpairedTags.indexOf(j)!==-1)k=W.closeIndex;else{let Ur=this.readStopNodeData(g,we,bt+1);if(!Ur)throw new Error(`Unexpected end of ${we}`);k=Ur.i,on=Ur.tagContent}let Nr=new v(j);Rt&&(Nr[":@"]=Rt),Nr.add(this.options.textNodeName,on),this.matcher.pop(),this.isCurrentNodeStopNode=!1,this.addChild(T,Nr,this.matcher,Cn)}else{if(Mr){({tagName:j,tagExp:Ee}=Gn(this.options.transformTagName,j,Ee,this.options));let on=new v(j);Rt&&(on[":@"]=Rt),this.addChild(T,on,this.matcher,Cn),this.matcher.pop(),this.isCurrentNodeStopNode=!1}else if(this.options.unpairedTags.indexOf(j)!==-1){let on=new v(j);Rt&&(on[":@"]=Rt),this.addChild(T,on,this.matcher,Cn),this.matcher.pop(),this.isCurrentNodeStopNode=!1,k=W.closeIndex;continue}else{let on=new v(j);if(this.tagsNodeStack.length>this.options.maxNestedTags)throw new Error("Maximum nested tags exceeded");this.tagsNodeStack.push(T),Rt&&(on[":@"]=Rt),this.addChild(T,on,this.matcher,Cn),T=on}_="",k=bt}}else _+=g[k];return b.child},"parseXml");function ce(g,b,T,_){this.options.captureMetaData||(_=void 0);let L=this.options.jPath?T.toString():T,k=this.options.updateTag(b.tagname,L,b[":@"]);k===!1||(typeof k=="string"&&(b.tagname=k),g.addChild(b,_))}i(ce,"addChild"),n(ce,"addChild");function ue(g,b,T){let _=this.options.processEntities;if(!_||!_.enabled)return g;if(_.allowedTags){let L=this.options.jPath?T.toString():T;if(!(Array.isArray(_.allowedTags)?_.allowedTags.includes(b):_.allowedTags(b,L)))return g}if(_.tagFilter){let L=this.options.jPath?T.toString():T;if(!_.tagFilter(b,L))return g}for(let L of Object.keys(this.docTypeEntities)){let k=this.docTypeEntities[L],ee=g.match(k.regx);if(ee){if(this.entityExpansionCount+=ee.length,_.maxTotalExpansions&&this.entityExpansionCount>_.maxTotalExpansions)throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${_.maxTotalExpansions}`);let W=g.length;if(g=g.replace(k.regx,k.val),_.maxExpandedLength&&(this.currentExpandedLength+=g.length-W,this.currentExpandedLength>_.maxExpandedLength))throw new Error(`Total expanded content size exceeded: ${this.currentExpandedLength} > ${_.maxExpandedLength}`)}}for(let L of Object.keys(this.lastEntities)){let k=this.lastEntities[L],ee=g.match(k.regex);if(ee&&(this.entityExpansionCount+=ee.length,_.maxTotalExpansions&&this.entityExpansionCount>_.maxTotalExpansions))throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${_.maxTotalExpansions}`);g=g.replace(k.regex,k.val)}if(g.indexOf("&")===-1)return g;if(this.options.htmlEntities)for(let L of Object.keys(this.htmlEntities)){let k=this.htmlEntities[L],ee=g.match(k.regex);if(ee&&(this.entityExpansionCount+=ee.length,_.maxTotalExpansions&&this.entityExpansionCount>_.maxTotalExpansions))throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${_.maxTotalExpansions}`);g=g.replace(k.regex,k.val)}return g=g.replace(this.ampEntity.regex,this.ampEntity.val),g}i(ue,"replaceEntitiesValue"),n(ue,"replaceEntitiesValue");function ke(g,b,T,_){return g&&(_===void 0&&(_=b.child.length===0),g=this.parseTextData(g,b.tagname,T,!1,b[":@"]?Object.keys(b[":@"]).length!==0:!1,_),g!==void 0&&g!==""&&b.add(this.options.textNodeName,g),g=""),g}i(ke,"saveTextToParentTag"),n(ke,"saveTextToParentTag");function xe(g,b){if(!g||g.length===0)return!1;for(let T=0;T<g.length;T++)if(b.matches(g[T]))return!0;return!1}i(xe,"isItStopNode"),n(xe,"isItStopNode");function $(g,b,T=">"){let _,L="";for(let k=b;k<g.length;k++){let ee=g[k];if(_)ee===_&&(_="");else if(ee==='"'||ee==="'")_=ee;else if(ee===T[0])if(T[1]){if(g[k+1]===T[1])return{data:L,index:k}}else return{data:L,index:k};else ee===" "&&(ee=" ");L+=ee}}i($,"tagExpWithClosingIndex"),n($,"tagExpWithClosingIndex");function wn(g,b,T,_){let L=g.indexOf(b,T);if(L===-1)throw new Error(_);return L+b.length-1}i(wn,"findClosingIndex"),n(wn,"findClosingIndex");function xn(g,b,T,_=">"){let L=$(g,b+1,_);if(!L)return;let k=L.data,ee=L.index,W=k.search(/\s/),j=k,we=!0;W!==-1&&(j=k.substring(0,W),k=k.substring(W+1).trimStart());let Ee=j;if(T){let ze=j.indexOf(":");ze!==-1&&(j=j.substr(ze+1),we=j!==L.data.substr(ze+1))}return{tagName:j,tagExp:k,closeIndex:ee,attrExpPresent:we,rawTagName:Ee}}i(xn,"readTagExp"),n(xn,"readTagExp");function So(g,b,T){let _=T,L=1;for(;T<g.length;T++)if(g[T]==="<")if(g[T+1]==="/"){let k=wn(g,">",T,`${b} is not closed`);if(g.substring(T+2,k).trim()===b&&(L--,L===0))return{tagContent:g.substring(_,T),i:k};T=k}else if(g[T+1]==="?")T=wn(g,"?>",T+1,"StopNode is not closed.");else if(g.substr(T+1,3)==="!--")T=wn(g,"-->",T+3,"StopNode is not closed.");else if(g.substr(T+1,2)==="![")T=wn(g,"]]>",T,"StopNode is not closed.")-2;else{let k=xn(g,T,">");k&&((k&&k.tagName)===b&&k.tagExp[k.tagExp.length-1]!=="/"&&L++,T=k.closeIndex)}}i(So,"readStopNodeData"),n(So,"readStopNodeData");function Qn(g,b,T){if(b&&typeof g=="string"){let _=g.trim();return _==="true"?!0:_==="false"?!1:Ct(g,T)}else return l(g)?g:""}i(Qn,"parseValue"),n(Qn,"parseValue");function Ho(g,b,T){let _=Number.parseInt(g,b);return _>=0&&_<=1114111?String.fromCodePoint(_):T+g+";"}i(Ho,"fromCodePoint"),n(Ho,"fromCodePoint");function Gn(g,b,T,_){if(g){let L=g(b);T===b&&(T=L),b=L}return b=Fo(b,_),{tagName:b,tagExp:T}}i(Gn,"transformTagName"),n(Gn,"transformTagName");function Fo(g,b){if(p.includes(g))throw new Error(`[SECURITY] Invalid name: "${g}" is a reserved JavaScript keyword that could cause prototype pollution`);return d.includes(g)?b.onDangerousProperty(g):g}i(Fo,"sanitizeName"),n(Fo,"sanitizeName");var Sn=v.getMetaDataSymbol();function Go(g,b){if(!g||typeof g!="object")return{};if(!b)return g;let T={};for(let _ in g)if(_.startsWith(b)){let L=_.substring(b.length);T[L]=g[_]}else T[_]=g[_];return T}i(Go,"stripAttributePrefix"),n(Go,"stripAttributePrefix");function Bo(g,b,T){return co(g,b,T)}i(Bo,"prettify"),n(Bo,"prettify");function co(g,b,T){let _,L={};for(let k=0;k<g.length;k++){let ee=g[k],W=Er(ee);if(W!==void 0&&W!==b.textNodeName){let j=Go(ee[":@"]||{},b.attributeNamePrefix);T.push(W,j)}if(W===b.textNodeName)_===void 0?_=ee[W]:_+=""+ee[W];else{if(W===void 0)continue;if(ee[W]){let j=co(ee[W],b,T),we=Co(j,b);if(ee[":@"]?Zo(j,ee[":@"],T,b):Object.keys(j).length===1&&j[b.textNodeName]!==void 0&&!b.alwaysCreateTextNode?j=j[b.textNodeName]:Object.keys(j).length===0&&(b.alwaysCreateTextNode?j[b.textNodeName]="":j=""),ee[Sn]!==void 0&&typeof j=="object"&&j!==null&&(j[Sn]=ee[Sn]),L[W]!==void 0&&Object.prototype.hasOwnProperty.call(L,W))Array.isArray(L[W])||(L[W]=[L[W]]),L[W].push(j);else{let Ee=b.jPath?T.toString():T;b.isArray(W,Ee,we)?L[W]=[j]:L[W]=j}W!==void 0&&W!==b.textNodeName&&T.pop()}}}return typeof _=="string"?_.length>0&&(L[b.textNodeName]=_):_!==void 0&&(L[b.textNodeName]=_),L}i(co,"compress"),n(co,"compress");function Er(g){let b=Object.keys(g);for(let T=0;T<b.length;T++){let _=b[T];if(_!==":@")return _}}i(Er,"propName"),n(Er,"propName");function Zo(g,b,T,_){if(b){let L=Object.keys(b),k=L.length;for(let ee=0;ee<k;ee++){let W=L[ee],j=W.startsWith(_.attributeNamePrefix)?W.substring(_.attributeNamePrefix.length):W,we=_.jPath?T.toString()+"."+j:T;_.isArray(W,we,!0,!0)?g[W]=[b[W]]:g[W]=b[W]}}}i(Zo,"assignAttributes"),n(Zo,"assignAttributes");function Co(g,b){let{textNodeName:T}=b,_=Object.keys(g).length;return!!(_===0||_===1&&(g[T]||typeof g[T]=="boolean"||g[T]===0))}i(Co,"isLeafTag"),n(Co,"isLeafTag");var Pr={allowBooleanAttributes:!1,unpairedTags:[]};function Vo(g,b){b=Object.assign({},Pr,b);let T=[],_=!1,L=!1;g[0]==="\uFEFF"&&(g=g.substr(1));for(let k=0;k<g.length;k++)if(g[k]==="<"&&g[k+1]==="?"){if(k+=2,k=Kt(g,k),k.err)return k}else if(g[k]==="<"){let ee=k;if(k++,g[k]==="!"){k=Jo(g,k);continue}else{let W=!1;g[k]==="/"&&(W=!0,k++);let j="";for(;k<g.length&&g[k]!==">"&&g[k]!==" "&&g[k]!==" "&&g[k]!==`
409
409
  `&&g[k]!=="\r";k++)j+=g[k];if(j=j.trim(),j[j.length-1]==="/"&&(j=j.substring(0,j.length-1),k--),!hi(j)){let ze;return j.trim().length===0?ze="Invalid space after '<'.":ze="Tag '"+j+"' is an invalid name.",ut("InvalidTag",ze,Ut(g,k))}let we=kr(g,k);if(we===!1)return ut("InvalidAttr","Attributes for '"+j+"' have open quote.",Ut(g,k));let Ee=we.value;if(k=we.index,Ee[Ee.length-1]==="/"){let ze=k-Ee.length;Ee=Ee.substring(0,Ee.length-1);let bt=Ko(Ee,b);if(bt===!0)_=!0;else return ut(bt.err.code,bt.err.msg,Ut(g,ze+bt.err.line))}else if(W)if(we.tagClosed){if(Ee.trim().length>0)return ut("InvalidTag","Closing tag '"+j+"' can't have attributes or invalid starting.",Ut(g,ee));if(T.length===0)return ut("InvalidTag","Closing tag '"+j+"' has not been opened.",Ut(g,ee));{let ze=T.pop();if(j!==ze.tagName){let bt=Ut(g,ze.tagStartPos);return ut("InvalidTag","Expected closing tag '"+ze.tagName+"' (opened in line "+bt.line+", col "+bt.col+") instead of closing tag '"+j+"'.",Ut(g,ee))}T.length==0&&(L=!0)}}else return ut("InvalidTag","Closing tag '"+j+"' doesn't have proper closing.",Ut(g,k));else{let ze=Ko(Ee,b);if(ze!==!0)return ut(ze.err.code,ze.err.msg,Ut(g,k-Ee.length+ze.err.line));if(L===!0)return ut("InvalidXml","Multiple possible root nodes found.",Ut(g,k));b.unpairedTags.indexOf(j)!==-1||T.push({tagName:j,tagStartPos:ee}),_=!0}for(k++;k<g.length;k++)if(g[k]==="<")if(g[k+1]==="!"){k++,k=Jo(g,k);continue}else if(g[k+1]==="?"){if(k=Kt(g,++k),k.err)return k}else break;else if(g[k]==="&"){let ze=xr(g,k);if(ze==-1)return ut("InvalidChar","char '&' is not expected.",Ut(g,k));k=ze}else if(L===!0&&!vo(g[k]))return ut("InvalidXml","Extra text at the end",Ut(g,k));g[k]==="<"&&k--}}else{if(vo(g[k]))continue;return ut("InvalidChar","char '"+g[k]+"' is not expected.",Ut(g,k))}if(_){if(T.length==1)return ut("InvalidTag","Unclosed tag '"+T[0].tagName+"'.",Ut(g,T[0].tagStartPos));if(T.length>0)return ut("InvalidXml","Invalid '"+JSON.stringify(T.map(k=>k.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return ut("InvalidXml","Start tag expected.",1);return!0}i(Vo,"validate"),n(Vo,"validate");function vo(g){return g===" "||g===" "||g===`
410
410
  `||g==="\r"}i(vo,"isWhiteSpace"),n(vo,"isWhiteSpace");function Kt(g,b){let T=b;for(;b<g.length;b++)if(g[b]=="?"||g[b]==" "){let _=g.substr(T,b-T);if(b>5&&_==="xml")return ut("InvalidXml","XML declaration allowed only at the start of the document.",Ut(g,b));if(g[b]=="?"&&g[b+1]==">"){b++;break}else continue}return b}i(Kt,"readPI"),n(Kt,"readPI");function Jo(g,b){if(g.length>b+5&&g[b+1]==="-"&&g[b+2]==="-"){for(b+=3;b<g.length;b++)if(g[b]==="-"&&g[b+1]==="-"&&g[b+2]===">"){b+=2;break}}else if(g.length>b+8&&g[b+1]==="D"&&g[b+2]==="O"&&g[b+3]==="C"&&g[b+4]==="T"&&g[b+5]==="Y"&&g[b+6]==="P"&&g[b+7]==="E"){let T=1;for(b+=8;b<g.length;b++)if(g[b]==="<")T++;else if(g[b]===">"&&(T--,T===0))break}else if(g.length>b+9&&g[b+1]==="["&&g[b+2]==="C"&&g[b+3]==="D"&&g[b+4]==="A"&&g[b+5]==="T"&&g[b+6]==="A"&&g[b+7]==="["){for(b+=8;b<g.length;b++)if(g[b]==="]"&&g[b+1]==="]"&&g[b+2]===">"){b+=2;break}}return b}i(Jo,"readCommentAndCDATA"),n(Jo,"readCommentAndCDATA");var Is='"',Ar="'";function kr(g,b){let T="",_="",L=!1;for(;b<g.length;b++){if(g[b]===Is||g[b]===Ar)_===""?_=g[b]:_!==g[b]||(_="");else if(g[b]===">"&&_===""){L=!0;break}T+=g[b]}return _!==""?!1:{value:T,index:b,tagClosed:L}}i(kr,"readAttributeStr"),n(kr,"readAttributeStr");var fi=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function Ko(g,b){let T=c(g,fi),_={};for(let L=0;L<T.length;L++){if(T[L][1].length===0)return ut("InvalidAttr","Attribute '"+T[L][2]+"' has no space in starting.",On(T[L]));if(T[L][3]!==void 0&&T[L][4]===void 0)return ut("InvalidAttr","Attribute '"+T[L][2]+"' is without value.",On(T[L]));if(T[L][3]===void 0&&!b.allowBooleanAttributes)return ut("InvalidAttr","boolean attribute '"+T[L][2]+"' is not allowed.",On(T[L]));let k=T[L][2];if(!Or(k))return ut("InvalidAttr","Attribute '"+k+"' is an invalid name.",On(T[L]));if(!Object.prototype.hasOwnProperty.call(_,k))_[k]=1;else return ut("InvalidAttr","Attribute '"+k+"' is repeated.",On(T[L]))}return!0}i(Ko,"validateAttributeString"),n(Ko,"validateAttributeString");function _r(g,b){let T=/\d/;for(g[b]==="x"&&(b++,T=/[\da-fA-F]/);b<g.length;b++){if(g[b]===";")return b;if(!g[b].match(T))break}return-1}i(_r,"validateNumberAmpersand"),n(_r,"validateNumberAmpersand");function xr(g,b){if(b++,g[b]===";")return-1;if(g[b]==="#")return b++,_r(g,b);let T=0;for(;b<g.length;b++,T++)if(!(g[b].match(/\w/)&&T<20)){if(g[b]===";")break;return-1}return b}i(xr,"validateAmpersand"),n(xr,"validateAmpersand");function ut(g,b,T){return{err:{code:g,msg:b,line:T.line||T,col:T.col}}}i(ut,"getErrorObject"),n(ut,"getErrorObject");function Or(g){return u(g)}i(Or,"validateAttrName"),n(Or,"validateAttrName");function hi(g){return u(g)}i(hi,"validateTagName"),n(hi,"validateTagName");function Ut(g,b){let T=g.substring(0,b).split(/\r?\n/);return{line:T.length,col:T[T.length-1].length+1}}i(Ut,"getLineNumberForPosition"),n(Ut,"getLineNumberForPosition");function On(g){return g.startIndex+g[1].length}i(On,"getPositionFromMatch"),n(On,"getPositionFromMatch");var gi=class{static{i(this,"XMLParser")}static{n(this,"XMLParser")}constructor(g){this.externalEntities={},this.options=R(g)}parse(g,b){if(typeof g!="string"&&g.toString)g=g.toString();else if(typeof g!="string")throw new Error("XML data is accepted in String or Bytes[] form.");if(b){b===!0&&(b={});let L=Vo(g,b);if(L!==!0)throw Error(`${L.err.msg}:${L.err.line}:${L.err.col}`)}let T=new Re(this.options);T.addExternalEntities(this.externalEntities);let _=T.parseXml(g);return this.options.preserveOrder||_===void 0?_:Bo(_,this.options,T.matcher)}addEntity(g,b){if(b.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(g.indexOf("&")!==-1||g.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(b==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[g]=b}static getMetaDataSymbol(){return v.getMetaDataSymbol()}};return new gi(t)},"getXmlParser");var UI=class extends Qo{static{i(this,"XmlToJsonOutboundPolicy")}static policyType="xml-to-json";parser;parseOnStatusCodes;constructor(e,n){super(e,n),Je(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=e.parseOnStatusCodes?ko(e.parseOnStatusCodes):void 0,this.parser=i$({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0,processEntities:{enabled:!0,maxTotalExpansions:1/0,maxEntityCount:1e3}})}async handler(e,n,o){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let r;try{let c=await e.text();r=this.parser.parse(c)}catch(c){let u=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw o.log.error(u,c),new H(u)}let s=new Headers(e.headers);return s.set("content-type","application/json"),new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:s})}};var qI=class{static{i(this,"ServiceProviderImpl")}services=new Map;addService(e,n){if(this.services.get(e))throw new Fe(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,n)}getService(e){return this.services.get(e)}};var DI=class{static{i(this,"ApiKeyConsumerClient")}bucketId;cacheDurationSeconds;cacheNamePromise;constructor(e){this.bucketId=e?.bucketId,this.cacheDurationSeconds=e?.cacheDurationSeconds??60}getCacheName(e){return this.cacheNamePromise||(this.cacheNamePromise=et("zuplo-get-consumer",{bucketId:e})),this.cacheNamePromise}async get(e){de("utility.get-consumer");let n=Ni(),o=this.bucketId??Xe.ZUPLO_SERVICE_BUCKET_ID;if(!o)throw new C("ApiKeyConsumerClient - no bucketId provided and no default bucket is configured for this environment. Pass `bucketId` explicitly (find it in the Zuplo portal under Settings > API Key Buckets).");if(!o.startsWith("bckt_"))throw new C(`ApiKeyConsumerClient - bucketId "${o}" is not a valid bucket id. Bucket ids start with "bckt_" (e.g. "bckt_2HaK3odRyJle6NJSu8mzNKBC30BYxllxL"); a bucket name (e.g. "zprj-...-working-copy") is not accepted here. Find the bucket id in the Zuplo portal under Settings > API Key Buckets.`);if(!e||e.trim()==="")throw new C("ApiKeyConsumerClient.get - consumerId is required and cannot be empty");let r=await this.getCacheName(o),s=new tt(r,n);if(this.cacheDurationSeconds>0){let l=await s.get(e);if(l)return l}let a=`/v2/key-auth/${encodeURIComponent(o)}/consumers/${encodeURIComponent(e)}`,c=await vy(a),u={id:c.id,name:c.name,createdOn:c.createdOn,updatedOn:c.updatedOn};return c.description!==void 0&&(u.description=c.description),c.metadata!==void 0&&(u.metadata=c.metadata),this.cacheDurationSeconds>0&&s.put(e,u,this.cacheDurationSeconds),u}};var s$=10,a$=3e4,jd=class{static{i(this,"BackgroundLoader")}#e=new Map;#t;#o;#n;#r;#i;#s={};constructor(e,n){if(typeof n=="number"){let o=n;this.#o=o*1e3,this.#r=a$,this.#n=s$,this.#i=Number.POSITIVE_INFINITY}else{let o=n;this.#o=o.ttlSeconds*1e3,this.#r=o.loaderTimeoutSeconds?o.loaderTimeoutSeconds*1e3:a$,this.#n=s$,this.#i=o.staleIfErrorSeconds===void 0?Number.POSITIVE_INFINITY:o.staleIfErrorSeconds*1e3}this.#t=e}#a(e){return e.expiry<=new Date}#c(e){let n=this.#s[e];return!(n===void 0||n===0)}#u(e){let n=this.#e.get(e);if(n&&!this.#a(n))return n.data}async get(e){let n=this.#u(e);if(n)return this.#l(e),n;if(this.#c(e))try{await C8(()=>this.#u(e)!==void 0||!this.#c(e),this.#r+this.#n+1,this.#n);let o=this.#u(e);if(o)return o}catch{}try{return await this.#p(e)}catch(o){let r=this.#e.get(e);if(r&&!this.#d(r))return r.data;throw o}}#d(e){return this.#i===Number.POSITIVE_INFINITY?!1:this.#i<=0?!0:Date.now()>e.expiry.getTime()+this.#i}#l(e){if(!this.#c(e)){let n=this.#p(e);$r().waitUntil(n)}}async#p(e){try{this.#s[e]===void 0&&(this.#s[e]=0),this.#s[e]++;let n=await Promise.race([this.#t(e),scheduler.wait(this.#r)]);if(n===void 0)throw new C(`BackgroundLoader: Loader timed out after ${this.#r} ms.`);return this.#e.set(e,{data:n,expiry:new Date(Date.now()+this.#o)}),n}finally{this.#s[e]--}}};async function C8(t,e,n){let o=Date.now();for(;!t();){let r=Date.now()-o;if(r>e)throw new C(`BackgroundLoader: Timeout waiting for an on-going loader after ${r} ms.`);await scheduler.wait(n)}}i(C8,"waitUntilTrue");import{trace as v8}from"@opentelemetry/api";var c$,u$=i(()=>(c$??=v8.getTracer("pipeline"),c$),"tracer"),l$=i(async(t,e,n)=>{let o=rt.instance.routeData.policies,r=Ks([t],o);if(r.length===0)throw new H(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);let s=r[0],a;try{a=at.getContextExtensions(n)}catch{a=void 0}let c=a?.currentPolicyName;a&&(a.currentPolicyName=s.policyName);try{return await u$().startActiveSpan(`policy:${s.policyName}`,async l=>{try{Js(l,s);let d=await s.handler(e,n);if(d instanceof Request||d instanceof Ge||d instanceof Response)return d instanceof Response||d instanceof Ge?d:new Ge(d);throw new C(`Invalid state - invalid handler on policy '${s.policyName}' invoked via 'invokeInboundPolicy' on route '${n.route.path}'. The result of an inbound policy must be a Response or Request.`)}catch(d){throw Ao(l,d),d}finally{l.end()}})}finally{a&&a.currentPolicyName===s.policyName&&(a.currentPolicyName=c)}},"invokeInboundPolicy"),d$=i(async(t,e,n,o)=>{let r=rt.instance.routeData.policies,s=au([t],r);if(s.length===0)throw new H(`Invalid 'invokeOutboundPolicy call' - no policy '${t}' found.`);let a=s[0];return await u$().startActiveSpan(`policy:${a.policyName}`,async u=>{try{Js(u,a);let l=await a.handler(e,n,o);if(l instanceof Response)return l;throw new C(`Invalid state - invalid handler on policy '${a.policyName}' invoked via 'invokeOutboundPolicy' on route '${o.route.path}. The result of an outbound policy must be a Response.`)}catch(l){throw Ao(u,l),l}finally{u.end()}})},"invokeOutboundPolicy");var At=class{static{i(this,"BaseAnalyticsEvent")}eventId;requestId;timestamp;accountName;projectName;deploymentName;unit;value;constructor(e){this.eventId=e.eventId,this.requestId=e.requestId,this.timestamp=e.timestamp??new Date,this.accountName=e.accountName,this.projectName=e.projectName,this.deploymentName=e.deploymentName,this.unit=e.unit,this.value=e.value}};var Wg=class extends At{static{i(this,"AiGatewayBlockedCountEvent")}eventType=N.AI_GATEWAY_BLOCKED_COUNT;metadata;constructor(e){super(e),this.metadata=e.metadata,(!this.metadata.type||!this.metadata.type.trim())&&(this.metadata.type="unknown"),(!this.metadata.configId||!this.metadata.configId.trim())&&(this.metadata.configId="unknown")}};var Yg=class extends At{static{i(this,"AiGatewayCostSumEvent")}eventType=N.AI_GATEWAY_COST_SUM;metadata;constructor(e){super(e),this.metadata=e.metadata,(!this.metadata.model||!this.metadata.model.trim())&&(this.metadata.model="unknown"),(!this.metadata.provider||!this.metadata.provider.trim())&&(this.metadata.provider="unknown"),(!this.metadata.label||!this.metadata.label.trim())&&(this.metadata.label="unknown"),(!this.metadata.configId||!this.metadata.configId.trim())&&(this.metadata.configId="unknown"),(!this.metadata.costSource||!this.metadata.costSource.trim())&&(this.metadata.costSource="unknown"),(!this.metadata.costAccuracy||!this.metadata.costAccuracy.trim())&&(this.metadata.costAccuracy="unknown")}};var Qg=class extends At{static{i(this,"AiGatewayFallbackCountEvent")}eventType=N.AI_GATEWAY_FALLBACK_COUNT;metadata;constructor(e){super(e),this.metadata=e.metadata,(!this.metadata.type||!this.metadata.type.trim())&&(this.metadata.type="unknown"),(!this.metadata.configId||!this.metadata.configId.trim())&&(this.metadata.configId="unknown")}};var Xg=class extends At{static{i(this,"AiGatewayLatencyHistogramEvent")}eventType=N.AI_GATEWAY_LATENCY_HISTOGRAM;metadata;constructor(e){super(e),this.metadata=e.metadata,(!this.metadata.model||!this.metadata.model.trim())&&(this.metadata.model="unknown"),(!this.metadata.provider||!this.metadata.provider.trim())&&(this.metadata.provider="unknown"),(!this.metadata.label||!this.metadata.label.trim())&&(this.metadata.label="unknown"),(!this.metadata.configId||!this.metadata.configId.trim())&&(this.metadata.configId="unknown")}};var ey=class extends At{static{i(this,"AiGatewayRequestCountEvent")}eventType=N.AI_GATEWAY_REQUEST_COUNT;metadata;constructor(e){super(e),this.metadata=e.metadata,(!this.metadata.model||!this.metadata.model.trim())&&(this.metadata.model="unknown"),(!this.metadata.provider||!this.metadata.provider.trim())&&(this.metadata.provider="unknown"),(!this.metadata.label||!this.metadata.label.trim())&&(this.metadata.label="unknown"),(!this.metadata.configId||!this.metadata.configId.trim())&&(this.metadata.configId="unknown")}};var ty=class extends At{static{i(this,"AiGatewayTokenSumEvent")}eventType=N.AI_GATEWAY_TOKEN_SUM;metadata;constructor(e){super(e),this.metadata=e.metadata,(!this.metadata.model||!this.metadata.model.trim())&&(this.metadata.model="unknown"),(!this.metadata.provider||!this.metadata.provider.trim())&&(this.metadata.provider="unknown"),(!this.metadata.label||!this.metadata.label.trim())&&(this.metadata.label="unknown"),(!this.metadata.configId||!this.metadata.configId.trim())&&(this.metadata.configId="unknown")}};var ny=class extends At{static{i(this,"AiGatewayWarningCountEvent")}eventType=N.AI_GATEWAY_WARNING_COUNT;metadata;constructor(e){super(e),this.metadata=e.metadata,(!this.metadata.type||!this.metadata.type.trim())&&(this.metadata.type="unknown"),(!this.metadata.configId||!this.metadata.configId.trim())&&(this.metadata.configId="unknown")}};var oy=class extends At{static{i(this,"CacheOperationEvent")}eventType=N.CACHE_OPERATION;metadata;constructor(e){super(e),this.metadata=e.metadata}};var ry=class extends At{static{i(this,"GraphqlOperationEvent")}eventType=N.GRAPHQL_OPERATION;metadata;constructor(e){super(e),this.metadata=e.metadata}};var iy=class extends At{static{i(this,"HandlerExecutionEvent")}eventType=N.HANDLER_EXECUTION;metadata;constructor(e){super(e),this.metadata=e.metadata}};var sy=class extends At{static{i(this,"McpEvent")}eventType;metadata;constructor(e){super(e),this.eventType=e.eventType,this.metadata=e.metadata}};var gt=i(t=>e=>new sy({...e,eventType:t}),"buildMcpEvent"),I8={[N.AI_GATEWAY_COST_SUM]:t=>new Yg(t),[N.AI_GATEWAY_REQUEST_COUNT]:t=>new ey(t),[N.AI_GATEWAY_TOKEN_SUM]:t=>new ty(t),[N.AI_GATEWAY_LATENCY_HISTOGRAM]:t=>new Xg(t),[N.AI_GATEWAY_WARNING_COUNT]:t=>new ny(t),[N.AI_GATEWAY_BLOCKED_COUNT]:t=>new Wg(t),[N.AI_GATEWAY_FALLBACK_COUNT]:t=>new Qg(t),[N.MCP_REQUEST_RECEIVED]:gt(N.MCP_REQUEST_RECEIVED),[N.MCP_REQUEST_COMPLETED]:gt(N.MCP_REQUEST_COMPLETED),[N.MCP_REQUEST_REJECTED]:gt(N.MCP_REQUEST_REJECTED),[N.MCP_INITIALIZE_NEGOTIATED]:gt(N.MCP_INITIALIZE_NEGOTIATED),[N.MCP_CLIENT_UNSUPPORTED_BEHAVIOR]:gt(N.MCP_CLIENT_UNSUPPORTED_BEHAVIOR),[N.MCP_CAPABILITY_LISTED]:gt(N.MCP_CAPABILITY_LISTED),[N.MCP_CAPABILITY_INVOKED]:gt(N.MCP_CAPABILITY_INVOKED),[N.MCP_CAPABILITY_COMPLETED]:gt(N.MCP_CAPABILITY_COMPLETED),[N.MCP_CAPABILITY_FAILED]:gt(N.MCP_CAPABILITY_FAILED),[N.MCP_CAPABILITY_CONNECT_REQUIRED]:gt(N.MCP_CAPABILITY_CONNECT_REQUIRED),[N.MCP_AUTH_DOWNSTREAM_TOKEN_VALIDATED]:gt(N.MCP_AUTH_DOWNSTREAM_TOKEN_VALIDATED),[N.MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED]:gt(N.MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED),[N.MCP_OAUTH_CLIENT_REGISTERED]:gt(N.MCP_OAUTH_CLIENT_REGISTERED),[N.MCP_OAUTH_AUTHORIZE_STARTED]:gt(N.MCP_OAUTH_AUTHORIZE_STARTED),[N.MCP_OAUTH_AUTHORIZE_AWAITING_SETUP]:gt(N.MCP_OAUTH_AUTHORIZE_AWAITING_SETUP),[N.MCP_OAUTH_TOKEN_ISSUED]:gt(N.MCP_OAUTH_TOKEN_ISSUED),[N.MCP_OAUTH_TOKEN_REFRESH_ROTATED]:gt(N.MCP_OAUTH_TOKEN_REFRESH_ROTATED),[N.MCP_OAUTH_TOKEN_REVOKED]:gt(N.MCP_OAUTH_TOKEN_REVOKED),[N.MCP_AUTH_UPSTREAM_CONNECT_REQUIRED]:gt(N.MCP_AUTH_UPSTREAM_CONNECT_REQUIRED),[N.MCP_AUTH_UPSTREAM_CONNECT_STARTED]:gt(N.MCP_AUTH_UPSTREAM_CONNECT_STARTED),[N.MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED]:gt(N.MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED),[N.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED]:gt(N.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED),[N.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED]:gt(N.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED),[N.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED]:gt(N.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED),[N.MCP_AUTH_UPSTREAM_CREDENTIAL_MISSING]:gt(N.MCP_AUTH_UPSTREAM_CREDENTIAL_MISSING),[N.MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED]:gt(N.MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED),[N.GRAPHQL_OPERATION]:t=>new ry(t),[N.CACHE_OPERATION]:t=>new oy(t),[N.HANDLER_EXECUTION]:t=>new iy(t)};function p$(t,e){let n=I8[t];return n(e)}i(p$,"createAnalyticsEvent");var ay=class{static{i(this,"ZuploGatewayAnalyticsContext")}#e;#t;constructor(e){this.#e=[],this.#t=e}addAnalyticsEvent(e,n,o,r,s){let a=this.createAnalyticsEvent(e,n,o,r,s);this.#e.push(a)}flushAnalyticsEvents(){let e=[...this.#e];return this.#e.length=0,e}getAnalyticsEvents(){return[...this.#e]}createAnalyticsEvent(e,n,o,r,s){return p$(n,{eventId:s??crypto.randomUUID(),requestId:this.#t,accountName:O.instance.accountName??"unknown",projectName:O.instance.projectName??"unknown",deploymentName:O.instance.deploymentName??"unknown",metadata:o,unit:r,value:e})}};var T8="127.0.0.1";function m$(t){let e=O.instance,n=t.get(e.trustedIpHeader)?.trim();return n||(e.isLocalDevelopment?T8:void 0)}i(m$,"resolveClientIp");function E8(t){let e={};if(!t)return e;try{let n=t.split(","),o={};return n.forEach(r=>{let[s,a]=r.split("=");s&&a&&(o[s.trim()]=a.trim())}),o.asnum&&(e[Up]=o.asnum),o.zip&&(e[qp]=o.zip.split("+")[0]),o.dma&&(e[Dp]=o.dma),o.region_code&&(e[$p]=o.region_code),o.timezone&&(e[zp]=o.timezone),o.city&&(e[xp]=o.city),o.continent&&(e[Op]=o.continent),o.country_code&&(e[Mp]=o.country_code),o.long&&(e[Lp]=o.long),o.lat&&(e[Np]=o.lat),e}catch{return{}}}i(E8,"parseEdgeScapeHeader");function f$(t,e){let n=E8(e);for(let[o,r]of Object.entries(n))t.has(o)||t.set(o,r)}i(f$,"setZpHeadersFromAkamaiEdgeScapeHeader");var Um=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e;let n=e.get(gT);if(n){let o=new Headers(e);f$(o,n),this.#e=o}}get ip(){return m$(this.#e)}get asn(){try{let e=this.#e.get(Up);if(typeof e=="string")return parseInt(e,10)}catch{}}get asOrganization(){return this.#e.get(lT)??void 0}get city(){return this.#e.get(BI)??this.#e.get(xp)??void 0}get continent(){return this.#e.get(ZI)??this.#e.get(Op)??void 0}get country(){return this.#e.get(VI)??this.#e.get(Mp)??void 0}get latitude(){return this.#e.get(KI)??this.#e.get(Np)??void 0}get longitude(){return this.#e.get(JI)??this.#e.get(Lp)??void 0}get colo(){return this.#e.get(dT)??void 0}get postalCode(){return this.#e.get(XI)??this.#e.get(qp)??void 0}get metroCode(){return this.#e.get(QI)??this.#e.get(Dp)??void 0}get region(){return this.#e.get(WI)??this.#e.get(pT)??void 0}get regionCode(){return this.#e.get(YI)??this.#e.get($p)??void 0}get timezone(){return this.#e.get(eT)??this.#e.get(zp)??void 0}get httpProtocol(){return this.#e.get(mT)??void 0}get clientCert(){return this.#e.get(nT)??void 0}get clientMtlsVerificationStatus(){return this.#e.get(oT)??void 0}get clientMtlsVerificationReason(){return this.#e.get(rT)??void 0}get clientCertFingerprintSha256(){return this.#e.get(iT)??void 0}get clientCertNotBefore(){return this.#e.get(sT)??void 0}get clientCertNotAfter(){return this.#e.get(aT)??void 0}get clientCertIssuerDn(){return this.#e.get(cT)??void 0}get clientCertSubjectDn(){return this.#e.get(uT)??void 0}toJSON(){return{ip:this.ip,asn:this.asn,asOrganization:this.asOrganization,city:this.city,continent:this.continent,country:this.country,latitude:this.latitude,longitude:this.longitude,colo:this.colo,postalCode:this.postalCode,metroCode:this.metroCode,region:this.region,regionCode:this.regionCode,timezone:this.timezone,httpProtocol:this.httpProtocol,clientCert:this.clientCert,clientMtlsVerificationStatus:this.clientMtlsVerificationStatus,clientMtlsVerificationReason:this.clientMtlsVerificationReason,clientCertFingerprintSha256:this.clientCertFingerprintSha256,clientCertNotBefore:this.clientCertNotBefore,clientCertNotAfter:this.clientCertNotAfter,clientCertIssuerDn:this.clientCertIssuerDn,clientCertSubjectDn:this.clientCertSubjectDn}}};function lc(t){return{contextId:t.contextId,incomingRequestProperties:t.incomingRequestProperties,requestId:t.requestId,route:t.route,custom:t.custom,parentContext:t.parentContext,analyticsContext:t.analyticsContext}}i(lc,"createRewriteContext");var Xc=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},eu=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,n){super("responseSent"),this.request=e,this.response=n}request;response},at=class t{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,n,o=n.url){if(!t.#e.has(e)){let r=new t(n,o);return t.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let n=t.#e.get(e);if(!n)throw new H(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return n}latestRequest;receivedUrl;requestLogProperties=new Map;#t;startDeferringMetrics(){return this.#t?!1:(this.#t=[],!0)}deferMetrics(e){return this.#t?(this.#t.push(e),!0):!1}flushDeferredMetrics(){let e=this.#t??[];this.#t=void 0;let n=[];for(let o of e)try{o()}catch(r){n.push(r)}return n}auditLogEventId="";preRequestState;currentPolicyName;preRequestPhase;#o;#n;#r;constructor(e,n){this.latestRequest=e,this.receivedUrl=n,this.preRequestState=void 0,this.currentPolicyName=void 0,this.preRequestPhase=void 0,this.#o=[],this.#n=[],this.#r=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#o.push(e)}addHandlerResponseHook(e){this.#r.push(e)}onResponseSendingFinal=i(async(e,n,o)=>{for(let r of this.#o)await r(e,n,o)},"onResponseSendingFinal");onResponseSending=i(async(e,n,o)=>{let r=e,s=O.instance.build.COMPATIBILITY_FLAGS.chainResponseSendingHooks;for(let a of this.#n)r=await a(s?r:e,n,o);return r},"onResponseSending");onHandlerResponse=i(async(e,n,o)=>{for(let r of this.#r)await r(e,n,o)},"onHandlerResponse")},qm=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:n,requestId:o,event:r,custom:s,incomingRequestProperties:a,parentContext:c}){super(),this.log=Object.freeze(e),this.route=n,this.requestId=o,this.custom=s,this.incomingRequestProperties=a,this.parentContext=c,this.#e=r,this.invokeInboundPolicy=(u,l)=>l$(u,l,this),this.contextId=crypto.randomUUID(),this.invokeOutboundPolicy=(u,l,d)=>d$(u,l,d,this),this.invokeRoute=async(u,l)=>{let d=u;typeof u=="string"&&u.startsWith("/")&&(d=new URL(u,"http://localhost"));let p=new Ge(d,l);return rt.instance.handleRequest(p,this,{parentContext:this})},this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{at.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{at.getContextExtensions(this).addResponseSendingFinalHook(u)},this.addPreRequestHandler=(u,l)=>{JE(this,at.getContextExtensions(this),u,l)},this.analyticsContext=new ay(o),Object.freeze(this)}#e;#t=new EventTarget;contextId;requestId;log;route;custom;incomingRequestProperties;parentContext;analyticsContext;invokeInboundPolicy;invokeOutboundPolicy;invokeRoute;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addPreRequestHandler;addEventListener(e,n,o){de("context.addEventListener");let r=i(s=>{try{typeof n=="function"?n(s):n.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");this.#t.addEventListener(e,r,o)}removeEventListener(e,n,o){de("context.removeEventListener"),this.#t.removeEventListener(e,n,o)}dispatchEvent(e){return this.#t.dispatchEvent(e)}};export{by as a,In as b,Wt as c,Bc as d,F$ as e,wy as f,lt as g,Ds as h,G$ as i,Ti as j,Sy as k,de as l,vy as m,Ty as n,Nn as o,Yo as p,Zc as q,Ei as r,G as s,Dt as t,Pi as u,N as v,Ey as w,Py as x,Wp as y,Be as z,jn as A,Hr as B,fe as C,Qo as D,JE as E,Ly as F,$y as G,hz as H,js as I,ay as J,Xc as K,eu as L,at as M,kb as N,un as O,uk as P,Vk as Q,Qk as R,HG as S,r_ as T,yR as U,YG as V,Zi as W,Hu as X,Vi as Y,Pa as Z,ir as _,sr as $,ri as aa,Ji as ba,rr as ca,xt as da,Hf as ea,Aa as fa,ka as ga,Gu as ha,Bu as ia,_a as ja,mn as ka,ii as la,Ot as ma,En as na,yn as oa,xa as pa,Mt as qa,ar as ra,Oa as sa,Ma as ta,Ki as ua,Wi as va,Yi as wa,Ff as xa,La as ya,Zu as za,Na as Aa,Vu as Ba,cr as Ca,xo as Da,fo as Ea,Gf as Fa,Bf as Ga,Ju as Ha,Ku as Ia,Ua as Ja,qa as Ka,Wu as La,Yu as Ma,Qu as Na,Xu as Oa,Da as Pa,el as Qa,tl as Ra,$a as Sa,nl as Ta,ur as Ua,lr as Va,za as Wa,ja as Xa,Ha as Ya,dr as Za,Oo as _a,Fa as $a,ol as ab,rl as bb,il as cb,sl as db,al as eb,Qi as fb,cl as gb,ul as hb,ll as ib,dl as jb,pl as kb,ml as lb,fl as mb,hl as nb,Ga as ob,gl as pb,yl as qb,bl as rb,Rl as sb,wl as tb,Sl as ub,Cl as vb,vl as wb,Il as xb,Tl as yb,El as zb,Pl as Ab,Al as Bb,kl as Cb,pr as Db,mr as Eb,fr as Fb,_l as Gb,Xi as Hb,es as Ib,ts as Jb,xl as Kb,Ol as Lb,Ml as Mb,Ll as Nb,Nl as Ob,Ba as Pb,Ul as Qb,ql as Rb,Za as Sb,Zf as Tb,Dl as Ub,$l as Vb,zl as Wb,wR as Xb,hr as Yb,jl as Zb,Hl as _b,Fl as $b,Gl as ac,Bl as bc,Zl as cc,Vl as dc,Jl as ec,Kl as fc,oi as gc,Wl as hc,Yl as ic,Ql as jc,Xl as kc,ed as lc,Va as mc,ns as nc,os as oc,Ja as pc,Ka as qc,Wa as rc,td as sc,Ya as tc,Qa as uc,nd as vc,od as wc,Xa as xc,rs as yc,rd as zc,id as Ac,sd as Bc,ad as Cc,cd as Dc,ud as Ec,ld as Fc,dd as Gc,pd as Hc,md as Ic,fd as Jc,hd as Kc,gd as Lc,yd as Mc,bd as Nc,Vf as Oc,Rd as Pc,gr as Qc,Jf as Rc,wd as Sc,Kf as Tc,Wf as Uc,Yf as Vc,Qf as Wc,Xf as Xc,eh as Yc,th as Zc,nh as _c,oh as $c,rh as ad,ih as bd,sh as cd,ah as dd,ch as ed,uh as fd,lh as gd,Sd as hd,Cd as id,dh as jd,ph as kd,mh as ld,fh as md,vd as nd,Id as od,hh as pd,gh as qd,yh as rd,Hx as sd,Fx as td,Gx as ud,Bx as vd,Zx as wd,Vx as xd,aw as yd,oV as zd,cw as Ad,lw as Bd,pw as Cd,hw as Dd,yw as Ed,Rw as Fd,Sw as Gd,vw as Hd,Ew as Id,kw as Jd,Ow as Kd,Nw as Ld,ls as Md,Tt as Nd,Lo as Od,qw as Pd,Dw as Qd,qd as Rd,Dd as Sd,$d as Td,Gw as Ud,Hd as Vd,Vw as Wd,Jw as Xd,jV as Yd,Kw as Zd,Ww as _d,uS as $d,pS as ae,Jh as be,Kh as ce,AM as de,og as ee,tC as fe,iC as ge,lg as he,lC as ie,mC as je,p0 as ke,SC as le,q0 as me,H0 as ne,F0 as oe,PC as pe,Z0 as qe,hg as re,sW as se,AC as te,An as ue,tL as ve,MC as we,LC as xe,oL as ye,qC as ze,iL as Ae,fL as Be,hL as Ce,gL as De,yL as Ee,bL as Fe,RL as Ge,GC as He,CL as Ie,vL as Je,IL as Ke,TL as Le,EL as Me,PL as Ne,AL as Oe,kL as Pe,Tg as Qe,u3 as Re,ML as Se,NL as Te,YC as Ue,v3 as Ve,ev as We,BL as Xe,pi as Ye,Ec as Ze,ct as _e,Pt as $e,qo as af,WNe as bf,up as cf,eUe as df,tUe as ef,Wn as ff,rUe as gf,iUe as hf,sUe as if,aUe as jf,cUe as kf,uUe as lf,lUe as mf,dUe as nf,lp as of,pUe as pf,bs as qf,yUe as rf,_g as sf,Rs as tf,Ac as uf,ov as vf,kUe as wf,rv as xf,iv as yf,sv as zf,av as Af,cv as Bf,uv as Cf,lv as Df,dv as Ef,pv as Ff,mv as Gf,fv as Hf,kDe as If,so as Jf,Yn as Kf,zt as Lf,$N as Mf,L6 as Nf,N6 as Of,hv as Pf,ZDe as Qf,VDe as Rf,JDe as Sf,tU as Tf,nU as Uf,b$e as Vf,R$e as Wf,gv as Xf,pp as Yf,Ug as Zf,w$e as _f,iU as $f,I$e as ag,mp as bg,o5 as cg,r5 as dg,bv as eg,M$e as fg,uU as gg,lU as hg,q$e as ig,D$e as jg,$$e as kg,z$e as lg,dU as mg,pU as ng,fU as og,Do as pg,Tr as qg,a5 as rg,c5 as sg,J$e as tg,K$e as ug,W$e as vg,Y$e as wg,$o as xg,p5 as yg,uze as zg,yU as Ag,Rze as Bg,Cv as Cg,f5 as Dg,C5 as Eg,I5 as Fg,wU as Gg,Lze as Hg,Nze as Ig,Uze as Jg,IU as Kg,zze as Lg,jze as Mg,Hze as Ng,Av as Og,zg as Pg,kv as Qg,PU as Rg,Yze as Sg,Qze as Tg,Xze as Ug,eje as Vg,vq as Wg,ao as Xg,Bv as Yg,Mje as Zg,Iq as _g,Lje as $g,Kv as ah,Wv as bh,kq as ch,c9 as dh,Lq as eh,nI as fh,Gq as gh,rI as hh,Xq as ih,iI as jh,aI as kh,tD as lh,nD as mh,oD as nh,lI as oh,pI as ph,lD as qh,dD as rh,pD as sh,mD as th,fD as uh,gD as vh,hI as wh,k9 as xh,SD as yh,RI as zh,PD as Ah,AD as Bh,kD as Ch,H9 as Dh,_D as Eh,xD as Fh,OD as Gh,MD as Hh,LD as Ih,vI as Jh,UD as Kh,qD as Lh,II as Mh,TI as Nh,zD as Oh,HD as Ph,FD as Qh,AI as Rh,BD as Sh,YD as Th,MI as Uh,LI as Vh,QD as Wh,r$ as Xh,UI as Yh,qI as Zh,DI as _h,jd as $h};
411
- /*! For license information please see chunk-5SHD5VGF.js.LEGAL.txt */
412
- //# sourceMappingURL=chunk-5SHD5VGF.js.map
411
+ /*! For license information please see chunk-7WJVPTYD.js.LEGAL.txt */
412
+ //# sourceMappingURL=chunk-7WJVPTYD.js.map