
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Zuplo, Inc. All rights reserved.
 *
 *  This software and associated documentation files (the "Software") is intended to be used
 *  only by Zuplo customers solely to develop and test applications that will be deployed
 *  to Zuplo hosted services. You and others in your organization may use these files on your
 *  Development Devices solely for the above stated purpose.
 *
 *  Outside of uses stated above, no license is granted for any other purpose including
 *  without limitation the rights to use, copy, modify, merge, publish, distribute,
 *  sublicense, host, and/or sell copies of the Software.
 *
 *  The software may include third party components with separate legal notices or governed by
 *  other agreements, as described in licenses either embedded in or accompanying the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
 *  INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR 
 *  PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE 
 *  FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 
 *  OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 *  DEALINGS IN THE SOFTWARE.
 *--------------------------------------------------------------------------------------------*/

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
`),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
`);#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]===`
`||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};
