@zuplo/core 6.52.5 → 6.52.6

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.
@@ -579,7 +579,7 @@ globstar while`,s,Q,l,Re,Ne),this.matchOne(s.slice(Q),l.slice(Re),_))return this
579
579
  `),stderr:b.join(`
580
580
  `),exitCode:D},"Tar process logs")}}t(yar,"tarFolder");async function bar({tarFilePath:a,outputDir:s,logger:l}){let _=[],h=[],b;try{await new Promise((D,N)=>{let M=Hut("sh",["-c",`tar -xvf ${a} -C ${s};`]);M.stdout.on("data",z=>{let re=z.toString().trim();re.length>0&&_.push(re.trim())}),M.stderr.on("data",z=>{let re=z.toString().trim();re.length>0&&h.push(re.trim())}),M.on("close",z=>{b=z,z===0?D():N(new Error(`tar process exited with code ${z}`))}),M.on("error",z=>{N(z)})})}catch(D){throw new Error("Failed to untar file",{cause:D})}finally{l.info({stdout:_.join(`
581
581
  `),stderr:h.join(`
582
- `),exitCode:b},"Untar process logs")}}t(bar,"untarFile");async function Sar(a){if(await V3e(a))return await j3.rm(a,{recursive:!0})}t(Sar,"deleteFolder");var ou=W3e;var IT=ap(q3e(),1);var oO=class extends Error{static{t(this,"CustomResolveError")}},B3=class{static{t(this,"RefParser")}sourceDirectory;logger;constructor(s,l){this.sourceDirectory=s,this.logger=l}dereference(s,l){return bG.$RefParser.dereference(s,{resolve:{json:!0,file:_ue(this.sourceDirectory,this.logger),external:!0,http:!1},dereference:{circular:"ignore",onDereference:l?.onDereference}})}bundle(s){return bG.$RefParser.bundle(s,{resolve:{file:_ue(this.sourceDirectory,this.logger),external:!0,http:!1}})}parse(s){return bG.$RefParser.parse(s,{resolve:{file:_ue(this.sourceDirectory,this.logger),external:!0,http:!1}})}resolve(s){return bG.$RefParser.resolve(s,{resolve:{file:_ue(this.sourceDirectory,this.logger),external:!0,http:!1}})}};function _ue(a,s){return{order:100,canRead(l){let _=Ear(l.url);if(!(_===void 0||_==="file"))return!1;let b;try{b=Xut(l.url)}catch(D){throw new oO(`Malformed URI: ${l.url}`,{cause:D})}try{ou.safePath(a).resolve(b)}catch(D){return s?.warn(D),!1}return!0},async read(l){let _;try{_=Xut(l.url)}catch(h){throw new oO(`Malformed URI: ${l.url}`,{cause:h})}try{return await Tar(_)}catch(h){throw new oO(`Error opening file "${_}"`,{cause:h})}}}}t(_ue,"customResolver");var ij=/^win/.test(globalThis.process?globalThis.process.platform:""),xar=/\//g,Car=/^(\w{2,}):\/\//i,H3e=[/%23/g,"#",/%24/g,"$",/%26/g,"&",/%2C/g,",",/%40/g,"@"];function Ear(a){let s=Car.exec(a);if(s)return s[1].toLowerCase()}t(Ear,"getProtocol");function Xut(a,s){a=decodeURI(a);for(let _=0;_<H3e.length;_+=2)a=a.replace(H3e[_],H3e[_+1]);let l=a.substr(0,7).toLowerCase()==="file://";if(l&&(a=a[7]==="/"?a.substr(8):a.substr(7),ij&&a[1]==="/"&&(a=a[0]+":"+a.substr(1)),s?a="file:///"+a:(l=!1,a=ij?a:"/"+a)),!l){let _=a.split(ij?"\\":"/"),h=[];for(let b of _)b===".."?h.length&&h[h.length-1]!==""&&h.pop():(b!==""||h.length===0)&&h.push(b);a=h.join(ij?"\\":"/"),!ij&&h[0]===""&&(a="/"+a.substring(1))}return ij&&!l&&(a=a.replace(xar,"\\"),a.substr(1,2)===":\\"&&(a=a[0].toUpperCase()+a.substr(1))),a}t(Xut,"toFileSystemPath");var Qut="YOUR_KEY_HERE";async function Zut(a){let l=await new B3(a.sourceDirectory,a.logger).bundle(a.openApiDocPath),_=a.openApiDocPath.replace(a.sourceDirectory,"");return Dar({...a,relativeOpenApiPath:_},l)}t(Zut,"buildPublicOpenApiFile");async function Dar(a,s){Aar({relativeOpenApiPath:a.relativeOpenApiPath},s);let l=s;return l=war(l),kar(l,a.deploymentUrl),l=Par(l,a),eft(l,"x-zuplo"),l}t(Dar,"buildRawOpenApiFile");function kar(a,s){s?a.servers=[{url:s}]:a.servers=[]}t(kar,"addServerHost");function war(a){if(!a.paths)return a;let{components:s}=a,l=s?{...s}:void 0,_=[];l&&l.parameters&&(_=Object.entries(l.parameters).reduce((b,[D,N])=>(PM in N&&ile(N[PM])&&(b.push(D),l.parameters&&delete l.parameters[D]),b),[]));let h=Object.entries(a.paths).reduce((b,[D,N])=>{if(!N)return b;let M={...N},z=["delete","get","head","patch","post","put","trace","options"];return z.forEach(re=>{let ie=N[re];if(!ie)return;if(ile(ie[PM])){delete M[re];return}let{parameters:Q}=ie;if(!Q)return;let Re=Q.filter(Ne=>{if(PM in Ne&&ile(Ne[PM]))return!1;if("$ref"in Ne){let we=Ne.$ref.split("/").pop();return we?!_.includes(we):!0}return!0});M[re]={...ie,parameters:Re}}),z.some(re=>!!M[re])&&(b[D]=M),b},{});return{...a,paths:h,components:l}}t(war,"removeHiddenRoutesAndParams");function Par(a,{policiesConfig:s}){if(!a.paths)return a;let l=Object.entries(a.paths).reduce((_,[h,b])=>{if(!b)return _;let D={...b};return[D.delete,D.get,D.head,D.patch,D.post,D.put,D.trace,D.options].forEach(N=>{if(!N)return;let M=N["x-zuplo-route"]?.policies?.inbound?.reduce((ie,Q)=>{let Re=s.policies?.find(({name:wt})=>wt===Q);if(!Re)return ie;if(!(Re.handler.export==="CompositeInboundPolicy"))return ie.concat(Q);let we=Re.handler.options?.policies;return we?ie.concat(we):ie},[]),z=[];if(M&&M.forEach(ie=>{s.policies?.forEach(Q=>{Q.name===ie&&(Q.handler.export==="ApiAuthKeyInboundPolicy"||Q.handler.export==="ApiKeyInboundPolicy")&&!Q.handler.options?.disableAutomaticallyAddingKeyHeaderToOpenApi&&z.push(Q)})}),z.length>0){let ie=z.length>0&&z[0].handler&&z[0].handler.options&&z[0].handler.options.authHeader?z[0].handler.options.authHeader:"Authorization",Q=z.length>0&&z[0].handler&&z[0].handler.options&&(z[0].handler.options.authScheme||z[0].handler.options.authScheme==="")?z[0].handler.options.authScheme:"Bearer",Re=Q!==""?`${Q} ${Qut}`:Qut,Ne={name:ie,in:"header",required:!0,example:Re,schema:{type:"string"},description:`The \`${ie}\` header is used to authenticate with the API using your API key. Value is of the format \`${Re}\`.`};N.parameters?N.parameters.some(Tr=>"name"in Tr&&Tr.name===Ne.name)||N.parameters.unshift(Ne):N.parameters=[Ne];let we={type:"http",scheme:Q.toLowerCase()},wt="api_key";a.components?.securitySchemes?Object.values(a.components?.securitySchemes).some(Tr=>"name"in Tr&&Tr.type==="apiKey"||"type"in Tr&&Tr.type==="http"&&Tr.scheme===Q)||(a.components.securitySchemes={...a.components.securitySchemes,[wt]:we}):(a.components||(a.components={}),a.components.securitySchemes={[wt]:we});let xt={[wt]:[]};N.security?N.security.some(Tr=>Tr[wt]!==void 0)||N.security.unshift(xt):N.security=[xt]}let re=[];if(M&&M.forEach(ie=>{s.policies?.forEach(Q=>{Q.name===ie&&(Q.handler.export==="RateLimitInboundPolicy"||Q.handler.export==="ComplexRateLimitInboundPolicy")&&re.push(Q)})}),re.length>0){let ie={description:"Rate Limiting Response",content:{"application/json":{schema:{type:"object",required:["type","title","status"],examples:[{type:"https://httpproblems.com/http-status/429",title:"Too Many Requests",status:429,instance:"/foo/bar"}],properties:{type:{type:"string",example:"https://httpproblems.com/http-status/429",description:"A URI reference that identifies the problem."},title:{type:"string",example:"Too Many Requests",description:"A short, human-readable summary of the problem."},status:{type:"number",example:429,description:"The HTTP status code."},instance:{type:"string",example:"/foo/bar"}}}}}},Q={...ie,headers:{"retry-after":{description:"The number of seconds to wait before making a new request.",schema:{type:"integer",example:60}}}};a.components?.responses||a.components||(a.components={}),a.components.responses={...a.components.responses,RateLimitNoRetryAfter:ie,RateLimitWithRetryAfter:Q},N.responses||(N.responses={});let Re=re.some(Ne=>Ne.handler.options?.headerMode!=="none");N.responses[429]||(N.responses[429]={$ref:Re?"#/components/responses/RateLimitWithRetryAfter":"#/components/responses/RateLimitNoRetryAfter"})}}),_[h]=D,_},{});return{...a,paths:l}}t(Par,"enrichSpecWithZuploData");function eft(a,s){for(let l in a)l.startsWith(s)?delete a[l]:typeof a[l]=="object"&&eft(a[l],s)}t(eft,"removePropertiesByPrefix");function Aar({relativeOpenApiPath:a},s){if(!s||typeof s!="object")throw new J1({message:"The OpenAPI Document could not be parsed.",severity:"error"});if(!("info"in s)||typeof s.info!="object"||!s.info)throw new J1({message:"The OpenAPI document does not have the required 'info' property.",location:{file:a,column:0,length:0,line:0,lineText:"",namespace:"",suggestion:"Add the required 'info' property. https://spec.openapis.org/oas/v3.1.0#info-object"},severity:"error"});if(!("title"in s.info)||typeof s.info.title!="string")throw new J1({message:"The OpenAPI document does not have the required 'info.title' property.",location:{file:a,column:0,length:0,line:0,lineText:"",namespace:"",suggestion:"Add the required 'info.title' property. https://spec.openapis.org/oas/v3.1.0#info-object"},severity:"error"})}t(Aar,"assertIsZuploOpenApiSpec");import CK from"node:path";function Nar(a){if(a.length>=255)throw new TypeError("Alphabet too long");let s=new Uint8Array(256);for(let z=0;z<s.length;z++)s[z]=255;for(let z=0;z<a.length;z++){let re=a.charAt(z),ie=re.charCodeAt(0);if(s[ie]!==255)throw new TypeError(re+" is ambiguous");s[ie]=z}let l=a.length,_=a.charAt(0),h=Math.log(l)/Math.log(256),b=Math.log(256)/Math.log(l);function D(z){if(z instanceof Uint8Array||(ArrayBuffer.isView(z)?z=new Uint8Array(z.buffer,z.byteOffset,z.byteLength):Array.isArray(z)&&(z=Uint8Array.from(z))),!(z instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(z.length===0)return"";let re=0,ie=0,Q=0,Re=z.length;for(;Q!==Re&&z[Q]===0;)Q++,re++;let Ne=(Re-Q)*b+1>>>0,we=new Uint8Array(Ne);for(;Q!==Re;){let Tr=z[Q],fn=0;for(let tn=Ne-1;(Tr!==0||fn<ie)&&tn!==-1;tn--,fn++)Tr+=256*we[tn]>>>0,we[tn]=Tr%l>>>0,Tr=Tr/l>>>0;if(Tr!==0)throw new Error("Non-zero carry");ie=fn,Q++}let wt=Ne-ie;for(;wt!==Ne&&we[wt]===0;)wt++;let xt=_.repeat(re);for(;wt<Ne;++wt)xt+=a.charAt(we[wt]);return xt}t(D,"encode");function N(z){if(typeof z!="string")throw new TypeError("Expected String");if(z.length===0)return new Uint8Array;let re=0,ie=0,Q=0;for(;z[re]===_;)ie++,re++;let Re=(z.length-re)*h+1>>>0,Ne=new Uint8Array(Re);for(;z[re];){let Tr=s[z.charCodeAt(re)];if(Tr===255)return;let fn=0;for(let tn=Re-1;(Tr!==0||fn<Q)&&tn!==-1;tn--,fn++)Tr+=l*Ne[tn]>>>0,Ne[tn]=Tr%256>>>0,Tr=Tr/256>>>0;if(Tr!==0)throw new Error("Non-zero carry");Q=fn,re++}let we=Re-Q;for(;we!==Re&&Ne[we]===0;)we++;let wt=new Uint8Array(ie+(Re-we)),xt=ie;for(;we!==Re;)wt[xt++]=Ne[we++];return wt}t(N,"decodeUnsafe");function M(z){let re=N(z);if(re)return re;throw new Error("Non-base"+l+" character")}return t(M,"decode"),{encode:D,decodeUnsafe:N,decode:M}}t(Nar,"base");var tft=Nar;var Iar="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",pue=tft(Iar);var Far=!1;function sj(a,s){return{open:`\x1B[${a.join(";")}m`,close:`\x1B[${s}m`,regexp:new RegExp(`\\x1b\\[${s}m`,"g")}}t(sj,"code");function aj(a,s){return Far?`${s.open}${a.replace(s.regexp,s.open)}${s.close}`:a}t(aj,"run");function Oar(a){return aj(a,sj([31],39))}t(Oar,"red");function Lar(a){return aj(a,sj([32],39))}t(Lar,"green");function Rar(a){return aj(a,sj([33],39))}t(Rar,"yellow");function Mar(a){return aj(a,sj([34],39))}t(Mar,"blue");function jar(a){return aj(a,sj([35],39))}t(jar,"magenta");function Bar(a){return aj(a,sj([36],39))}t(Bar,"cyan");var G8r=new RegExp(["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|"),"g");var rft=[Oar,Lar,Rar,Mar,jar,Bar];function Uar(a){let s=0,l=a.length,_=0;if(l>0)for(;_<l;)s=(s<<5)-s+a.charCodeAt(_++)|0;return s}t(Uar,"hashCode");function nft(a){let s=Math.abs(Uar(a));return rft[s%rft.length]}t(nft,"generateColor");import{inspect as $ar}from"node:util";function ift(a,s,...l){let _=0,h=l.length,b=String(s).replace(/%[sdjoO%]/g,D=>{if(D==="%%")return"%";if(_>=h)return D;switch(D){case"%s":return String(l[_++]);case"%d":return Number(l[_++]).toString();case"%o":return a(l[_++]).split(`
582
+ `),exitCode:b},"Untar process logs")}}t(bar,"untarFile");async function Sar(a){if(await V3e(a))return await j3.rm(a,{recursive:!0})}t(Sar,"deleteFolder");var ou=W3e;var IT=ap(q3e(),1);var oO=class extends Error{static{t(this,"CustomResolveError")}},B3=class{static{t(this,"RefParser")}sourceDirectory;logger;constructor(s,l){this.sourceDirectory=s,this.logger=l}dereference(s,l){return bG.$RefParser.dereference(s,{resolve:{json:!0,file:_ue(this.sourceDirectory,this.logger),external:!0,http:!1},dereference:{circular:"ignore",onDereference:l?.onDereference}})}bundle(s){return bG.$RefParser.bundle(s,{resolve:{file:_ue(this.sourceDirectory,this.logger),external:!0,http:!1}})}parse(s){return bG.$RefParser.parse(s,{resolve:{file:_ue(this.sourceDirectory,this.logger),external:!0,http:!1}})}resolve(s){return bG.$RefParser.resolve(s,{resolve:{file:_ue(this.sourceDirectory,this.logger),external:!0,http:!1}})}};function _ue(a,s){return{order:100,canRead(l){let _=Ear(l.url);if(!(_===void 0||_==="file"))return!1;let b;try{b=Xut(l.url)}catch(D){throw new oO(`Malformed URI: ${l.url}`,{cause:D})}try{ou.safePath(a).resolve(b)}catch(D){return s?.warn(D),!1}return!0},async read(l){let _;try{_=Xut(l.url)}catch(h){throw new oO(`Malformed URI: ${l.url}`,{cause:h})}try{return await Tar(_)}catch(h){throw new oO(`Error opening file "${_}"`,{cause:h})}}}}t(_ue,"customResolver");var ij=/^win/.test(globalThis.process?globalThis.process.platform:""),xar=/\//g,Car=/^(\w{2,}):\/\//i,H3e=[/%23/g,"#",/%24/g,"$",/%26/g,"&",/%2C/g,",",/%40/g,"@"];function Ear(a){let s=Car.exec(a);if(s)return s[1].toLowerCase()}t(Ear,"getProtocol");function Xut(a,s){a=decodeURI(a);for(let _=0;_<H3e.length;_+=2)a=a.replace(H3e[_],H3e[_+1]);let l=a.substr(0,7).toLowerCase()==="file://";if(l&&(a=a[7]==="/"?a.substr(8):a.substr(7),ij&&a[1]==="/"&&(a=a[0]+":"+a.substr(1)),s?a="file:///"+a:(l=!1,a=ij?a:"/"+a)),!l){let _=a.split(ij?"\\":"/"),h=[];for(let b of _)b===".."?h.length&&h[h.length-1]!==""&&h.pop():(b!==""||h.length===0)&&h.push(b);a=h.join(ij?"\\":"/"),!ij&&h[0]===""&&(a="/"+a.substring(1))}return ij&&!l&&(a=a.replace(xar,"\\"),a.substr(1,2)===":\\"&&(a=a[0].toUpperCase()+a.substr(1))),a}t(Xut,"toFileSystemPath");var Qut="YOUR_KEY_HERE";async function Zut(a){let l=await new B3(a.sourceDirectory,a.logger).bundle(a.openApiDocPath),_=a.openApiDocPath.replace(a.sourceDirectory,"");return Dar({...a,relativeOpenApiPath:_},l)}t(Zut,"buildPublicOpenApiFile");async function Dar(a,s){Aar({relativeOpenApiPath:a.relativeOpenApiPath},s);let l=s;return l=war(l),kar(l,a.urls?.api?.defaultUrl),l=Par(l,a),eft(l,"x-zuplo"),l}t(Dar,"buildRawOpenApiFile");function kar(a,s){s?a.servers=[{url:s}]:a.servers=[]}t(kar,"addServerHost");function war(a){if(!a.paths)return a;let{components:s}=a,l=s?{...s}:void 0,_=[];l&&l.parameters&&(_=Object.entries(l.parameters).reduce((b,[D,N])=>(PM in N&&ile(N[PM])&&(b.push(D),l.parameters&&delete l.parameters[D]),b),[]));let h=Object.entries(a.paths).reduce((b,[D,N])=>{if(!N)return b;let M={...N},z=["delete","get","head","patch","post","put","trace","options"];return z.forEach(re=>{let ie=N[re];if(!ie)return;if(ile(ie[PM])){delete M[re];return}let{parameters:Q}=ie;if(!Q)return;let Re=Q.filter(Ne=>{if(PM in Ne&&ile(Ne[PM]))return!1;if("$ref"in Ne){let we=Ne.$ref.split("/").pop();return we?!_.includes(we):!0}return!0});M[re]={...ie,parameters:Re}}),z.some(re=>!!M[re])&&(b[D]=M),b},{});return{...a,paths:h,components:l}}t(war,"removeHiddenRoutesAndParams");function Par(a,{policiesConfig:s}){if(!a.paths)return a;let l=Object.entries(a.paths).reduce((_,[h,b])=>{if(!b)return _;let D={...b};return[D.delete,D.get,D.head,D.patch,D.post,D.put,D.trace,D.options].forEach(N=>{if(!N)return;let M=N["x-zuplo-route"]?.policies?.inbound?.reduce((ie,Q)=>{let Re=s.policies?.find(({name:wt})=>wt===Q);if(!Re)return ie;if(!(Re.handler.export==="CompositeInboundPolicy"))return ie.concat(Q);let we=Re.handler.options?.policies;return we?ie.concat(we):ie},[]),z=[];if(M&&M.forEach(ie=>{s.policies?.forEach(Q=>{Q.name===ie&&(Q.handler.export==="ApiAuthKeyInboundPolicy"||Q.handler.export==="ApiKeyInboundPolicy")&&!Q.handler.options?.disableAutomaticallyAddingKeyHeaderToOpenApi&&z.push(Q)})}),z.length>0){let ie=z.length>0&&z[0].handler&&z[0].handler.options&&z[0].handler.options.authHeader?z[0].handler.options.authHeader:"Authorization",Q=z.length>0&&z[0].handler&&z[0].handler.options&&(z[0].handler.options.authScheme||z[0].handler.options.authScheme==="")?z[0].handler.options.authScheme:"Bearer",Re=Q!==""?`${Q} ${Qut}`:Qut,Ne={name:ie,in:"header",required:!0,example:Re,schema:{type:"string"},description:`The \`${ie}\` header is used to authenticate with the API using your API key. Value is of the format \`${Re}\`.`};N.parameters?N.parameters.some(Tr=>"name"in Tr&&Tr.name===Ne.name)||N.parameters.unshift(Ne):N.parameters=[Ne];let we={type:"http",scheme:Q.toLowerCase()},wt="api_key";a.components?.securitySchemes?Object.values(a.components?.securitySchemes).some(Tr=>"name"in Tr&&Tr.type==="apiKey"||"type"in Tr&&Tr.type==="http"&&Tr.scheme===Q)||(a.components.securitySchemes={...a.components.securitySchemes,[wt]:we}):(a.components||(a.components={}),a.components.securitySchemes={[wt]:we});let xt={[wt]:[]};N.security?N.security.some(Tr=>Tr[wt]!==void 0)||N.security.unshift(xt):N.security=[xt]}let re=[];if(M&&M.forEach(ie=>{s.policies?.forEach(Q=>{Q.name===ie&&(Q.handler.export==="RateLimitInboundPolicy"||Q.handler.export==="ComplexRateLimitInboundPolicy")&&re.push(Q)})}),re.length>0){let ie={description:"Rate Limiting Response",content:{"application/json":{schema:{type:"object",required:["type","title","status"],examples:[{type:"https://httpproblems.com/http-status/429",title:"Too Many Requests",status:429,instance:"/foo/bar"}],properties:{type:{type:"string",example:"https://httpproblems.com/http-status/429",description:"A URI reference that identifies the problem."},title:{type:"string",example:"Too Many Requests",description:"A short, human-readable summary of the problem."},status:{type:"number",example:429,description:"The HTTP status code."},instance:{type:"string",example:"/foo/bar"}}}}}},Q={...ie,headers:{"retry-after":{description:"The number of seconds to wait before making a new request.",schema:{type:"integer",example:60}}}};a.components?.responses||a.components||(a.components={}),a.components.responses={...a.components.responses,RateLimitNoRetryAfter:ie,RateLimitWithRetryAfter:Q},N.responses||(N.responses={});let Re=re.some(Ne=>Ne.handler.options?.headerMode!=="none");N.responses[429]||(N.responses[429]={$ref:Re?"#/components/responses/RateLimitWithRetryAfter":"#/components/responses/RateLimitNoRetryAfter"})}}),_[h]=D,_},{});return{...a,paths:l}}t(Par,"enrichSpecWithZuploData");function eft(a,s){for(let l in a)l.startsWith(s)?delete a[l]:typeof a[l]=="object"&&eft(a[l],s)}t(eft,"removePropertiesByPrefix");function Aar({relativeOpenApiPath:a},s){if(!s||typeof s!="object")throw new J1({message:"The OpenAPI Document could not be parsed.",severity:"error"});if(!("info"in s)||typeof s.info!="object"||!s.info)throw new J1({message:"The OpenAPI document does not have the required 'info' property.",location:{file:a,column:0,length:0,line:0,lineText:"",namespace:"",suggestion:"Add the required 'info' property. https://spec.openapis.org/oas/v3.1.0#info-object"},severity:"error"});if(!("title"in s.info)||typeof s.info.title!="string")throw new J1({message:"The OpenAPI document does not have the required 'info.title' property.",location:{file:a,column:0,length:0,line:0,lineText:"",namespace:"",suggestion:"Add the required 'info.title' property. https://spec.openapis.org/oas/v3.1.0#info-object"},severity:"error"})}t(Aar,"assertIsZuploOpenApiSpec");import CK from"node:path";function Nar(a){if(a.length>=255)throw new TypeError("Alphabet too long");let s=new Uint8Array(256);for(let z=0;z<s.length;z++)s[z]=255;for(let z=0;z<a.length;z++){let re=a.charAt(z),ie=re.charCodeAt(0);if(s[ie]!==255)throw new TypeError(re+" is ambiguous");s[ie]=z}let l=a.length,_=a.charAt(0),h=Math.log(l)/Math.log(256),b=Math.log(256)/Math.log(l);function D(z){if(z instanceof Uint8Array||(ArrayBuffer.isView(z)?z=new Uint8Array(z.buffer,z.byteOffset,z.byteLength):Array.isArray(z)&&(z=Uint8Array.from(z))),!(z instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(z.length===0)return"";let re=0,ie=0,Q=0,Re=z.length;for(;Q!==Re&&z[Q]===0;)Q++,re++;let Ne=(Re-Q)*b+1>>>0,we=new Uint8Array(Ne);for(;Q!==Re;){let Tr=z[Q],fn=0;for(let tn=Ne-1;(Tr!==0||fn<ie)&&tn!==-1;tn--,fn++)Tr+=256*we[tn]>>>0,we[tn]=Tr%l>>>0,Tr=Tr/l>>>0;if(Tr!==0)throw new Error("Non-zero carry");ie=fn,Q++}let wt=Ne-ie;for(;wt!==Ne&&we[wt]===0;)wt++;let xt=_.repeat(re);for(;wt<Ne;++wt)xt+=a.charAt(we[wt]);return xt}t(D,"encode");function N(z){if(typeof z!="string")throw new TypeError("Expected String");if(z.length===0)return new Uint8Array;let re=0,ie=0,Q=0;for(;z[re]===_;)ie++,re++;let Re=(z.length-re)*h+1>>>0,Ne=new Uint8Array(Re);for(;z[re];){let Tr=s[z.charCodeAt(re)];if(Tr===255)return;let fn=0;for(let tn=Re-1;(Tr!==0||fn<Q)&&tn!==-1;tn--,fn++)Tr+=l*Ne[tn]>>>0,Ne[tn]=Tr%256>>>0,Tr=Tr/256>>>0;if(Tr!==0)throw new Error("Non-zero carry");Q=fn,re++}let we=Re-Q;for(;we!==Re&&Ne[we]===0;)we++;let wt=new Uint8Array(ie+(Re-we)),xt=ie;for(;we!==Re;)wt[xt++]=Ne[we++];return wt}t(N,"decodeUnsafe");function M(z){let re=N(z);if(re)return re;throw new Error("Non-base"+l+" character")}return t(M,"decode"),{encode:D,decodeUnsafe:N,decode:M}}t(Nar,"base");var tft=Nar;var Iar="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",pue=tft(Iar);var Far=!1;function sj(a,s){return{open:`\x1B[${a.join(";")}m`,close:`\x1B[${s}m`,regexp:new RegExp(`\\x1b\\[${s}m`,"g")}}t(sj,"code");function aj(a,s){return Far?`${s.open}${a.replace(s.regexp,s.open)}${s.close}`:a}t(aj,"run");function Oar(a){return aj(a,sj([31],39))}t(Oar,"red");function Lar(a){return aj(a,sj([32],39))}t(Lar,"green");function Rar(a){return aj(a,sj([33],39))}t(Rar,"yellow");function Mar(a){return aj(a,sj([34],39))}t(Mar,"blue");function jar(a){return aj(a,sj([35],39))}t(jar,"magenta");function Bar(a){return aj(a,sj([36],39))}t(Bar,"cyan");var G8r=new RegExp(["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|"),"g");var rft=[Oar,Lar,Rar,Mar,jar,Bar];function Uar(a){let s=0,l=a.length,_=0;if(l>0)for(;_<l;)s=(s<<5)-s+a.charCodeAt(_++)|0;return s}t(Uar,"hashCode");function nft(a){let s=Math.abs(Uar(a));return rft[s%rft.length]}t(nft,"generateColor");import{inspect as $ar}from"node:util";function ift(a,s,...l){let _=0,h=l.length,b=String(s).replace(/%[sdjoO%]/g,D=>{if(D==="%%")return"%";if(_>=h)return D;switch(D){case"%s":return String(l[_++]);case"%d":return Number(l[_++]).toString();case"%o":return a(l[_++]).split(`
583
583
  `).map(N=>N.trim()).join(" ");case"%O":return a(l[_++]);case"%j":try{return JSON.stringify(l[_++])}catch{return"[Circular]"}default:return D}});for(let D of l.splice(_))D===null||!(typeof D=="object"&&D!==null)?b+=" "+D:b+=" "+a(D);return b}t(ift,"format");var sft=t((a,...s)=>ift($ar,a,s),"format");var G3e=class{static{t(this,"Debugger")}manager;ns;color;last;enabled;constructor(s,l){this.manager=s,this.ns=l,this.color=nft(l),this.last=0,this.enabled=s.enabled.some(_=>_.test(l))}log(...s){if(!this.enabled)return;let l,_=s[0];typeof _=="function"?l=_():l=String(_);let h=Date.now()-(this.last||Date.now());l=sft(l,...s);let b=`${this.color(this.ns)} ${l} ${this.color(`+${h}ms`)}`;console.log(b),this.last=Date.now()}},K3e=class{static{t(this,"DebugManager")}debuggers;enabled;constructor(s){this.debuggers=new Map,this.enabled=s??[]}};function zar(a){return!a||a.length===0?[]:(a=a.replace(/\s/g,"").replace(/\*/g,".+"),a.split(",").map(s=>new RegExp(`^${s}$`)))}t(zar,"extract");var due;function mue(a){due||(due=new K3e(zar(process.env.DEBUG)));let s=new G3e(due,a);return due.debuggers.set(a,s),Object.assign(s.log.bind(s),{self:s})}t(mue,"debug");var U3=class extends Error{static{t(this,"RuntimeError")}extensionMembers;constructor(s,l){typeof s=="string"?super(s,l):(super(s.message,l),this.extensionMembers=s.extensionMembers),this.name="RuntimeError"}};var cO=mue("zuplo:runtime:external-service");function Jar(){let a,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:s}=F0.instance.runtime;if(s&&s!=="undefined")try{let l=atob(s);a=JSON.parse(l)}catch{}return a}t(Jar,"getServiceAuth");async function aft(a,s){let l=Jar();if(l)if(cO(`Using external service auth. ClientId: ${l.clientId})`),typeof a=="string"){let _=new URL(a),h=_.hostname,b=s??{},D=new Headers(b.headers||{});D.set("CF-Access-Client-Id",l.clientId),D.set("CF-Access-Client-Secret",l.clientSecret),b.headers=D;let N;if(l.customServiceMapping&&l.customServiceMapping[h])N=`https://${l.customServiceMapping[h]}`;else if(F0.instance.useLegacyServiceRouting)N=`https://${h}.zuptunnel.com`;else{cO("Using sha256 service routing");let re=F0.instance.build;if(re.ACCOUNT_NAME&&re.PROJECT_NAME&&re.ENVIRONMENT_TYPE){let ie=await qar(h,re.ACCOUNT_NAME,re.PROJECT_NAME,re.ENVIRONMENT_TYPE),Q=cft(re.ENVIRONMENT_TYPE),Re=await Y3e(`${re.ACCOUNT_NAME}-${re.PROJECT_NAME}-${Q}`);Re==="40d7ad502f5d743997999594c177184a00161a77865423511f3a1ea21eb5a5e"||Re==="d05bffe8fa91a300187d2cf43e8aa4a56bd809c442ae10d1ee49af7d29a5a11"?N=`https://${ie}.zuptunnel.com`:N=`https://${ie}.t.zuplo.app`}else throw cO("Cannot use sha256 service routing, missing build variables"),new U3("Failed to generate fully qualified tunnel url.")}let M=new URL(`${N}${_.pathname}${_.search}`);cO(`Calling external service: ${M.toString()}`);let z=await SG(M.toString(),b);if(z.status===403&&z.headers.get("cf-access-domain")!==null)throw TG.console.error("403 Forbidden when calling external service.",{clientId:l.clientId,tunnelHost:N}),new U3("Could not connect to secure tunnel.");return z}else throw cO("Cannot call external service with Request object"),new U3("Currently, we only support fetch(<some_string>, ...).");else throw cO("There is no external service auth configured for this zup."),new U3("There are no external services configured for this zup.")}t(aft,"externalServiceHandler");async function oft(a,s){if(typeof a=="string"){let l=new URL(a),h=`http://${l.hostname}.zuplo.svc.cluster.local:9000`,b=new URL(`${h}${l.pathname}${l.search}`);return await SG(b.toString(),s)}else throw new U3("Currently, we only support fetch(<some_string>, ...).")}t(oft,"clusterServiceHandler");async function qar(a,s,l,_){let h=a.toLowerCase(),b=s.toLowerCase(),D=l.toLowerCase(),N=cft(_);cO(`Hashing service name: ${b}-${h}.${b}-${D}-${N}`);let M=await Y3e(`${b}-${h}`),z=await Y3e(`${b}-${D}-${N}`);return`${M}.${z}`}t(qar,"hashServiceName");async function Y3e(a){let s=new TextEncoder().encode(a),l=await crypto.subtle.digest("SHA-256",s);return Array.from(new Uint8Array(l)).map(b=>b.toString(16).padStart(2,"0")).join("").slice(0,-1)}t(Y3e,"hashSegment");function cft(a){let s=a.toLowerCase();switch(s){case"production":case"preview":return s;default:return"working-copy"}}t(cft,"sanitizeEnvironmentType");var X3e=new Map;X3e.set("service:",aft);X3e.set("local:",oft);var SG=globalThis.fetch;function Q3e(a,s){let l=Var(s);if(typeof a=="string"){let _=new URL(a),h=X3e.get(_.protocol);return h?h(a,l):SG(a,l)}else return SG(a,l)}t(Q3e,"internalFetch");globalThis.fetch=Q3e;var Var=t(a=>{if(!a||a instanceof Request)return a;let s=a;if(!s.zuplo)return a;let l=a;return l.cf={cacheEverything:s.zuplo?.cacheEverything,cacheTtl:s.zuplo?.cacheTtlSeconds},delete a.zuplo,a},"transformInit");var War={console:{log:console.log.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console),debug:console.debug.bind(console),assert:console.assert.bind(console),clear:console.clear.bind(console),count:console.count.bind(console),countReset:console.countReset.bind(console),dir:console.dir.bind(console),dirxml:console.dirxml.bind(console),group:console.group.bind(console),groupCollapsed:console.groupCollapsed.bind(console),groupEnd:console.groupEnd.bind(console),table:console.table.bind(console),time:console.time.bind(console),timeEnd:console.timeEnd.bind(console),timeLog:console.timeLog.bind(console),timeStamp:console.timeStamp.bind(console),trace:console.trace.bind(console),profile:console.profile.bind(console),profileEnd:console.profileEnd.bind(console)},fetch:Q3e},TG=War;var Z3e="2025-02-06",lft=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1,allowCustomPorts:!1,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1,allowCustomPorts:!1,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!1,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!1,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2024-09-02":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!0,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2025-02-06":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!0,removeLegacyLogInitialization:!0,useForwardRedirectsPropOnUrlForwardHandler:!0}});function uft(){return new F0({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:Z3e,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,IS_LOCAL_DEVELOPMENT:!1,COMPATIBILITY_FLAGS:lft[Z3e]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}t(uft,"getMockEnvironment");var F0=class a{static{t(this,"Environment")}config;static#r;static#n=!1;static initialize(s){this.#r||(this.#r=new a(s),this.#n=!0)}static get instance(){return this.#n||(TG.console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#r=uft()),this.#r}constructor({build:s,runtime:l}){let _;try{if(l.ZUPLO_SYSTEM_CONFIGURATIONS){let h=new TextDecoder().decode(pue.decode(l.ZUPLO_SYSTEM_CONFIGURATIONS)),b=JSON.parse(h);for(let D of Object.keys(b))l[D]||(l[D]=b[D])}if(l.__ZUPLO_CONFIG){let h=atob(l.__ZUPLO_CONFIG);_=JSON.parse(h)}}catch(h){TG.console.error("Failed to parse runtime configuration",h)}this.config=_??{},this.build=s,this.runtime=l,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get zuploEdgeApiUrl(){return this.config.zuplo_edge_api_url??"https://api.zuploedge.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get zuploClientAuthBucketId(){return this.config.zuplo_auth_client_bucket_id??"auth_o8PUdhKxSTOiB794GWPwLQCD"}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get developerApiUrl(){return this.config.developer_api_url??"https://dev.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuploedge.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuploedge.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuploedge.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuploedge.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get authClientId(){return this.runtime.__ZUPLO_AUTH_CLIENT_ID}get authClientSecret(){return this.runtime.__ZUPLO_AUTH_CLIENT_SECRET}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.IS_LOCAL_DEVELOPMENT}get isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var Har=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function fft(a){return a.startsWith("__ZUPLO")||a.startsWith("ZUPLO_")?!Har.includes(a)&&!a.startsWith("ZUPLO_PUBLIC_"):!1}t(fft,"isRestrictedEnvVariableName");function _ft(a){return!!a.startsWith("ZUPLO_")}t(_ft,"isZuploReadableEnvVariableName");var FFr=new Proxy({},{get(a,s){let l=String(s);switch(l){case"ZUPLO_ENVIRONMENT_TYPE":return F0.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return F0.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return F0.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return F0.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return F0.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return F0.instance.build.BUILD_ID;case"ZUPLO_COMPATIBILITY_DATE":return F0.instance.build.COMPATIBILITY_DATE}if(!(fft(l)&&!_ft(l)))return F0.instance.runtime[l]}});function xG(a,s,l){return`_${EA(`${a}_${s}_${l}`)}`}t(xG,"getRawOperationDataIdentifierName");function eNe(a,s,l,_){return`_${EA(a.toLowerCase())}_${s.toLowerCase()}_${l.toLowerCase()}_${_.toLowerCase()}`}t(eNe,"getIdForParameterSchema");function tNe(a,s,l){return`_${EA(a.toLowerCase())}_${s.toLowerCase()}_rb_${EA(l.toLowerCase())}`}t(tNe,"getIdForRequestBodySchema");function CG(a,s){return`_${EA(a)}_${EA(s)}`}t(CG,"getIdForRefSchema");function EA(a){let s=a.replace(/\[/g,"_LBRACKET_").replace(/\]/g,"_RBRACKET_").replace(/\{/g,"_LCURLY_").replace(/\}/g,"_RCURLY_").replace(/\//g,"_SLASH_").replace(/-/g,"_DASH_").replace(/\./g,"_DOT_").replace(/\+/g,"_PLUS_").replace(/:/g,"_COLON_").replace(/@/g,"_AT_").replace(/\$/g,"_DOLLAR_").replace(/[^a-zA-Z0-9_]/g,"_");return/^[a-zA-Z_]/.test(s)||(s="_"+s),s}t(EA,"sanitizedIdentifierName");var qht=ap(rpt(),1);var UG=class{static{t(this,"R")}type=3;name="";prefix="";value="";suffix="";modifier=3;constructor(a,s,l,_,h,b){this.type=a,this.name=s,this.prefix=l,this.value=_,this.suffix=h,this.modifier=b}hasCustomName(){return this.name!==""&&typeof this.name!="number"}},Ulr=/[$_\p{ID_Start}]/u,$lr=/[$_\u200C\u200D\p{ID_Continue}]/u,KNe=".*";function zlr(a,s){return(s?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test(a)}t(zlr,"Re");function spt(a,s=!1){let l=[],_=0;for(;_<a.length;){let h=a[_],b=t(function(D){if(!s)throw new TypeError(D);l.push({type:"INVALID_CHAR",index:_,value:a[_++]})},"c");if(h==="*"){l.push({type:"ASTERISK",index:_,value:a[_++]});continue}if(h==="+"||h==="?"){l.push({type:"OTHER_MODIFIER",index:_,value:a[_++]});continue}if(h==="\\"){l.push({type:"ESCAPED_CHAR",index:_++,value:a[_++]});continue}if(h==="{"){l.push({type:"OPEN",index:_,value:a[_++]});continue}if(h==="}"){l.push({type:"CLOSE",index:_,value:a[_++]});continue}if(h===":"){let D="",N=_+1;for(;N<a.length;){let M=a.substr(N,1);if(N===_+1&&Ulr.test(M)||N!==_+1&&$lr.test(M)){D+=a[N++];continue}break}if(!D){b(`Missing parameter name at ${_}`);continue}l.push({type:"NAME",index:_,value:D}),_=N;continue}if(h==="("){let D=1,N="",M=_+1,z=!1;if(a[M]==="?"){b(`Pattern cannot start with "?" at ${M}`);continue}for(;M<a.length;){if(!zlr(a[M],!1)){b(`Invalid character '${a[M]}' at ${M}.`),z=!0;break}if(a[M]==="\\"){N+=a[M++]+a[M++];continue}if(a[M]===")"){if(D--,D===0){M++;break}}else if(a[M]==="("&&(D++,a[M+1]!=="?")){b(`Capturing groups are not allowed at ${M}`),z=!0;break}N+=a[M++]}if(z)continue;if(D){b(`Unbalanced pattern at ${_}`);continue}if(!N){b(`Missing pattern at ${_}`);continue}l.push({type:"REGEX",index:_,value:N}),_=M;continue}l.push({type:"CHAR",index:_,value:a[_++]})}return l.push({type:"END",index:_,value:""}),l}t(spt,"v");function apt(a,s={}){let l=spt(a);s.delimiter??="/#?",s.prefixes??="./";let _=`[^${RT(s.delimiter)}]+?`,h=[],b=0,D=0,N="",M=new Set,z=t(fn=>{if(D<l.length&&l[D].type===fn)return l[D++].value},"a"),re=t(()=>z("OTHER_MODIFIER")??z("ASTERISK"),"f"),ie=t(fn=>{let tn=z(fn);if(tn!==void 0)return tn;let{type:cn,index:Cr}=l[D];throw new TypeError(`Unexpected ${cn} at ${Cr}, expected ${fn}`)},"d"),Q=t(()=>{let fn="",tn;for(;tn=z("CHAR")??z("ESCAPED_CHAR");)fn+=tn;return fn},"T"),Re=t(fn=>fn,"Se"),Ne=s.encodePart||Re,we="",wt=t(fn=>{we+=fn},"U"),xt=t(()=>{we.length&&(h.push(new UG(3,"","",Ne(we),"",3)),we="")},"$"),Tr=t((fn,tn,cn,Cr,vr)=>{let fs=3;switch(vr){case"?":fs=1;break;case"*":fs=0;break;case"+":fs=2;break}if(!tn&&!cn&&fs===3){wt(fn);return}if(xt(),!tn&&!cn){if(!fn)return;h.push(new UG(3,"","",Ne(fn),"",fs));return}let Fi;cn?cn==="*"?Fi=KNe:Fi=cn:Fi=_;let Ho=2;Fi===_?(Ho=1,Fi=""):Fi===KNe&&(Ho=0,Fi="");let di;if(tn?di=tn:cn&&(di=b++),M.has(di))throw new TypeError(`Duplicate name '${di}'.`);M.add(di),h.push(new UG(Ho,di,Ne(fn),Fi,Ne(Cr),fs))},"V");for(;D<l.length;){let fn=z("CHAR"),tn=z("NAME"),cn=z("REGEX");if(!tn&&!cn&&(cn=z("ASTERISK")),tn||cn){let vr=fn??"";s.prefixes.indexOf(vr)===-1&&(wt(vr),vr=""),xt();let fs=re();Tr(vr,tn,cn,"",fs);continue}let Cr=fn??z("ESCAPED_CHAR");if(Cr){wt(Cr);continue}if(z("OPEN")){let vr=Q(),fs=z("NAME"),Fi=z("REGEX");!fs&&!Fi&&(Fi=z("ASTERISK"));let Ho=Q();ie("CLOSE");let di=re();Tr(vr,fs,Fi,Ho,di);continue}xt(),ie("END")}return h}t(apt,"D");function RT(a){return a.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}t(RT,"S");function npt(a){return a&&a.ignoreCase?"ui":"u"}t(npt,"X");function Jlr(a,s,l){return opt(apt(a,l),s,l)}t(Jlr,"Z");function hj(a){switch(a){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}t(hj,"k");function opt(a,s,l={}){l.delimiter??="/#?",l.prefixes??="./",l.sensitive??=!1,l.strict??=!1,l.end??=!0,l.start??=!0,l.endsWith="";let _=l.start?"^":"";for(let N of a){if(N.type===3){N.modifier===3?_+=RT(N.value):_+=`(?:${RT(N.value)})${hj(N.modifier)}`;continue}s&&s.push(N.name);let M=`[^${RT(l.delimiter)}]+?`,z=N.value;if(N.type===1?z=M:N.type===0&&(z=KNe),!N.prefix.length&&!N.suffix.length){N.modifier===3||N.modifier===1?_+=`(${z})${hj(N.modifier)}`:_+=`((?:${z})${hj(N.modifier)})`;continue}if(N.modifier===3||N.modifier===1){_+=`(?:${RT(N.prefix)}(${z})${RT(N.suffix)})`,_+=hj(N.modifier);continue}_+=`(?:${RT(N.prefix)}`,_+=`((?:${z})(?:`,_+=RT(N.suffix),_+=RT(N.prefix),_+=`(?:${z}))*)${RT(N.suffix)})`,N.modifier===0&&(_+="?")}let h=`[${RT(l.endsWith)}]|$`,b=`[${RT(l.delimiter)}]`;if(l.end)return l.strict||(_+=`${b}?`),l.endsWith.length?_+=`(?=${h})`:_+="$",new RegExp(_,npt(l));l.strict||(_+=`(?:${b}(?=${h}))?`);let D=!1;if(a.length){let N=a[a.length-1];N.type===3&&N.modifier===3&&(D=l.delimiter.indexOf(N)>-1)}return D||(_+=`(?=${b}|${h})`),new RegExp(_,npt(l))}t(opt,"F");var q3={delimiter:"",prefixes:"",sensitive:!0,strict:!0},qlr={delimiter:".",prefixes:"",sensitive:!0,strict:!0},Vlr={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function Wlr(a,s){return a.length?a[0]==="/"?!0:!s||a.length<2?!1:(a[0]=="\\"||a[0]=="{")&&a[1]=="/":!1}t(Wlr,"J");function cpt(a,s){return a.startsWith(s)?a.substring(s.length,a.length):a}t(cpt,"Q");function Hlr(a,s){return a.endsWith(s)?a.substr(0,a.length-s.length):a}t(Hlr,"Ee");function lpt(a){return!a||a.length<2?!1:a[0]==="["||(a[0]==="\\"||a[0]==="{")&&a[1]==="["}t(lpt,"W");var upt=["ftp","file","http","https","ws","wss"];function fpt(a){if(!a)return!0;for(let s of upt)if(a.test(s))return!0;return!1}t(fpt,"N");function Glr(a,s){if(a=cpt(a,"#"),s||a==="")return a;let l=new URL("https://example.com");return l.hash=a,l.hash?l.hash.substring(1,l.hash.length):""}t(Glr,"te");function Klr(a,s){if(a=cpt(a,"?"),s||a==="")return a;let l=new URL("https://example.com");return l.search=a,l.search?l.search.substring(1,l.search.length):""}t(Klr,"re");function Ylr(a,s){return s||a===""?a:lpt(a)?dpt(a):ppt(a)}t(Ylr,"ne");function Xlr(a,s){if(s||a==="")return a;let l=new URL("https://example.com");return l.password=a,l.password}t(Xlr,"se");function Qlr(a,s){if(s||a==="")return a;let l=new URL("https://example.com");return l.username=a,l.username}t(Qlr,"ie");function Zlr(a,s,l){if(l||a==="")return a;if(s&&!upt.includes(s))return new URL(`${s}:${a}`).pathname;let _=a[0]=="/";return a=new URL(_?a:"/-"+a,"https://example.com").pathname,_||(a=a.substring(2,a.length)),a}t(Zlr,"ae");function eur(a,s,l){return _pt(s)===a&&(a=""),l||a===""?a:mpt(a)}t(eur,"oe");function tur(a,s){return a=Hlr(a,":"),s||a===""?a:YNe(a)}t(tur,"ce");function _pt(a){switch(a){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}t(_pt,"_");function YNe(a){if(a==="")return a;if(/^[-+.A-Za-z0-9]*$/.test(a))return a.toLowerCase();throw new TypeError(`Invalid protocol '${a}'.`)}t(YNe,"y");function rur(a){if(a==="")return a;let s=new URL("https://example.com");return s.username=a,s.username}t(rur,"le");function nur(a){if(a==="")return a;let s=new URL("https://example.com");return s.password=a,s.password}t(nur,"fe");function ppt(a){if(a==="")return a;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test(a))throw new TypeError(`Invalid hostname '${a}'`);let s=new URL("https://example.com");return s.hostname=a,s.hostname}t(ppt,"z");function dpt(a){if(a==="")return a;if(/[^0-9a-fA-F[\]:]/g.test(a))throw new TypeError(`Invalid IPv6 hostname '${a}'`);return a.toLowerCase()}t(dpt,"j");function mpt(a){if(a===""||/^[0-9]*$/.test(a)&&parseInt(a)<=65535)return a;throw new TypeError(`Invalid port '${a}'.`)}t(mpt,"K");function iur(a){if(a==="")return a;let s=new URL("https://example.com");return s.pathname=a[0]!=="/"?"/-"+a:a,a[0]!=="/"?s.pathname.substring(2,s.pathname.length):s.pathname}t(iur,"he");function sur(a){return a===""?a:new URL(`data:${a}`).pathname}t(sur,"ue");function aur(a){if(a==="")return a;let s=new URL("https://example.com");return s.search=a,s.search.substring(1,s.search.length)}t(aur,"de");function our(a){if(a==="")return a;let s=new URL("https://example.com");return s.hash=a,s.hash.substring(1,s.hash.length)}t(our,"pe");var cur=class{static{t(this,"H")}#r;#n=[];#e={};#t=0;#s=1;#p=0;#a=0;#_=0;#c=0;#l=!1;constructor(a){this.#r=a}get result(){return this.#e}parse(){for(this.#n=spt(this.#r,!0);this.#t<this.#n.length;this.#t+=this.#s){if(this.#s=1,this.#n[this.#t].type==="END"){if(this.#a===0){this.#v(),this.#D()?this.#i(9,1):this.#y()?this.#i(8,1):this.#i(7,0);continue}else if(this.#a===2){this.#d(5);continue}this.#i(10,0);break}if(this.#_>0)if(this.#o())this.#_-=1;else continue;if(this.#w()){this.#_+=1;continue}switch(this.#a){case 0:this.#g()&&this.#d(1);break;case 1:if(this.#g()){this.#I();let a=7,s=1;this.#E()?(a=2,s=3):this.#l&&(a=2),this.#i(a,s)}break;case 2:this.#x()?this.#d(3):(this.#C()||this.#y()||this.#D())&&this.#d(5);break;case 3:this.#b()?this.#i(4,1):this.#x()&&this.#i(5,1);break;case 4:this.#x()&&this.#i(5,1);break;case 5:this.#N()?this.#c+=1:this.#S()&&(this.#c-=1),this.#k()&&!this.#c?this.#i(6,1):this.#C()?this.#i(7,0):this.#y()?this.#i(8,1):this.#D()&&this.#i(9,1);break;case 6:this.#C()?this.#i(7,0):this.#y()?this.#i(8,1):this.#D()&&this.#i(9,1);break;case 7:this.#y()?this.#i(8,1):this.#D()&&this.#i(9,1);break;case 8:this.#D()&&this.#i(9,1);break;case 9:break;case 10:break}}this.#e.hostname!==void 0&&this.#e.port===void 0&&(this.#e.port="")}#i(a,s){switch(this.#a){case 0:break;case 1:this.#e.protocol=this.#T();break;case 2:break;case 3:this.#e.username=this.#T();break;case 4:this.#e.password=this.#T();break;case 5:this.#e.hostname=this.#T();break;case 6:this.#e.port=this.#T();break;case 7:this.#e.pathname=this.#T();break;case 8:this.#e.search=this.#T();break;case 9:this.#e.hash=this.#T();break;case 10:break}this.#a!==0&&a!==10&&([1,2,3,4].includes(this.#a)&&[6,7,8,9].includes(a)&&(this.#e.hostname??=""),[1,2,3,4,5,6].includes(this.#a)&&[8,9].includes(a)&&(this.#e.pathname??=this.#l?"/":""),[1,2,3,4,5,6,7].includes(this.#a)&&a===9&&(this.#e.search??="")),this.#f(a,s)}#f(a,s){this.#a=a,this.#p=this.#t+s,this.#t+=s,this.#s=0}#v(){this.#t=this.#p,this.#s=0}#d(a){this.#v(),this.#a=a}#u(a){return a<0&&(a=this.#n.length-a),a<this.#n.length?this.#n[a]:this.#n[this.#n.length-1]}#m(a,s){let l=this.#u(a);return l.value===s&&(l.type==="CHAR"||l.type==="ESCAPED_CHAR"||l.type==="INVALID_CHAR")}#g(){return this.#m(this.#t,":")}#E(){return this.#m(this.#t+1,"/")&&this.#m(this.#t+2,"/")}#x(){return this.#m(this.#t,"@")}#b(){return this.#m(this.#t,":")}#k(){return this.#m(this.#t,":")}#C(){return this.#m(this.#t,"/")}#y(){if(this.#m(this.#t,"?"))return!0;if(this.#n[this.#t].value!=="?")return!1;let a=this.#u(this.#t-1);return a.type!=="NAME"&&a.type!=="REGEX"&&a.type!=="CLOSE"&&a.type!=="ASTERISK"}#D(){return this.#m(this.#t,"#")}#w(){return this.#n[this.#t].type=="OPEN"}#o(){return this.#n[this.#t].type=="CLOSE"}#N(){return this.#m(this.#t,"[")}#S(){return this.#m(this.#t,"]")}#T(){let a=this.#n[this.#t],s=this.#u(this.#p).index;return this.#r.substring(s,a.index)}#I(){let a={};Object.assign(a,q3),a.encodePart=YNe;let s=Jlr(this.#T(),void 0,a);this.#l=fpt(s)}},GNe=["protocol","username","password","hostname","port","pathname","search","hash"],J3="*";function ipt(a,s){if(typeof a!="string")throw new TypeError("parameter 1 is not of type 'string'.");let l=new URL(a,s);return{protocol:l.protocol.substring(0,l.protocol.length-1),username:l.username,password:l.password,hostname:l.hostname,port:l.port,pathname:l.pathname,search:l.search!==""?l.search.substring(1,l.search.length):void 0,hash:l.hash!==""?l.hash.substring(1,l.hash.length):void 0}}t(ipt,"ge");function AA(a,s){return s?BG(a):a}t(AA,"b");function jG(a,s,l){let _;if(typeof s.baseURL=="string")try{_=new URL(s.baseURL),s.protocol===void 0&&(a.protocol=AA(_.protocol.substring(0,_.protocol.length-1),l)),!l&&s.protocol===void 0&&s.hostname===void 0&&s.port===void 0&&s.username===void 0&&(a.username=AA(_.username,l)),!l&&s.protocol===void 0&&s.hostname===void 0&&s.port===void 0&&s.username===void 0&&s.password===void 0&&(a.password=AA(_.password,l)),s.protocol===void 0&&s.hostname===void 0&&(a.hostname=AA(_.hostname,l)),s.protocol===void 0&&s.hostname===void 0&&s.port===void 0&&(a.port=AA(_.port,l)),s.protocol===void 0&&s.hostname===void 0&&s.port===void 0&&s.pathname===void 0&&(a.pathname=AA(_.pathname,l)),s.protocol===void 0&&s.hostname===void 0&&s.port===void 0&&s.pathname===void 0&&s.search===void 0&&(a.search=AA(_.search.substring(1,_.search.length),l)),s.protocol===void 0&&s.hostname===void 0&&s.port===void 0&&s.pathname===void 0&&s.search===void 0&&s.hash===void 0&&(a.hash=AA(_.hash.substring(1,_.hash.length),l))}catch{throw new TypeError(`invalid baseURL '${s.baseURL}'.`)}if(typeof s.protocol=="string"&&(a.protocol=tur(s.protocol,l)),typeof s.username=="string"&&(a.username=Qlr(s.username,l)),typeof s.password=="string"&&(a.password=Xlr(s.password,l)),typeof s.hostname=="string"&&(a.hostname=Ylr(s.hostname,l)),typeof s.port=="string"&&(a.port=eur(s.port,a.protocol,l)),typeof s.pathname=="string"){if(a.pathname=s.pathname,_&&!Wlr(a.pathname,l)){let h=_.pathname.lastIndexOf("/");h>=0&&(a.pathname=AA(_.pathname.substring(0,h+1),l)+a.pathname)}a.pathname=Zlr(a.pathname,a.protocol,l)}return typeof s.search=="string"&&(a.search=Klr(s.search,l)),typeof s.hash=="string"&&(a.hash=Glr(s.hash,l)),a}t(jG,"w");function BG(a){return a.replace(/([+*?:{}()\\])/g,"\\$1")}t(BG,"C");function lur(a){return a.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}t(lur,"Oe");function uur(a,s){s.delimiter??="/#?",s.prefixes??="./",s.sensitive??=!1,s.strict??=!1,s.end??=!0,s.start??=!0,s.endsWith="";let l=".*",_=`[^${lur(s.delimiter)}]+?`,h=/[$_\u200C\u200D\p{ID_Continue}]/u,b="";for(let D=0;D<a.length;++D){let N=a[D];if(N.type===3){if(N.modifier===3){b+=BG(N.value);continue}b+=`{${BG(N.value)}}${hj(N.modifier)}`;continue}let M=N.hasCustomName(),z=!!N.suffix.length||!!N.prefix.length&&(N.prefix.length!==1||!s.prefixes.includes(N.prefix)),re=D>0?a[D-1]:null,ie=D<a.length-1?a[D+1]:null;if(!z&&M&&N.type===1&&N.modifier===3&&ie&&!ie.prefix.length&&!ie.suffix.length)if(ie.type===3){let Q=ie.value.length>0?ie.value[0]:"";z=h.test(Q)}else z=!ie.hasCustomName();if(!z&&!N.prefix.length&&re&&re.type===3){let Q=re.value[re.value.length-1];z=s.prefixes.includes(Q)}z&&(b+="{"),b+=BG(N.prefix),M&&(b+=`:${N.name}`),N.type===2?b+=`(${N.value})`:N.type===1?M||(b+=`(${_})`):N.type===0&&(!M&&(!re||re.type===3||re.modifier!==3||z||N.prefix!=="")?b+="*":b+=`(${l})`),N.type===1&&M&&N.suffix.length&&h.test(N.suffix[0])&&(b+="\\"),b+=BG(N.suffix),z&&(b+="}"),N.modifier!==3&&(b+=hj(N.modifier))}return b}t(uur,"ke");var hpt=class{static{t(this,"me")}#r;#n={};#e={};#t={};#s={};#p=!1;constructor(a={},s,l){try{let _;if(typeof s=="string"?_=s:l=s,typeof a=="string"){let N=new cur(a);if(N.parse(),a=N.result,_===void 0&&typeof a.protocol!="string")throw new TypeError("A base URL must be provided for a relative constructor string.");a.baseURL=_}else{if(!a||typeof a!="object")throw new TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(_)throw new TypeError("parameter 1 is not of type 'string'.")}typeof l>"u"&&(l={ignoreCase:!1});let h={ignoreCase:l.ignoreCase===!0},b={pathname:J3,protocol:J3,username:J3,password:J3,hostname:J3,port:J3,search:J3,hash:J3};this.#r=jG(b,a,!0),_pt(this.#r.protocol)===this.#r.port&&(this.#r.port="");let D;for(D of GNe){if(!(D in this.#r))continue;let N={},M=this.#r[D];switch(this.#e[D]=[],D){case"protocol":Object.assign(N,q3),N.encodePart=YNe;break;case"username":Object.assign(N,q3),N.encodePart=rur;break;case"password":Object.assign(N,q3),N.encodePart=nur;break;case"hostname":Object.assign(N,qlr),lpt(M)?N.encodePart=dpt:N.encodePart=ppt;break;case"port":Object.assign(N,q3),N.encodePart=mpt;break;case"pathname":fpt(this.#n.protocol)?(Object.assign(N,Vlr,h),N.encodePart=iur):(Object.assign(N,q3,h),N.encodePart=sur);break;case"search":Object.assign(N,q3,h),N.encodePart=aur;break;case"hash":Object.assign(N,q3,h),N.encodePart=our;break}try{this.#s[D]=apt(M,N),this.#n[D]=opt(this.#s[D],this.#e[D],N),this.#t[D]=uur(this.#s[D],N),this.#p=this.#p||this.#s[D].some(z=>z.type===2)}catch{throw new TypeError(`invalid ${D} pattern '${this.#r[D]}'.`)}}}catch(_){throw new TypeError(`Failed to construct 'URLPattern': ${_.message}`)}}test(a={},s){let l={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof a!="string"&&s)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof a>"u")return!1;try{typeof a=="object"?l=jG(l,a,!1):l=jG(l,ipt(a,s),!1)}catch{return!1}let _;for(_ of GNe)if(!this.#n[_].exec(l[_]))return!1;return!0}exec(a={},s){let l={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof a!="string"&&s)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof a>"u")return;try{typeof a=="object"?l=jG(l,a,!1):l=jG(l,ipt(a,s),!1)}catch{return null}let _={};s?_.inputs=[a,s]:_.inputs=[a];let h;for(h of GNe){let b=this.#n[h].exec(l[h]);if(!b)return null;let D={};for(let[N,M]of this.#e[h].entries())if(typeof M=="string"||typeof M=="number"){let z=b[N+1];D[M]=z}_[h]={input:l[h]??"",groups:D}}return _}static compareComponent(a,s,l){let _=t((N,M)=>{for(let z of["type","modifier","prefix","value","suffix"]){if(N[z]<M[z])return-1;if(N[z]!==M[z])return 1}return 0},"o"),h=new UG(3,"","","","",3),b=new UG(0,"","","","",3),D=t((N,M)=>{let z=0;for(;z<Math.min(N.length,M.length);++z){let re=_(N[z],M[z]);if(re)return re}return N.length===M.length?0:_(N[z]??h,M[z]??h)},"s");return!s.#t[a]&&!l.#t[a]?0:s.#t[a]&&!l.#t[a]?D(s.#s[a],[b]):!s.#t[a]&&l.#t[a]?D([b],l.#s[a]):D(s.#s[a],l.#s[a])}get protocol(){return this.#t.protocol}get username(){return this.#t.username}get password(){return this.#t.password}get hostname(){return this.#t.hostname}get port(){return this.#t.port}get pathname(){return this.#t.pathname}get search(){return this.#t.search}get hash(){return this.#t.hash}get hasRegExpGroups(){return this.#p}};globalThis.URLPattern||(globalThis.URLPattern=hpt);import{AssertionError as fur}from"node:assert";function NA(a,s){if(a===!1)throw new fur({message:s})}t(NA,"assert");var ec;(function(a){a.Object="Object",a.Property="Property",a.Array="Array",a.Literal="Literal",a.TemplateString="TemplateString",a.Identifier="Identifier",a.FunctionCall="FunctionCall",a.Raw="Raw"})(ec||(ec={}));function gj(a){return a.type===ec.Object}t(gj,"isAstObject");function IA(a){return a.type===ec.Property}t(IA,"isAstProperty");function gpt(a){return a.type===ec.Array}t(gpt,"isAstArray");function yj(a){return a.type===ec.Literal}t(yj,"isAstLiteral");function V3(a){if(a===void 0)throw new Error("Node is undefined");if(!gj(a))throw new Error("Node is not object")}t(V3,"assertAstObject");import{findNodeAtLocation as _ur,getNodeValue as pur,printParseErrorCode as dur,visit as mur}from"jsonc-parser";var hur={DEFAULT:{allowTrailingComma:!1}};function $G(a,s=[],l=hur.DEFAULT){let _={type:"array",offset:-1,length:-1,line:-1,column:-1,children:[],parent:void 0};function h(M){_.type==="property"&&(_.length=M-_.offset,_=_.parent)}t(h,"ensurePropertyComplete");function b(M){return _.children?.push(M),M}t(b,"onValue"),mur(a,{onObjectBegin:t((M,z,re)=>{_=b({type:"object",offset:M,length:-1,line:z+1,column:re+1,parent:_,children:[]})},"onObjectBegin"),onObjectProperty:t((M,z,re,ie,Q)=>{_=b({type:"property",offset:z,length:-1,line:ie+1,column:Q+1,parent:_,children:[]}),_.children?.push({type:"string",value:M,offset:z,length:re,line:ie,column:Q,parent:_})},"onObjectProperty"),onObjectEnd:t((M,z)=>{h(M+z),_.length=M+z-_.offset,_=_.parent,h(M+z)},"onObjectEnd"),onArrayBegin:t((M,z,re,ie)=>{_=b({type:"array",offset:M,length:-1,line:re+1,column:ie+1,parent:_,children:[]})},"onArrayBegin"),onArrayEnd:t((M,z)=>{_.length=M+z-_.offset,_=_.parent,h(M+z)},"onArrayEnd"),onLiteralValue:t((M,z,re,ie,Q)=>{b({type:gur(M),offset:z,length:re,line:ie+1,column:Q+1,parent:_,value:M}),h(z+re)},"onLiteralValue"),onSeparator:t((M,z)=>{_.type==="property"&&(M===":"?_.colonOffset=z:M===","&&h(z))},"onSeparator"),onError:t((M,z,re,ie,Q)=>{s.push({error:M,offset:z,length:re,line:ie+1,column:Q+1})},"onError")},l);let N=_.children[0];return N&&delete N.parent,N}t($G,"parse");function gur(a){switch(typeof a){case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"object":{if(a){if(Array.isArray(a))return"array"}else return"null";return"object"}default:return"null"}}t(gur,"getNodeType");function XNe(a,s){return _ur(a,s)}t(XNe,"findNodeAtLocation");function zG(a){return pur(a)}t(zG,"getNodeValue");function ypt(a){return dur(a)}t(ypt,"printParseErrorCode");var JG=class{static{t(this,"AstAdapter")}parse(s){let _=$G(s,[]);if(_)return this.parseNode(_,void 0);throw new Error("Failed to parse JSON")}convert(s){return this.parseNode(s,void 0)}parseNode(s,l){switch(s.type){case"object":return this.createObject(s,l);case"array":return this.createArray(s,l);case"property":return this.createProperty(s,l);case"string":return this.createLiteral(s,l);case"number":return this.createLiteral(s,l);case"boolean":return this.createLiteral(s,l);case"null":return this.createLiteral(s,l)}}createLiteral(s,l){return{type:ec.Literal,location:{line:s.line,column:s.column},parent:l,value:s.type==="null"?null:s.value}}createObject(s,l){let _={type:ec.Object,children:[],parent:l,location:{line:s.line,column:s.column}};return s.children?.forEach(h=>{_.children.push(this.parseNode(h,_))}),_}createProperty(s,l){NA(s.children?.length===2,"Invalid property node");let _={type:ec.Property,location:{line:s.line,column:s.column},parent:l,name:null,value:null};return _.name={value:s.children[0].value,location:{line:s.line,column:s.column},type:ec.Identifier,parent:_},_.value=this.parseNode(s.children[1],_),_}createArray(s,l){let _={type:ec.Array,location:{line:s.line,column:s.column},parent:l,children:[]};return s.children?.forEach(h=>_.children.push(this.parseNode(h,_))),_}};var MT={createLiteral:t((a,s)=>({type:ec.Literal,parent:s,value:a}),"createLiteral"),createTemplateString:t((a,s)=>({type:ec.TemplateString,parent:s,value:a}),"createTemplateString"),createIdentifier:t((a,s)=>({type:ec.Identifier,value:a,parent:s}),"createIdentifier"),createProperty:t((a,s,l)=>{let _={type:ec.Property,parent:l,name:null,value:s};return _.name={value:a,type:ec.Identifier,parent:_},_.value.parent=_,_},"createProperty"),createArrayOfLiterals:t((a,s)=>{let l={type:ec.Array,parent:s,children:[]};for(let _ of a)l.children.push(MT.createLiteral(_,l));return l},"createArrayOfLiterals")};var yur=/^[a-zA-Z_$][a-zA-Z0-9_$]*$/,qG=class{static{t(this,"SourceGenerator")}generate(s){let l=[];return this.generateSource(l,s),l.join("")}generateSource(s,l){switch(l.type){case ec.Array:return this.generateArray(s,l);case ec.Object:return this.generateObject(s,l);case ec.Property:return this.generateProperty(s,l);case ec.Literal:return this.generateLiteral(s,l);case ec.FunctionCall:return this.generateFunctionCall(s,l);case ec.Identifier:return this.generateIdentifier(s,l);case ec.Raw:return this.generateRaw(s,l);case ec.TemplateString:return this.generateTemplateString(s,l)}}generateArray(s,l){s.push("["),l.children.map(_=>{this.generateSource(s,_),s.push(",")}),s.push("]")}generateObject(s,l){s.push("{"),l.children.forEach(_=>{this.generateSource(s,_),s.push(",")}),s.push("}")}generateProperty(s,l){this.generateIdentifier(s,l.name),s.push(":"),this.generateSource(s,l.value)}generateFunctionCall(s,l){s.push(l.name.value),s.push("("),l.children.forEach((_,h,b)=>{this.generateSource(s,_),h<b.length&&s.push(",")}),s.push(")")}generateRaw(s,l){s.push(l.value)}generateTemplateString(s,l){s.push("`"),s.push(l.value.replaceAll("`","\\`")),s.push("`")}generateLiteral(s,l){if(l.value===null)return s.push("null");switch(typeof l.value){case"number":case"boolean":return s.push(`${l.value}`);case"string":{let _=l.value,h=JSON.stringify(_);return s.push(`${h}`)}}}generateIdentifier(s,l){let _=yur.test(l.value)?l.value:`'${l.value}'`;s.push(_)}};import vur from"node:fs/promises";import{parse as bur}from"@swc/core";var vpt=t(async a=>{let s=new Set;try{let l=await vur.readFile(a,"utf-8");(await bur(l,{syntax:"typescript"})).body.forEach(h=>{h.type==="ExportDefaultDeclaration"||h.type==="ExportDefaultExpression"?s.add("default"):h.type==="ExportDeclaration"&&h.declaration.type==="FunctionDeclaration"?s.add(h.declaration.identifier.value):h.type==="ExportDeclaration"&&h.declaration.type==="VariableDeclaration"&&h.declaration.declarations[0].id.type==="Identifier"&&s.add(h.declaration.declarations[0].id.value)})}catch{return null}return s},"getJSFileExports");var bpt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/fragments.schema.json",$defs:{corsPolicyConfiguration:{type:"object",required:["name","allowedOrigins"],additionalProperties:!1,properties:{name:{type:"string",pattern:"^[0-9a-z-]+$"},allowCredentials:{type:"boolean"},maxAge:{type:"number"},allowedOrigins:{oneOf:[{type:"array",items:{type:"string"}},{type:"string"}]},allowedMethods:{oneOf:[{type:"array",items:{$ref:"fragments.schema.json#/$defs/httpMethod"}},{type:"string"}]},allowedHeaders:{oneOf:[{type:"array",items:{type:"string"}},{type:"string"}]},exposeHeaders:{oneOf:[{type:"array",items:{type:"string"}},{type:"string"}]}}},handlerDefinition:{type:"object",properties:{module:{type:"string",pattern:"^\\$import\\([^ )]*?\\)$"},export:{type:"string"},options:{type:"object",additionalProperties:!0}},additionalProperties:!1,required:["module","export"]},httpMethod:{type:"string",enum:["GET","HEAD","POST","PUT","DELETE","CONNECT","OPTIONS","TRACE","PATCH"]}}};var QNe={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/policies.schema.json",title:"Policies Config File",type:"object",additionalProperties:!1,properties:{policies:{type:"array",items:{$ref:"policy-configuration.schema.json"}},corsPolicies:{type:"array",items:{$ref:"fragments.schema.json#/$defs/corsPolicyConfiguration"}}}};var Spt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/policy-configuration.schema.json",title:"Policy Configuration Fragment",type:"object",required:["name","policyType","handler"],additionalProperties:!1,properties:{name:{type:"string",pattern:"^[0-9a-z-]+$"},policyType:{type:"string"},handler:{$ref:"fragments.schema.json#/$defs/handlerDefinition"},options:{type:"object",additionalProperties:!0}}};var ZNe={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/route-configuration-open-api.schema.json",title:"Open API Route Configuration Fragment",description:"These are the properties that can appear under the x-zuplo-route extension in a PathObject in Open API. It's a subset of what can appear in Zuplo's routes.json.",type:"object",required:["handler"],additionalProperties:!1,properties:{label:{type:"string",description:"An internal user-friendly identifier of the route."},key:{type:"string",deprecated:!0},handler:{$ref:"fragments.schema.json#/$defs/handlerDefinition"},corsPolicy:{type:"string",pattern:"^[0-9a-z-]+$"},custom:{},mcp:{type:"object",additionalProperties:!1,properties:{enabled:{type:"boolean"}}},policies:{type:"object",additionalProperties:!1,properties:{inbound:{type:"array",items:{type:"string",pattern:"^[0-9a-z-]+$"}},outbound:{type:"array",items:{type:"string",pattern:"^[0-9a-z-]+$"}}}},tags:{type:"array",items:{type:"string"}}}};var eIe={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/route-configuration.schema.json",title:"Route Configuration Fragment",description:"",type:"object",required:["path","methods","handler"],additionalProperties:!1,$defs:{corsPolicy:{type:"string",pattern:"^[0-9a-z-]+$"}},properties:{operationId:{type:"string"},path:{type:"string",pattern:"^/[^\\s]*$"},methods:{type:"array",items:{$ref:"fragments.schema.json#/$defs/httpMethod"}},label:{type:"string",description:"An internal user-friendly identifier of the route."},enforceOpenApi:{type:"boolean",description:"If true, schema validation found in the OpenAPI spec will be enforced on requests/responses."},key:{type:"string",deprecated:!0},handler:{$ref:"fragments.schema.json#/$defs/handlerDefinition"},corsPolicy:{$ref:"#/$defs/corsPolicy"},custom:{},mcp:{type:"object",additionalProperties:!1,properties:{enabled:{type:"boolean"}}},policies:{type:"object",additionalProperties:!1,properties:{inbound:{type:"array",items:{type:"string",pattern:"^[0-9a-z-]+$"}},outbound:{type:"array",items:{type:"string",pattern:"^[0-9a-z-]+$"}}}},summary:{type:"string"},description:{type:"string"},excludeFromOpenApi:{type:"boolean"},tags:{type:"array",items:{type:"string"}}}};var Oht=ap(nht(),1),Lht=ap(Fht(),1);var Ffe=class a{static{t(this,"JsonValidator")}static#r=new a;static get instance(){return a.#r}ajv;constructor(){this.ajv=new Lht.Ajv2020({allErrors:!0,allowUnionTypes:!0}),this.ajv.addKeyword("faker"),(0,Oht.default)(this.ajv,{mode:"fast"})}addSchema(s,l){this.ajv.addSchema(s,l)}compile(s){let l=this.ajv.compile(s);return t(h=>({isValid:l(h),errors:this.toSimpleErrors(l.errors,h),warnings:[]}),"validator")}toSimpleErrors(s,l){let _=[];return s?.forEach(h=>{h.keyword==="enum"&&h.params.allowedValues&&Array.isArray(h.params.allowedValues)&&(h.message+=`; ${h.params.allowedValues.join(", ")}`),h.instancePath&&(h.instancePath=h.instancePath.replaceAll(/(\/)?(~1)(\/)?/gm,"/"));let b={details:{}},D=h.instancePath.split("/");if(D.length>2){let M=D[1],z=D[2]?parseInt(D[2]):0,re=D[3],ie=isNaN(z)?void 0:l[M][z][re];b={details:{property:M,index:z,field:re,fieldValue:ie}}}if(h.keyword==="required"&&h.params.missingProperty&&h.instancePath&&(h.message=`A 'path' is missing required property '${h.params.missingProperty}'`),h.keyword==="additionalProperties"&&h.params.additionalProperty&&h.instancePath&&(h.message=`A 'path' should NOT include property '${h.params.additionalProperty}'`),h.keyword==="type"&&h.params.type&&h.instancePath){let M=h.instancePath.split("/"),z=M[M.length-1];h.message=`Value of property '${z}' must be '${h.params.type}'`}let N=Object.assign(h,b);_.push(N)}),_}};var tN=Ffe.instance;tN.addSchema(eIe,"route-configuration.schema.json");tN.addSchema(Spt,"policy-configuration.schema.json");tN.addSchema(QNe,"policies.schema.json");tN.addSchema(ZNe,"open-api-route-configuration.schema.json");tN.addSchema(bpt,"fragments.schema.json");var ILr=tN.compile(eIe),Rht=tN.compile(ZNe),mFe=tN.compile(QNe);var Ofe=class{static{t(this,"PoliciesConfigurationValidator")}results;validate(s){return this.results=mFe(s),this.results}};var Lfe=class{static{t(this,"OpenAPILocalizedValidator")}results;validate(s){return this.results=Rht(s),this.results}};import kgr from"node:path";var hFe=/\$import\((.*)\)/,Rfe=/\$env\((.*?)\)/g;var MA=class extends Error{static{t(this,"CodeGenError")}location;constructor(s,l,_,h){super(s),this.location={file:l,namespace:"",line:_?_.line:0,column:_?_.column:0,length:0,lineText:h??"",suggestion:""}}},Dgr=t(a=>{let s=[],l=a;for(;l.parent;)s.push(l),l=l.parent;return s.reverse()},"invertTree"),rN=t((a,s)=>{if(!a)return!1;let l=Dgr(a);return s.split("/").every((b,D)=>{let N=l[D];return N?b==="*"||IA(N)&&N.name.value===b?!0:b==="{}"?N.type===ec.Object:b==="[]"?N.type===ec.Array:!1:!1})},"testPosition");var Mfe=class{static{t(this,"AstTransformer")}errors=[];transform(s){return this.visitor(s),s}visitor(s){this.visit(s),gj(s)?s.children.forEach(l=>{this.visitor(l)}):gpt(s)?s.children.forEach(l=>{this.visitor(l)}):IA(s)&&this.visitor(s.value)}},Mht=t((a,s,l)=>_=>{if(!IA(_)||!yj(_.value)||typeof _.value.value!="string")return;if(!a.some(b=>rN(_,b))){Rfe.test(_.value.value)&&s.push(new MA("An $env() statement is not expected at this location.",l,_.location,_.value.value));return}let h=new RegExp(Rfe).exec(_.value.value);if(h?.length===2&&h[0]===_.value.value){let b={type:ec.Raw,parent:null,value:`environment["${h[1]}"]`};_.value=b}else{let b=_.value.value.replaceAll(new RegExp(Rfe),(D,N)=>`\${environment["${N}"] ? environment["${N}"] : ""}`);b!==_.value.value&&(_.value=MT.createTemplateString(b,_))}},"getEnvStatementTransformer");var xK="config/routes.json",wgr=["handler/{}/options/*","policies/[]/{}/handler/{}/options/*","corsPolicies/[]/{}/*"],Pgr=["handler/{}/module","handler/{}/options/{}/policies/{}/inbound/[]/{}/module","handler/{}/options/{}/policies/{}/outbound/[]/{}/module","policies/[]/{}/handler/{}/module","policies/[]/{}/handler/{}/options/{}/identifier/{}/module","policies/[]/{}/handler/{}/options/{}/validator"],jht=["handler/{}/options/*","policies/[]/{}/handler/{}/options/*"],Agr="handler/{}/options/{}/rewritePattern",Ngr="handler/{}/options/{}/baseUrl",jfe=class extends Mfe{static{t(this,"OpenAPIRoutesFragmentAstTransformer")}importCount=0;addedImports=new Map;getImportName(s){this.addedImports.has(s)||this.addedImports.set(s,`__import${this.importCount++}`);let l=this.addedImports.get(s);if(!l)throw new Error("Import name is undefined. This should not happen.");return l}getImports(){let s=[];return this.addedImports.forEach((l,_)=>{s.push({name:l,path:_})}),s}visit(s){this.rewriteHandlerFunction(s),this.rewriteForwardFunction(s),this.replaceImportStatements(s),this.replaceEnvStatements(s)}rewriteHandlerFunction(s){if(!(!IA(s)||!yj(s.value)||typeof s.value.value!="string")&&rN(s,Agr)){if(!s.parent||!gj(s.parent)){this.errors.push(new MA("Invalid node, expected object",xK,s.parent?s.parent.location:s.location,void 0));return}let l=s.value.value,_={type:ec.Raw,parent:null,value:Bht(l)},h=MT.createProperty("__rewriteFunction",_,s);s.parent.children.push(h)}}rewriteForwardFunction(s){if(!(!IA(s)||!yj(s.value)||typeof s.value.value!="string")&&rN(s,Ngr)){if(!s.parent||!gj(s.parent)){this.errors.push(new MA("Invalid node, expected object",xK,s.parent?s.parent.location:s.location,void 0));return}let l=s.value.value,_={type:ec.Raw,parent:null,value:Bht(l)},h=MT.createProperty("__rewriteFunction",_,s);s.parent.children.push(h)}}replaceImportStatements(s){if(!IA(s)||!yj(s.value))return;let l=s.value.value;if(typeof l!="string")return;if(!Pgr.some(N=>rN(s,N))&&!jht.some(N=>rN(s,N))){if(hFe.test(l)){if(s.name.value==="$ref")return;this.errors.push(new MA("An $import() statement is not expected at this location.",xK,s.location,l))}return}let _=hFe.exec(l);if(jht.some(N=>rN(s,N))&&!_)return;if(!_){this.errors.push(new MA("Invalid $import() statement",xK,s.location,l));return}let h=_[1];h=h.replace(/\\/g,"/"),h.startsWith(".")&&(h=kgr.posix.join("..",h));let b=this.getImportName(h),D={type:ec.Identifier,parent:s.parent,value:b};s.value=D}replaceEnvStatements=Mht(wgr,this.errors,xK)};function Bht(a){return`(request, context) => {
584
584
  const { params, url, query, method, headers } = request;
585
585
  const { host, hostname, origin, pathname, port, search } = new URL(url);
@@ -617,7 +617,7 @@ ${_N}${l.detail.toString().split(`
617
617
  `).join(`
618
618
  ${_N}`)}`:""}`);_.push(D);let N=BTr(l.location??void 0);if(N&&_.push(`${_N}${b(`The error was found in the file: ${N}`)}`),l.location&&l.location.file&&l.location.column!==0&&l.location.line!==0)try{let M=jTr.join(a,l.location.file),z=await MTr(M,"utf-8"),re=(0,Y1t.codeFrameColumns)(z,{start:{line:l.location.line,column:l.location.column}},{highlightCode:!0,message:l.message,linesAbove:3,linesBelow:3});_.push(_N),_.push(re)}catch{}else l.location&&l.location.file&&_.push(BO.red(`${_N}File: ${l.location.file}:${l.location.line}:${l.location.column}`));_.push(""),l.severity==="warning"?s.warn(_.join(`
619
619
  `)):s.error(_.join(`
620
- `))}t(K1t,"logIssue");function BTr(a){if(a&&a.file){let s=a.file;if(a.line)return`${s}:${a.line}`;if(a.column)return`${s}:${a.column}`}}t(BTr,"getFileLocation");var KT=class{static{t(this,"PluginResult")}errors=[];warnings=[];constructor(s){s&&this.errors.push(s)}};async function X1t(a,s,l){let _=[],h=[],b=new Map;for await(let D of a)try{let N=await D(s,{data:b,errors:h,warnings:_});if(h.push(...N.errors.map(M=>(M.pluginName===""&&(M.pluginName=D.name),M))),_.push(...N.warnings),N.errors.length>0)break}catch(N){if(N instanceof J1?h.push({...N.issue,pluginName:N.pluginName??"unknown"}):h.push(N),l?.throwOnException)throw N;break}return{errors:h,warnings:_,data:b}}t(X1t,"runPlugins");import{readFile as UTr}from"node:fs/promises";import Q1t from"node:path";import{parse as $Tr}from"jsonc-parser";async function cB(a){let s=Q1t.join(a,Jat),l=Q1t.join(a,qat),_=!1,h=s;await ou.fileExists(s)?(_=!0,h=s):await ou.fileExists(l)&&(_=!0,h=l);let b,D;if(_){let M=await UTr(h,"utf-8"),re=$Tr(M,[]);if(typeof re!="object")return{status:HF,errors:[{message:"Invalid zuplo.jsonc file.",detail:"The zuplo.jsonc file is not a valid JSON object",pluginName:"buildData",severity:"error"}]};if("version"in re&&re.version!==1)return{status:HF,errors:[{message:"Invalid version set in zuplo.jsonc file.",detail:"version in zuplo.jsonc must be set to 1",pluginName:"buildData",severity:"error"}]};if("compatibilityDate"in re&&wM&&typeof re.compatibilityDate=="string"){if(!wM.includes(re.compatibilityDate)){let ie={message:"Invalid compatibilityDate set in zuplo.jsonc file.",detail:`compatibilityDate was set to ${re.compatibilityDate}. Valid compatibility dates are ${wM.join(", ")}`,pluginName:"buildData",severity:"error"};return{status:HF,errors:[ie]}}b=re.compatibilityDate}D=rle(b,re.flags)}else D=rle(void 0,void 0);return{status:hA,config:{version:1,compatibilityDate:b,flags:D}}}t(cB,"getZuploConfig");import zTr from"node:fs";import{mkdir as Z1t,readFile as JTr,readdir as qTr,writeFile as VTr}from"node:fs/promises";import cY from"node:path";import WTr from"node:readline";var evt=t(async function({sourceDirectory:a,logger:s,outputDirectory:l,deploymentName:_,environmentType:h,deploymentUrl:b}){return Bu.timeFn("Building OpenAPI files",async()=>{s.debug("Building OpenAPI files");let D=cY.join(a,q2),N=cY.join(D,cle),M=cY.join(l,$at,q2);try{if(await ou.dirExists(l)||await Z1t(l),await ou.dirExists(M)||await Z1t(M,{recursive:!0}),!await JM(a))return new KT({message:"Failed to build project because no OpenAPI file was found on the 'config' folder",pluginName:"build-open-api-files",severity:"error"});let ie=(await qTr(D)).filter(we=>we.endsWith(".oas.json"));if(!await ou.fileExists(N))return new KT({message:"The project must include a policies file ('/config/policies.json')",pluginName:"build-open-api-files",severity:"error"});let Q=await JTr(N,"utf-8"),Re=JSON.parse(Q),Ne=t(async we=>{let wt=cY.join(D,we);if(!await HTr(wt)){s.debug(`Skipping ${we} as it does not use the OpenAPI handler`);return}let xt;try{xt=await Zut({sourceDirectory:a,openApiDocPath:wt,policiesConfig:Re,logger:s,environmentType:h,deploymentName:_,deploymentUrl:b})}catch(tn){if(s.error(tn),tn instanceof SyntaxError||tn instanceof IT.ResolverError||tn instanceof IT.JSONParserError||tn instanceof IT.ParserError||tn instanceof IT.MissingPointerError||tn instanceof oO)return new KT({message:tn.message,location:{file:we,column:0,length:0,line:0,lineText:"",namespace:"",suggestion:""},pluginName:"build-open-api-files",severity:"error"});if(tn instanceof J1)return new KT({...tn.issue,pluginName:"build-open-api-files"});throw tn}let Tr=JSON.stringify(xt,null,2),fn=cY.join(M,we);await VTr(fn,Tr,"utf-8")},"processFile");await Promise.all(ie.map(Ne))}catch(z){return s.error(z),new KT({message:"Error building OpenAPI files",pluginName:"build-open-api-files",severity:"error"})}return new KT})},"buildOpenApiFiles");async function HTr(a){let s=zTr.createReadStream(a),l=WTr.createInterface({input:s,crlfDelay:1/0}),_=!1,h=!1;for await(let b of l)if(b.includes('"openApiSpecHandler"')&&(_=!0),b.includes('"openApiFilePath"')&&(h=!0),_&&h)break;return l.close(),s.destroy(),_&&h}t(HTr,"usesOpenApiHandler");import GTr from"node:fs/promises";import KTr from"node:path";var tvt=t(async function({outputDirectory:a,systemDirectory:s,cacheDirectory:l,logger:_}){return Bu.timeFn("Cleaning output",async()=>{_.debug("Cleaning output");let h=KTr.join(l,"routes");return await Promise.all([a,s,h].map(async b=>{try{await GTr.rm(b,{recursive:!0,force:!0})}catch(D){_.error(D)}})),{warnings:[],errors:[]}})},"cleanOutput");import rvt from"node:fs/promises";var nvt=t(async function({systemDirectory:a,cacheDirectory:s,logger:l}){return Bu.timeFn("Creating system directory",async()=>{l.debug("Creating system directory");try{return await Promise.all([rvt.mkdir(a,{recursive:!0}),rvt.mkdir(s,{recursive:!0})]),{warnings:[],errors:[]}}catch(_){return l.error(_),{warnings:[],errors:[]}}return{warnings:[],errors:[]}})},"createSystemDir");var ivt=t(async function({logger:a}){return Bu.timeFn("Checking for breaking changes",async()=>(a.debug("Checking for breaking changes"),{warnings:[],errors:[]}))},"checkForDeprecations");import{readFile as YTr,writeFile as XTr}from"node:fs/promises";import QTr from"node:path";var svt=t(async function({systemDirectory:a,buildId:s,logger:l,config:_,publicZuploEnvironmentVariables:h}){return Bu.timeFn("Generating build data",async()=>{l.debug("Generating build data");let b=await YTr(new URL("../../../package.json",import.meta.url),"utf-8"),D=JSON.parse(b),N={BUILD_ID:s??"",GIT_SHA:process.env.GIT_SHA,TIMESTAMP:new Date().toISOString(),BUILD_ENV:ih.NODE_ENV,ZUPLO_VERSION:D.version,API_VERSION:process.env.API_VERSION,COMPATIBILITY_DATE:_?.compatibilityDate,ACCOUNT_NAME:h?.ZUPLO_ACCOUNT_NAME,PROJECT_NAME:h?.ZUPLO_PROJECT_NAME,ENVIRONMENT_TYPE:h?.ZUPLO_ENVIRONMENT_TYPE,IS_LOCAL_DEVELOPMENT:ih.isLocalDevelopment(),COMPATIBILITY_FLAGS:J6e[_?.compatibilityDate??"none"]},M=JSON.stringify(N,void 0,2),z=QTr.join(a,lle);try{await XTr(z,M.trimStart(),"utf-8")}catch(re){l.error(re);let ie={message:`Error creating file at ${z}`,pluginName:"buildData",severity:"error"};return{warnings:[],errors:[ie]}}return{warnings:[],errors:[]}})},"generateBuildData");import ZTr from"node:fs/promises";import exr from"node:path";var txr=`import { Handler, ServiceProviderImpl } from "@zuplo/runtime";
620
+ `))}t(K1t,"logIssue");function BTr(a){if(a&&a.file){let s=a.file;if(a.line)return`${s}:${a.line}`;if(a.column)return`${s}:${a.column}`}}t(BTr,"getFileLocation");var KT=class{static{t(this,"PluginResult")}errors=[];warnings=[];constructor(s){s&&this.errors.push(s)}};async function X1t(a,s,l){let _=[],h=[],b=new Map;for await(let D of a)try{let N=await D(s,{data:b,errors:h,warnings:_});if(h.push(...N.errors.map(M=>(M.pluginName===""&&(M.pluginName=D.name),M))),_.push(...N.warnings),N.errors.length>0)break}catch(N){if(N instanceof J1?h.push({...N.issue,pluginName:N.pluginName??"unknown"}):h.push(N),l?.throwOnException)throw N;break}return{errors:h,warnings:_,data:b}}t(X1t,"runPlugins");import{readFile as UTr}from"node:fs/promises";import Q1t from"node:path";import{parse as $Tr}from"jsonc-parser";async function cB(a){let s=Q1t.join(a,Jat),l=Q1t.join(a,qat),_=!1,h=s;await ou.fileExists(s)?(_=!0,h=s):await ou.fileExists(l)&&(_=!0,h=l);let b,D;if(_){let M=await UTr(h,"utf-8"),re=$Tr(M,[]);if(typeof re!="object")return{status:HF,errors:[{message:"Invalid zuplo.jsonc file.",detail:"The zuplo.jsonc file is not a valid JSON object",pluginName:"buildData",severity:"error"}]};if("version"in re&&re.version!==1)return{status:HF,errors:[{message:"Invalid version set in zuplo.jsonc file.",detail:"version in zuplo.jsonc must be set to 1",pluginName:"buildData",severity:"error"}]};if("compatibilityDate"in re&&wM&&typeof re.compatibilityDate=="string"){if(!wM.includes(re.compatibilityDate)){let ie={message:"Invalid compatibilityDate set in zuplo.jsonc file.",detail:`compatibilityDate was set to ${re.compatibilityDate}. Valid compatibility dates are ${wM.join(", ")}`,pluginName:"buildData",severity:"error"};return{status:HF,errors:[ie]}}b=re.compatibilityDate}D=rle(b,re.flags)}else D=rle(void 0,void 0);return{status:hA,config:{version:1,compatibilityDate:b,flags:D}}}t(cB,"getZuploConfig");import zTr from"node:fs";import{mkdir as Z1t,readFile as JTr,readdir as qTr,writeFile as VTr}from"node:fs/promises";import cY from"node:path";import WTr from"node:readline";var evt=t(async function({sourceDirectory:a,logger:s,outputDirectory:l,deploymentName:_,environmentType:h,urls:b}){return Bu.timeFn("Building OpenAPI files",async()=>{s.debug("Building OpenAPI files");let D=cY.join(a,q2),N=cY.join(D,cle),M=cY.join(l,$at,q2);try{if(await ou.dirExists(l)||await Z1t(l),await ou.dirExists(M)||await Z1t(M,{recursive:!0}),!await JM(a))return new KT({message:"Failed to build project because no OpenAPI file was found on the 'config' folder",pluginName:"build-open-api-files",severity:"error"});let ie=(await qTr(D)).filter(we=>we.endsWith(".oas.json"));if(!await ou.fileExists(N))return new KT({message:"The project must include a policies file ('/config/policies.json')",pluginName:"build-open-api-files",severity:"error"});let Q=await JTr(N,"utf-8"),Re=JSON.parse(Q),Ne=t(async we=>{let wt=cY.join(D,we);if(!await HTr(wt)){s.debug(`Skipping ${we} as it does not use the OpenAPI handler`);return}let xt;try{xt=await Zut({sourceDirectory:a,openApiDocPath:wt,policiesConfig:Re,logger:s,environmentType:h,deploymentName:_,urls:b})}catch(tn){if(s.error(tn),tn instanceof SyntaxError||tn instanceof IT.ResolverError||tn instanceof IT.JSONParserError||tn instanceof IT.ParserError||tn instanceof IT.MissingPointerError||tn instanceof oO)return new KT({message:tn.message,location:{file:we,column:0,length:0,line:0,lineText:"",namespace:"",suggestion:""},pluginName:"build-open-api-files",severity:"error"});if(tn instanceof J1)return new KT({...tn.issue,pluginName:"build-open-api-files"});throw tn}let Tr=JSON.stringify(xt,null,2),fn=cY.join(M,we);await VTr(fn,Tr,"utf-8")},"processFile");await Promise.all(ie.map(Ne))}catch(z){return s.error(z),new KT({message:"Error building OpenAPI files",pluginName:"build-open-api-files",severity:"error"})}return new KT})},"buildOpenApiFiles");async function HTr(a){let s=zTr.createReadStream(a),l=WTr.createInterface({input:s,crlfDelay:1/0}),_=!1,h=!1;for await(let b of l)if(b.includes('"openApiSpecHandler"')&&(_=!0),b.includes('"openApiFilePath"')&&(h=!0),_&&h)break;return l.close(),s.destroy(),_&&h}t(HTr,"usesOpenApiHandler");import GTr from"node:fs/promises";import KTr from"node:path";var tvt=t(async function({outputDirectory:a,systemDirectory:s,cacheDirectory:l,logger:_}){return Bu.timeFn("Cleaning output",async()=>{_.debug("Cleaning output");let h=KTr.join(l,"routes");return await Promise.all([a,s,h].map(async b=>{try{await GTr.rm(b,{recursive:!0,force:!0})}catch(D){_.error(D)}})),{warnings:[],errors:[]}})},"cleanOutput");import rvt from"node:fs/promises";var nvt=t(async function({systemDirectory:a,cacheDirectory:s,logger:l}){return Bu.timeFn("Creating system directory",async()=>{l.debug("Creating system directory");try{return await Promise.all([rvt.mkdir(a,{recursive:!0}),rvt.mkdir(s,{recursive:!0})]),{warnings:[],errors:[]}}catch(_){return l.error(_),{warnings:[],errors:[]}}return{warnings:[],errors:[]}})},"createSystemDir");var ivt=t(async function({logger:a}){return Bu.timeFn("Checking for breaking changes",async()=>(a.debug("Checking for breaking changes"),{warnings:[],errors:[]}))},"checkForDeprecations");import{readFile as YTr,writeFile as XTr}from"node:fs/promises";import QTr from"node:path";var svt=t(async function({systemDirectory:a,buildId:s,logger:l,config:_,publicZuploEnvironmentVariables:h}){return Bu.timeFn("Generating build data",async()=>{l.debug("Generating build data");let b=await YTr(new URL("../../../package.json",import.meta.url),"utf-8"),D=JSON.parse(b),N={BUILD_ID:s??"",GIT_SHA:process.env.GIT_SHA,TIMESTAMP:new Date().toISOString(),BUILD_ENV:ih.NODE_ENV,ZUPLO_VERSION:D.version,API_VERSION:process.env.API_VERSION,COMPATIBILITY_DATE:_?.compatibilityDate,ACCOUNT_NAME:h?.ZUPLO_ACCOUNT_NAME,PROJECT_NAME:h?.ZUPLO_PROJECT_NAME,ENVIRONMENT_TYPE:h?.ZUPLO_ENVIRONMENT_TYPE,IS_LOCAL_DEVELOPMENT:ih.isLocalDevelopment(),COMPATIBILITY_FLAGS:J6e[_?.compatibilityDate??"none"]},M=JSON.stringify(N,void 0,2),z=QTr.join(a,lle);try{await XTr(z,M.trimStart(),"utf-8")}catch(re){l.error(re);let ie={message:`Error creating file at ${z}`,pluginName:"buildData",severity:"error"};return{warnings:[],errors:[ie]}}return{warnings:[],errors:[]}})},"generateBuildData");import ZTr from"node:fs/promises";import exr from"node:path";var txr=`import { Handler, ServiceProviderImpl } from "@zuplo/runtime";
621
621
  import routeLoader from "zuplo:routes";
622
622
  import * as schemaValidations from "zuplo:schema-validations";
623
623
  import { runtimeInit } from "../modules/zuplo.runtime.ts";
@@ -648,11 +648,11 @@ export default {
648
648
  },
649
649
  };
650
650
  `,avt=t(async function({systemDirectory:a,logger:s}){return Bu.timeFn("Generating Worker shim",async()=>{s.debug("Generating Worker shim");let l=exr.join(a,ule);try{await ZTr.writeFile(l,txr,"utf-8")}catch(_){s.error(_);let h={message:`Error creating file at ${l}`,pluginName:"generate-worker-entry",severity:"error"};return{warnings:[],errors:[h]}}return{warnings:[],errors:[]}})},"generateWorker");import{readFile as rxr,readdir as nxr}from"node:fs/promises";import ovt from"node:path";var N_e="validate-open-api-files",cvt=t(async function({sourceDirectory:a,logger:s}){return Bu.timeFn("Validating OpenAPI files",async()=>{s.debug("Validating OpenAPI files");let l=ovt.join(a,q2),_=[];try{if(!await JM(a))return new KT({message:"Failed to build project because no open-api file was found on the 'config' folder",pluginName:N_e,severity:"error"});let D=(await nxr(l)).filter(M=>M.endsWith(".oas.json")),N=t(async M=>{let z=ovt.join(l,M);try{M==="zp.oas.json"&&_.push({message:"Open API files cannot be named 'zp.oas.json' since 'zp' is a reserved prefix. Update the file name to solve this build issue.",pluginName:N_e,severity:"error"});let re=await rxr(z,"utf-8"),ie=JSON.parse(re);if(ie&&ie.paths){let Q=Object.entries(ie.paths).filter(Re=>Re[0]==="zp"||Re[0]==="/zp");if(Q.length>0){let Re=Q.length===1?"includes one route path":`includes '${Q.length}' routes`;_.push({message:`Open API file '${M}' ${Re} that's named '/zp' which is a reserved route name. Updating the route to something other than '/zp' will solve this build issue.`,pluginName:N_e,severity:"error"})}}}catch(re){s.error(re)}},"validateOpenApiFile");await Promise.all(D.map(N))}catch(h){return s.error(h),_.length>0?{errors:_,warnings:[]}:new KT({message:"Failed while validating the open api files in the project",pluginName:N_e,severity:"warning"})}return{errors:_,warnings:[]}})},"validateOpenAPIFiles");import{readFile as xxr,writeFile as wvt}from"node:fs/promises";import Cxr from"node:path";var fB=ap(l5e(),1);import{parse as Exr}from"jsonc-parser";var uB=ap(l5e(),1);var kvt=t(()=>({include:["modules/**/*",".zuplo/**/*","tests/**/*"],exclude:["./node_modules","./dist"],compilerOptions:{module:uB.ModuleKind.ESNext,target:uB.ScriptTarget.ES2022,moduleResolution:uB.ModuleResolutionKind.Bundler,lib:["ESNext","WebWorker","Webworker.Iterable"],preserveConstEnums:!0,useUnknownInCatchVariables:!1,forceConsistentCasingInFileNames:!0,importHelpers:!0,esModuleInterop:!0,strictNullChecks:!0,noEmit:!0}}),"getZuploTsConfigTemplate");var zO="validate-tsconfig",Pvt=t(async function({sourceDirectory:a,logger:s,command:l,environmentType:_}){return Bu.timeFn("Validate TSConfig",async()=>{s.debug("Validate TSConfig");let h=_==="WORKING_COPY"||l==="dev";try{let b=kvt(),D=Cxr.join(a,"tsconfig.json");if(!await ou.fileExists(D))return h?(await wvt(D,JSON.stringify(b,null,2)),{warnings:[{message:"This project does not have a tsconfig.json file. The file has been created for you.",severity:"warning",pluginName:zO,helpUrl:"https://zuplo.com/docs/articles/tsconfig"}],errors:[]}):{warnings:[],errors:[{message:"This project does not have a tsconfig.json file.",severity:"error",pluginName:zO,helpUrl:"https://zuplo.com/docs/articles/tsconfig"}]};let N=await xxr(D,"utf-8"),M=Exr(N);if(!(M&&typeof M=="object"&&"compilerOptions"in M))return h?(await wvt(D,JSON.stringify(b,null,2)),{warnings:[{message:"This project's tsconfig.json file was invalid. A valid file has been written for you.",severity:"warning",pluginName:zO,helpUrl:"https://zuplo.com/docs/articles/tsconfig"}],errors:[]}):{warnings:[],errors:[{message:"This project's tsconfig.json file is invalid. It must have a compilerOptions.",severity:"error",pluginName:zO,helpUrl:"https://zuplo.com/docs/articles/tsconfig"}]};let z=fB.default.convertCompilerOptionsFromJson(M.compilerOptions,a);if(z.errors.length>0)return{warnings:[],errors:z.errors.map(cn=>({severity:"error",pluginName:zO,message:cn.messageText.toString(),detail:"You will need to modify your tsconfig.json file to build this project.",helpUrl:"https://zuplo.com/docs/articles/tsconfig",location:cn.file?{line:cn.file.getLineStarts()[0],length:cn.file.getWidth(),file:cn.file.fileName,column:cn.file.getStart(),lineText:"",namespace:"",suggestion:""}:void 0}))};if(!M||typeof M!="object")throw new TypeError("The userConfigRaw is not an object, this should not happen.");if(!("compilerOptions"in M)||M.compilerOptions===null||M.compilerOptions===void 0||typeof M.compilerOptions!="object")throw new TypeError("The userConfigRaw.compilerOptions property is not an object, this should not happen.");let re=t((cn,Cr,vr)=>`The compiler option '${cn}' should ${Cr===void 0?"not be set":`be set to '${typeof Cr=="string"?Cr:JSON.stringify(Cr)}'`}, it was ${vr===void 0?"not set":`set to '${typeof vr=="string"?vr:JSON.stringify(vr)}'`}`,"getMessage"),ie="ESNext",Q=fB.ModuleKind.ESNext,Re=[];z.options.module!==Q&&Re.push(re("module",ie,M.compilerOptions.module));let Ne="ES2022",we=fB.default.ScriptTarget.ES2022;z.options.target!==we&&Re.push(re("target",Ne,M.compilerOptions.target));let wt="Bundler",xt=fB.default.ModuleResolutionKind.Bundler;z.options.moduleResolution!==xt&&Re.push(re("moduleResolution",wt,M.compilerOptions.moduleResolution));let Tr=["ESNext","WebWorker","Webworker.Iterable"];t(cn=>{let Cr=Tr.map(fs=>fs.toLowerCase()),vr=cn.map(fs=>fs.toLowerCase());return Cr.every(fs=>vr.includes(fs))},"includesAllLibs")(M.compilerOptions.lib??[])||Re.push(re("lib",Tr,M.compilerOptions.lib)),z.options.baseUrl&&Re.push(re("baseUrl",void 0,M.compilerOptions.baseUrl));let tn=[];return Re.length>0&&tn.push({message:"This project's tsconfig.json was not set to the recommended settings. Custom settings may cause build issues. For guidance on how to adjust your settings, please visit: https://zuplo.com/docs/articles/tsconfig",severity:"warning",detail:Re.join(`
651
- `),pluginName:zO,helpUrl:"https://zuplo.com/docs/articles/tsconfig"}),{warnings:tn,errors:[]}}catch(b){s.error(b);let D={message:`Error validating tsconfig.json : ${b.message}`,severity:"error",pluginName:zO};return{warnings:[],errors:[D]}}})},"validateTSConfig");var _B;try{let a=Dxr(new URL("../../package.json",import.meta.url),"utf-8");_B=JSON.parse(a).version}catch{_B="0.0.0"}function kxr(a){let{ZUPLO:s,ZUPLO_BUILD_ID:l,ZUPLO_BUILD_CONFIG:_}=process.env;if(s&&l&&_){let h;try{h=JSON.parse(_)}catch{throw new Error("Couuld not parse ZUPLO_BUILD_CONFIG")}let b={ZUPLO_PROJECT_ID:h.projectId,ZUPLO_ACCOUNT_NAME:h.accountName,ZUPLO_PROJECT_NAME:h.projectName,ZUPLO_ENVIRONMENT_TYPE:h.environmentType};for(let[D,N]of Object.entries(process.env))D.startsWith("ZUPLO_PUBLIC_")&&(b[D]=N??"");return{...a,buildId:l,...h,publicZuploEnvironmentVariables:b}}return a}t(kxr,"getBuildConfig");async function u5e(a){let s=performance.now(),{buildId:l,sourceDirectory:_,deploymentName:h=L_e.basename(_),command:b,minify:D,entitlements:N,environmentType:M,logger:z,output:re,noCompile:ie=!1,projectId:Q,deploymentUrl:Re,publicZuploEnvironmentVariables:Ne}=kxr(a),we=await cB(_),wt=L_e.join(_,IM),xt;if("errors"in we)G7e({output:re.child("api"),buildId:l,runtimeVersion:_B}),xt={status:"Failed",flags:void 0,compatibilityDate:void 0,runtimeVersion:_B,outputPath:wt,buildTime:new Date().toISOString(),buildTimeMs:0,buildId:l,warnings:[],errors:we.errors,metafile:void 0};else{ie||G7e({output:re.child("api"),buildId:l,runtimeVersion:_B,compatibilityDate:we.config.compatibilityDate});let tn={command:b,minify:D,deploymentName:h,sourceDirectory:_,outputDirectory:wt,systemDirectory:L_e.join(_,k3),cacheDirectory:L_e.join(_,"node_modules",k3),buildId:l,logger:z,output:re,config:we.config,publicZuploEnvironmentVariables:Ne,projectId:Q,entitlements:N,environmentType:M,deploymentUrl:Re},cn=[];cn.push(tvt),cn.push(nvt),cn.push(ivt),cn.push(svt),cn.push(Pvt),cn.push(cvt),cn.push(avt),ie||cn.push(W1t),cn.push(evt);let Cr=await X1t(cn,tn),vr=Cr.errors.length>0?HF:Cr.warnings.length>0?$6e:hA,fs=Cr.data.get("metafile");xt={status:vr,compatibilityDate:we.config.compatibilityDate,runtimeVersion:_B,outputPath:wt,buildTime:new Date().toISOString(),buildTimeMs:0,metafile:fs,buildId:l,warnings:Cr.warnings,errors:Cr.errors,flags:we.config.flags}}xt.warnings.length>0&&xt.warnings.forEach(tn=>{z.warn(tn)}),xt.errors.length>0&&xt.errors.forEach(tn=>{z.error(tn)});let{metafile:Tr,...fn}=xt;if(z.debug(fn,"Compiler completed"),xt.buildTimeMs=performance.now()-s,ie||await A_e(_,re.child("api"),xt),process.env.ZUPLO_SHOW_PERF){console.log();let tn=xt.buildTimeMs<2e3?"green":xt.buildTimeMs<5e3?"yellow":"red";console.log(Jf[tn](`Build time: ${xt.buildTimeMs.toFixed(0)}ms`)),Bu.report()}return Bu.clear(),xt}t(u5e,"build");import{existsSync as iAr}from"node:fs";import{mkdir as sAr,readFile as aAr}from"node:fs/promises";import wY from"node:path";var Nxt=ap(S9e(),1);import{randomUUID as KSt}from"node:crypto";import Cwr from"node:events";import VB from"node:path";import Ewr from"chokidar";import*as YSt from"esbuild";var T9e=class extends Cwr{static{t(this,"WatchEmitter")}},DN=class{static{t(this,"BuildWatcher")}esbuildContext;emitter=new T9e;envFilesWatcher;outputDirectory;sourceDirectory;command;logger;publicZuploEnvironmentVariables;projectName;buildId;output;constructor({sourceDirectory:s,command:l,logger:_,publicZuploEnvironmentVariables:h={},buildId:b,output:D}){this.sourceDirectory=s,this.command=l,this.outputDirectory=VB.join(s,IM),this.logger=_,this.publicZuploEnvironmentVariables=h,this.projectName=VB.basename(s),this.buildId=b,this.output=D,this.envFilesWatcher=Ewr.watch([VB.join(s,".env"),VB.join(s,".env.zuplo")])}watchEnvFiles(){this.envFilesWatcher.on("change",()=>{this.emitter.emit("reload",null,null)}),this.envFilesWatcher.on("add",()=>{this.emitter.emit("reload",null,null)}),this.envFilesWatcher.on("unlink",()=>{this.emitter.emit("reload",null,null)})}onReload=t(s=>{this.emitter.on("reload",s)},"onReload");async start(){let{sourceDirectory:s}=this;if(this.esbuildContext!==void 0)throw new Error("Watcher cannot be started more than once");let l=await u5e({buildId:this.buildId,output:this.output,sourceDirectory:s,noCompile:!0,command:this.command,publicZuploEnvironmentVariables:this.publicZuploEnvironmentVariables,logger:this.logger,deploymentUrl:void 0}),_=await oY({command:this.command,systemDirectory:VB.join(s,k3),cacheDirectory:VB.join(s,"node_modules",k3),outputDirectory:this.outputDirectory,sourceDirectory:s,logger:this.logger,flags:l.flags,compatibilityDate:l.compatibilityDate}),h=this;_.plugins?.push({name:"on-end",setup(b){b.onEnd(D=>{h.logger.debug("Watcher (build) reloaded");let N=W7e({buildId:KSt(),result:D});N.errors.length>0?h.logger.error(N.errors,"Build errors"):h.logger.debug(`Successfully rebuilt watched project. Build id ${N.buildId}`);let M={...N,compatibilityDate:l.compatibilityDate,flags:l.flags};h.emitter.emit("reload",M,null)})}}),this.esbuildContext=await YSt.context(_);try{if((await this.esbuildContext.rebuild()).errors.length>0){let D={status:"Failed",runtimeVersion:"0.0.0",buildTime:"",buildTimeMs:0,buildId:KSt(),warnings:[],errors:[],metafile:void 0};await A_e(s,h.output.child("api"),D),this.logger.error(D.errors,"Build errors")}}catch(b){throw await this.close(),b}await this.esbuildContext.watch()}async close(){try{await this.envFilesWatcher.close(),this.esbuildContext&&(await this.esbuildContext.dispose(),this.logger.debug("ESBuild watcher closed"))}catch(s){this.logger.error(s)}}};import{existsSync as Pxt,readFileSync as Axt}from"node:fs";import vde from"node:path";var H9e=ap(rTt(),1);var kxt=ap(qTt(),1);import{Buffer as QPr}from"node:buffer";import ZPr from"node:path";import Dxt from"node:child_process";import yde from"node:process";function O9e(a){let s=typeof a=="string"?`
651
+ `),pluginName:zO,helpUrl:"https://zuplo.com/docs/articles/tsconfig"}),{warnings:tn,errors:[]}}catch(b){s.error(b);let D={message:`Error validating tsconfig.json : ${b.message}`,severity:"error",pluginName:zO};return{warnings:[],errors:[D]}}})},"validateTSConfig");var _B;try{let a=Dxr(new URL("../../package.json",import.meta.url),"utf-8");_B=JSON.parse(a).version}catch{_B="0.0.0"}function kxr(a){let{ZUPLO:s,ZUPLO_BUILD_ID:l,ZUPLO_BUILD_CONFIG:_}=process.env;if(s&&l&&_){let h;try{h=JSON.parse(_)}catch{throw new Error("Couuld not parse ZUPLO_BUILD_CONFIG")}let b={ZUPLO_PROJECT_ID:h.projectId,ZUPLO_ACCOUNT_NAME:h.accountName,ZUPLO_PROJECT_NAME:h.projectName,ZUPLO_ENVIRONMENT_TYPE:h.environmentType};for(let[D,N]of Object.entries(process.env))D.startsWith("ZUPLO_PUBLIC_")&&(b[D]=N??"");return{...a,buildId:l,...h,publicZuploEnvironmentVariables:b}}return a}t(kxr,"getBuildConfig");async function u5e(a){let s=performance.now(),{buildId:l,sourceDirectory:_,deploymentName:h=L_e.basename(_),command:b,minify:D,entitlements:N,environmentType:M,logger:z,output:re,noCompile:ie=!1,projectId:Q,urls:Re,publicZuploEnvironmentVariables:Ne}=kxr(a),we=await cB(_),wt=L_e.join(_,IM),xt;if("errors"in we)G7e({output:re.child("api"),buildId:l,runtimeVersion:_B}),xt={status:"Failed",flags:void 0,compatibilityDate:void 0,runtimeVersion:_B,outputPath:wt,buildTime:new Date().toISOString(),buildTimeMs:0,buildId:l,warnings:[],errors:we.errors,metafile:void 0};else{ie||G7e({output:re.child("api"),buildId:l,runtimeVersion:_B,compatibilityDate:we.config.compatibilityDate});let tn={command:b,minify:D,deploymentName:h,sourceDirectory:_,outputDirectory:wt,systemDirectory:L_e.join(_,k3),cacheDirectory:L_e.join(_,"node_modules",k3),buildId:l,logger:z,output:re,config:we.config,publicZuploEnvironmentVariables:Ne,projectId:Q,entitlements:N,environmentType:M,urls:Re},cn=[];cn.push(tvt),cn.push(nvt),cn.push(ivt),cn.push(svt),cn.push(Pvt),cn.push(cvt),cn.push(avt),ie||cn.push(W1t),cn.push(evt);let Cr=await X1t(cn,tn),vr=Cr.errors.length>0?HF:Cr.warnings.length>0?$6e:hA,fs=Cr.data.get("metafile");xt={status:vr,compatibilityDate:we.config.compatibilityDate,runtimeVersion:_B,outputPath:wt,buildTime:new Date().toISOString(),buildTimeMs:0,metafile:fs,buildId:l,warnings:Cr.warnings,errors:Cr.errors,flags:we.config.flags}}xt.warnings.length>0&&xt.warnings.forEach(tn=>{z.warn(tn)}),xt.errors.length>0&&xt.errors.forEach(tn=>{z.error(tn)});let{metafile:Tr,...fn}=xt;if(z.debug(fn,"Compiler completed"),xt.buildTimeMs=performance.now()-s,ie||await A_e(_,re.child("api"),xt),process.env.ZUPLO_SHOW_PERF){console.log();let tn=xt.buildTimeMs<2e3?"green":xt.buildTimeMs<5e3?"yellow":"red";console.log(Jf[tn](`Build time: ${xt.buildTimeMs.toFixed(0)}ms`)),Bu.report()}return Bu.clear(),xt}t(u5e,"build");import{existsSync as iAr}from"node:fs";import{mkdir as sAr,readFile as aAr}from"node:fs/promises";import wY from"node:path";var Nxt=ap(S9e(),1);import{randomUUID as KSt}from"node:crypto";import Cwr from"node:events";import VB from"node:path";import Ewr from"chokidar";import*as YSt from"esbuild";var T9e=class extends Cwr{static{t(this,"WatchEmitter")}},DN=class{static{t(this,"BuildWatcher")}esbuildContext;emitter=new T9e;envFilesWatcher;outputDirectory;sourceDirectory;command;logger;publicZuploEnvironmentVariables;projectName;buildId;output;constructor({sourceDirectory:s,command:l,logger:_,publicZuploEnvironmentVariables:h={},buildId:b,output:D}){this.sourceDirectory=s,this.command=l,this.outputDirectory=VB.join(s,IM),this.logger=_,this.publicZuploEnvironmentVariables=h,this.projectName=VB.basename(s),this.buildId=b,this.output=D,this.envFilesWatcher=Ewr.watch([VB.join(s,".env"),VB.join(s,".env.zuplo")])}watchEnvFiles(){this.envFilesWatcher.on("change",()=>{this.emitter.emit("reload",null,null)}),this.envFilesWatcher.on("add",()=>{this.emitter.emit("reload",null,null)}),this.envFilesWatcher.on("unlink",()=>{this.emitter.emit("reload",null,null)})}onReload=t(s=>{this.emitter.on("reload",s)},"onReload");async start(){let{sourceDirectory:s}=this;if(this.esbuildContext!==void 0)throw new Error("Watcher cannot be started more than once");let l=await u5e({buildId:this.buildId,output:this.output,sourceDirectory:s,noCompile:!0,command:this.command,publicZuploEnvironmentVariables:this.publicZuploEnvironmentVariables,logger:this.logger,urls:void 0}),_=await oY({command:this.command,systemDirectory:VB.join(s,k3),cacheDirectory:VB.join(s,"node_modules",k3),outputDirectory:this.outputDirectory,sourceDirectory:s,logger:this.logger,flags:l.flags,compatibilityDate:l.compatibilityDate}),h=this;_.plugins?.push({name:"on-end",setup(b){b.onEnd(D=>{h.logger.debug("Watcher (build) reloaded");let N=W7e({buildId:KSt(),result:D});N.errors.length>0?h.logger.error(N.errors,"Build errors"):h.logger.debug(`Successfully rebuilt watched project. Build id ${N.buildId}`);let M={...N,compatibilityDate:l.compatibilityDate,flags:l.flags};h.emitter.emit("reload",M,null)})}}),this.esbuildContext=await YSt.context(_);try{if((await this.esbuildContext.rebuild()).errors.length>0){let D={status:"Failed",runtimeVersion:"0.0.0",buildTime:"",buildTimeMs:0,buildId:KSt(),warnings:[],errors:[],metafile:void 0};await A_e(s,h.output.child("api"),D),this.logger.error(D.errors,"Build errors")}}catch(b){throw await this.close(),b}await this.esbuildContext.watch()}async close(){try{await this.envFilesWatcher.close(),this.esbuildContext&&(await this.esbuildContext.dispose(),this.logger.debug("ESBuild watcher closed"))}catch(s){this.logger.error(s)}}};import{existsSync as Pxt,readFileSync as Axt}from"node:fs";import vde from"node:path";var H9e=ap(rTt(),1);var kxt=ap(qTt(),1);import{Buffer as QPr}from"node:buffer";import ZPr from"node:path";import Dxt from"node:child_process";import yde from"node:process";function O9e(a){let s=typeof a=="string"?`
652
652
  `:10,l=typeof a=="string"?"\r":13;return a[a.length-1]===s&&(a=a.slice(0,-1)),a[a.length-1]===l&&(a=a.slice(0,-1)),a}t(O9e,"stripFinalNewline");import ude from"node:process";import EY from"node:path";import{fileURLToPath as VTt}from"node:url";function lde(a={}){let{env:s=process.env,platform:l=process.platform}=a;return l!=="win32"?"PATH":Object.keys(s).reverse().find(_=>_.toUpperCase()==="PATH")||"Path"}t(lde,"pathKey");var _Pr=t(({cwd:a=ude.cwd(),path:s=ude.env[lde()],preferLocal:l=!0,execPath:_=ude.execPath,addExecPath:h=!0}={})=>{let b=a instanceof URL?VTt(a):a,D=EY.resolve(b),N=[];return l&&pPr(N,D),h&&dPr(N,_,D),[...N,s].join(EY.delimiter)},"npmRunPath"),pPr=t((a,s)=>{let l;for(;l!==s;)a.push(EY.join(s,"node_modules/.bin")),l=s,s=EY.resolve(s,"..")},"applyPreferLocal"),dPr=t((a,s,l)=>{let _=s instanceof URL?VTt(s):s;a.push(EY.resolve(l,_,".."))},"applyExecPath"),WTt=t(({env:a=ude.env,...s}={})=>{a={...a};let l=lde({env:a});return s.path=a[l],a[l]=_Pr(s),a},"npmRunPathEnv");var mPr=t((a,s,l,_)=>{if(l==="length"||l==="prototype"||l==="arguments"||l==="caller")return;let h=Object.getOwnPropertyDescriptor(a,l),b=Object.getOwnPropertyDescriptor(s,l);!hPr(h,b)&&_||Object.defineProperty(a,l,b)},"copyProperty"),hPr=t(function(a,s){return a===void 0||a.configurable||a.writable===s.writable&&a.enumerable===s.enumerable&&a.configurable===s.configurable&&(a.writable||a.value===s.value)},"canCopyProperty"),gPr=t((a,s)=>{let l=Object.getPrototypeOf(s);l!==Object.getPrototypeOf(a)&&Object.setPrototypeOf(a,l)},"changePrototype"),yPr=t((a,s)=>`/* Wrapped ${a}*/
653
653
  ${s}`,"wrappedToString"),vPr=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),bPr=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),SPr=t((a,s,l)=>{let _=l===""?"":`with ${l.trim()}() `,h=yPr.bind(null,_,s.toString());Object.defineProperty(h,"name",bPr),Object.defineProperty(a,"toString",{...vPr,value:h})},"changeToString");function L9e(a,s,{ignoreNonConfigurable:l=!1}={}){let{name:_}=a;for(let h of Reflect.ownKeys(s))mPr(a,s,h,l);return gPr(a,s),SPr(a,s,_),a}t(L9e,"mimicFunction");var fde=new WeakMap,HTt=t((a,s={})=>{if(typeof a!="function")throw new TypeError("Expected a function");let l,_=0,h=a.displayName||a.name||"<anonymous>",b=t(function(...D){if(fde.set(b,++_),_===1)l=a.apply(this,D),a=null;else if(s.throw===!0)throw new Error(`Function \`${h}\` can only be called once`);return l},"onetime");return L9e(b,a),fde.set(b,_),b},"onetime");HTt.callCount=a=>{if(!fde.has(a))throw new Error(`The given function \`${a.name}\` is not wrapped by the \`onetime\` package`);return fde.get(a)};var GTt=HTt;import{constants as EPr}from"os";var KTt=t(function(){let a=R9e-YTt+1;return Array.from({length:a},TPr)},"getRealtimeSignals"),TPr=t(function(a,s){return{name:`SIGRT${s+1}`,number:YTt+s,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}},"getRealtimeSignal"),YTt=34,R9e=64;import{constants as xPr}from"os";var XTt=[{name:"SIGHUP",number:1,action:"terminate",description:"Terminal closed",standard:"posix"},{name:"SIGINT",number:2,action:"terminate",description:"User interruption with CTRL-C",standard:"ansi"},{name:"SIGQUIT",number:3,action:"core",description:"User interruption with CTRL-\\",standard:"posix"},{name:"SIGILL",number:4,action:"core",description:"Invalid machine instruction",standard:"ansi"},{name:"SIGTRAP",number:5,action:"core",description:"Debugger breakpoint",standard:"posix"},{name:"SIGABRT",number:6,action:"core",description:"Aborted",standard:"ansi"},{name:"SIGIOT",number:6,action:"core",description:"Aborted",standard:"bsd"},{name:"SIGBUS",number:7,action:"core",description:"Bus error due to misaligned, non-existing address or paging error",standard:"bsd"},{name:"SIGEMT",number:7,action:"terminate",description:"Command should be emulated but is not implemented",standard:"other"},{name:"SIGFPE",number:8,action:"core",description:"Floating point arithmetic error",standard:"ansi"},{name:"SIGKILL",number:9,action:"terminate",description:"Forced termination",standard:"posix",forced:!0},{name:"SIGUSR1",number:10,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGSEGV",number:11,action:"core",description:"Segmentation fault",standard:"ansi"},{name:"SIGUSR2",number:12,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGPIPE",number:13,action:"terminate",description:"Broken pipe or socket",standard:"posix"},{name:"SIGALRM",number:14,action:"terminate",description:"Timeout or timer",standard:"posix"},{name:"SIGTERM",number:15,action:"terminate",description:"Termination",standard:"ansi"},{name:"SIGSTKFLT",number:16,action:"terminate",description:"Stack is empty or overflowed",standard:"other"},{name:"SIGCHLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"posix"},{name:"SIGCLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"other"},{name:"SIGCONT",number:18,action:"unpause",description:"Unpaused",standard:"posix",forced:!0},{name:"SIGSTOP",number:19,action:"pause",description:"Paused",standard:"posix",forced:!0},{name:"SIGTSTP",number:20,action:"pause",description:'Paused using CTRL-Z or "suspend"',standard:"posix"},{name:"SIGTTIN",number:21,action:"pause",description:"Background process cannot read terminal input",standard:"posix"},{name:"SIGBREAK",number:21,action:"terminate",description:"User interruption with CTRL-BREAK",standard:"other"},{name:"SIGTTOU",number:22,action:"pause",description:"Background process cannot write to terminal output",standard:"posix"},{name:"SIGURG",number:23,action:"ignore",description:"Socket received out-of-band data",standard:"bsd"},{name:"SIGXCPU",number:24,action:"core",description:"Process timed out",standard:"bsd"},{name:"SIGXFSZ",number:25,action:"core",description:"File too big",standard:"bsd"},{name:"SIGVTALRM",number:26,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGPROF",number:27,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGWINCH",number:28,action:"ignore",description:"Terminal window size changed",standard:"bsd"},{name:"SIGIO",number:29,action:"terminate",description:"I/O is available",standard:"other"},{name:"SIGPOLL",number:29,action:"terminate",description:"Watched event",standard:"other"},{name:"SIGINFO",number:29,action:"ignore",description:"Request for process information",standard:"other"},{name:"SIGPWR",number:30,action:"terminate",description:"Device running out of power",standard:"systemv"},{name:"SIGSYS",number:31,action:"core",description:"Invalid system call",standard:"other"},{name:"SIGUNUSED",number:31,action:"terminate",description:"Invalid system call",standard:"other"}];var M9e=t(function(){let a=KTt();return[...XTt,...a].map(CPr)},"getSignals"),CPr=t(function({name:a,number:s,description:l,action:_,forced:h=!1,standard:b}){let{signals:{[a]:D}}=xPr,N=D!==void 0;return{name:a,number:N?D:s,description:l,supported:N,action:_,forced:h,standard:b}},"normalizeSignal");var DPr=t(function(){return M9e().reduce(kPr,{})},"getSignalsByName"),kPr=t(function(a,{name:s,number:l,description:_,supported:h,action:b,forced:D,standard:N}){return{...a,[s]:{name:s,number:l,description:_,supported:h,action:b,forced:D,standard:N}}},"getSignalByName"),QTt=DPr(),wPr=t(function(){let a=M9e(),s=R9e+1,l=Array.from({length:s},(_,h)=>PPr(h,a));return Object.assign({},...l)},"getSignalsByNumber"),PPr=t(function(a,s){let l=APr(a,s);if(l===void 0)return{};let{name:_,description:h,supported:b,action:D,forced:N,standard:M}=l;return{[a]:{name:_,number:a,description:h,supported:b,action:D,forced:N,standard:M}}},"getSignalByNumber"),APr=t(function(a,s){let l=s.find(({name:_})=>EPr.signals[_]===a);return l!==void 0?l:s.find(_=>_.number===a)},"findSignalByNumber"),CHr=wPr();var NPr=t(({timedOut:a,timeout:s,errorCode:l,signal:_,signalDescription:h,exitCode:b,isCanceled:D})=>a?`timed out after ${s} milliseconds`:D?"was canceled":l!==void 0?`failed with ${l}`:_!==void 0?`was killed with ${_} (${h})`:b!==void 0?`failed with exit code ${b}`:"failed","getErrorPrefix"),j9e=t(({stdout:a,stderr:s,all:l,error:_,signal:h,exitCode:b,command:D,escapedCommand:N,timedOut:M,isCanceled:z,killed:re,parsed:{options:{timeout:ie}}})=>{b=b===null?void 0:b,h=h===null?void 0:h;let Q=h===void 0?void 0:QTt[h].description,Re=_&&_.code,we=`Command ${NPr({timedOut:M,timeout:ie,errorCode:Re,signal:h,signalDescription:Q,exitCode:b,isCanceled:z})}: ${D}`,wt=Object.prototype.toString.call(_)==="[object Error]",xt=wt?`${we}
654
654
  ${_.message}`:we,Tr=[xt,s,a].filter(Boolean).join(`
655
- `);return wt?(_.originalMessage=_.message,_.message=Tr):_=new Error(Tr),_.shortMessage=xt,_.command=D,_.escapedCommand=N,_.exitCode=b,_.signal=h,_.signalDescription=Q,_.stdout=a,_.stderr=s,l!==void 0&&(_.all=l),"bufferedData"in _&&delete _.bufferedData,_.failed=!0,_.timedOut=!!M,_.isCanceled=z,_.killed=re&&!M,_},"makeError");var _de=["stdin","stdout","stderr"],IPr=t(a=>_de.some(s=>a[s]!==void 0),"hasAlias"),ZTt=t(a=>{if(!a)return;let{stdio:s}=a;if(s===void 0)return _de.map(_=>a[_]);if(IPr(a))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${_de.map(_=>`\`${_}\``).join(", ")}`);if(typeof s=="string")return s;if(!Array.isArray(s))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof s}\``);let l=Math.max(s.length,_de.length);return Array.from({length:l},(_,h)=>s[h])},"normalizeStdio");var axt=ap(sxt(),1);import FPr from"node:os";var OPr=1e3*5,oxt=t((a,s="SIGTERM",l={})=>{let _=a(s);return LPr(a,s,l,_),_},"spawnedKill"),LPr=t((a,s,l,_)=>{if(!RPr(s,l,_))return;let h=jPr(l),b=setTimeout(()=>{a("SIGKILL")},h);b.unref&&b.unref()},"setKillTimeout"),RPr=t((a,{forceKillAfterTimeout:s},l)=>MPr(a)&&s!==!1&&l,"shouldForceKill"),MPr=t(a=>a===FPr.constants.signals.SIGTERM||typeof a=="string"&&a.toUpperCase()==="SIGTERM","isSigterm"),jPr=t(({forceKillAfterTimeout:a=!0})=>{if(a===!0)return OPr;if(!Number.isFinite(a)||a<0)throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${a}\` (${typeof a})`);return a},"getForceKillAfterTimeout"),cxt=t((a,s)=>{a.kill()&&(s.isCanceled=!0)},"spawnedCancel"),BPr=t((a,s,l)=>{a.kill(s),l(Object.assign(new Error("Timed out"),{timedOut:!0,signal:s}))},"timeoutKill"),lxt=t((a,{timeout:s,killSignal:l="SIGTERM"},_)=>{if(s===0||s===void 0)return _;let h,b=new Promise((N,M)=>{h=setTimeout(()=>{BPr(a,l,M)},s)}),D=_.finally(()=>{clearTimeout(h)});return Promise.race([b,D])},"setupTimeout"),uxt=t(({timeout:a})=>{if(a!==void 0&&(!Number.isFinite(a)||a<0))throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${a}\` (${typeof a})`)},"validateTimeout"),fxt=t(async(a,{cleanup:s,detached:l},_)=>{if(!s||l)return _;let h=(0,axt.default)(()=>{a.kill()});return _.finally(()=>{h()})},"setExitHandler");function _xt(a){return a!==null&&typeof a=="object"&&typeof a.pipe=="function"}t(_xt,"isStream");var q9e=ap(mxt(),1),yxt=ap(gxt(),1);var vxt=t((a,s)=>{s===void 0||a.stdin===void 0||(_xt(s)?s.pipe(a.stdin):a.stdin.end(s))},"handleInput"),bxt=t((a,{all:s})=>{if(!s||!a.stdout&&!a.stderr)return;let l=(0,yxt.default)();return a.stdout&&l.add(a.stdout),a.stderr&&l.add(a.stderr),l},"makeAllStream"),z9e=t(async(a,s)=>{if(a){a.destroy();try{return await s}catch(l){return l.bufferedData}}},"getBufferedData"),J9e=t((a,{encoding:s,buffer:l,maxBuffer:_})=>{if(!(!a||!l))return s?(0,q9e.default)(a,{encoding:s,maxBuffer:_}):q9e.default.buffer(a,{maxBuffer:_})},"getStreamPromise"),Sxt=t(async({stdout:a,stderr:s,all:l},{encoding:_,buffer:h,maxBuffer:b},D)=>{let N=J9e(a,{encoding:_,buffer:h,maxBuffer:b}),M=J9e(s,{encoding:_,buffer:h,maxBuffer:b}),z=J9e(l,{encoding:_,buffer:h,maxBuffer:b*2});try{return await Promise.all([D,N,M,z])}catch(re){return Promise.all([{error:re,signal:re.signal,timedOut:re.timedOut},z9e(a,N),z9e(s,M),z9e(l,z)])}},"getSpawnedResult");var HPr=(async()=>{})().constructor.prototype,GPr=["then","catch","finally"].map(a=>[a,Reflect.getOwnPropertyDescriptor(HPr,a)]),V9e=t((a,s)=>{for(let[l,_]of GPr){let h=typeof s=="function"?(...b)=>Reflect.apply(_.value,s(),b):_.value.bind(s);Reflect.defineProperty(a,l,{..._,value:h})}return a},"mergePromise"),Txt=t(a=>new Promise((s,l)=>{a.on("exit",(_,h)=>{s({exitCode:_,signal:h})}),a.on("error",_=>{l(_)}),a.stdin&&a.stdin.on("error",_=>{l(_)})}),"getSpawnedPromise");var xxt=t((a,s=[])=>Array.isArray(s)?[a,...s]:[a],"normalizeArgs"),KPr=/^[\w.-]+$/,YPr=/"/g,XPr=t(a=>typeof a!="string"||KPr.test(a)?a:`"${a.replace(YPr,'\\"')}"`,"escapeArg"),Cxt=t((a,s)=>xxt(a,s).join(" "),"joinCommand"),Ext=t((a,s)=>xxt(a,s).map(l=>XPr(l)).join(" "),"getEscapedCommand");var eAr=1e3*1e3*100,tAr=t(({env:a,extendEnv:s,preferLocal:l,localDir:_,execPath:h})=>{let b=s?{...yde.env,...a}:a;return l?WTt({env:b,cwd:_,execPath:h}):b},"getEnv"),rAr=t((a,s,l={})=>{let _=kxt.default._parse(a,s,l);return a=_.command,s=_.args,l=_.options,l={maxBuffer:eAr,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:l.cwd||yde.cwd(),execPath:yde.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,...l},l.env=tAr(l),l.stdio=ZTt(l),yde.platform==="win32"&&ZPr.basename(a,".exe")==="cmd"&&s.unshift("/q"),{file:a,args:s,options:l,parsed:_}},"handleArguments"),W9e=t((a,s,l)=>typeof s!="string"&&!QPr.isBuffer(s)?l===void 0?void 0:"":a.stripFinalNewline?O9e(s):s,"handleOutput");function wxt(a,s,l){let _=rAr(a,s,l),h=Cxt(a,s),b=Ext(a,s);uxt(_.options);let D;try{D=Dxt.spawn(_.file,_.args,_.options)}catch(Re){let Ne=new Dxt.ChildProcess,we=Promise.reject(j9e({error:Re,stdout:"",stderr:"",all:"",command:h,escapedCommand:b,parsed:_,timedOut:!1,isCanceled:!1,killed:!1}));return V9e(Ne,we)}let N=Txt(D),M=lxt(D,_.options,N),z=fxt(D,_.options,M),re={isCanceled:!1};D.kill=oxt.bind(null,D.kill.bind(D)),D.cancel=cxt.bind(null,D,re);let Q=GTt(t(async()=>{let[{error:Re,exitCode:Ne,signal:we,timedOut:wt},xt,Tr,fn]=await Sxt(D,_.options,z),tn=W9e(_.options,xt),cn=W9e(_.options,Tr),Cr=W9e(_.options,fn);if(Re||Ne!==0||we!==null){let vr=j9e({error:Re,exitCode:Ne,signal:we,stdout:tn,stderr:cn,all:Cr,command:h,escapedCommand:b,parsed:_,timedOut:wt,isCanceled:re.isCanceled||(_.options.signal?_.options.signal.aborted:!1),killed:D.killed});if(!_.options.reject)return vr;throw vr}return{command:h,escapedCommand:b,exitCode:0,stdout:tn,stderr:cn,all:Cr,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}},"handlePromise"));return vxt(D,_.options.input),D.all=bxt(D,_.options),V9e(D,Q)}t(wxt,"execa");async function bde(a,s){if(a.__ZUPLO_LOG_LEVEL=process.env.__ZUPLO_LOG_LEVEL??process.env.LOG_LEVEL,a.__ZUPLO_LOG_FORMAT=process.env.__ZUPLO_LOG_FORMAT??process.env.LOG_FORMAT,a.LOG_LEVEL=process.env.LOG_LEVEL??process.env.LOG_LEVEL,a.LOG_FORMAT=process.env.LOG_FORMAT??process.env.LOG_FORMAT,a.GIT_SHA=process.env.GIT_SHA??await nAr(s),process.env.__ZUPLO_CONFIG&&(a.__ZUPLO_CONFIG=process.env.__ZUPLO_CONFIG),Pxt(vde.join(s,".env.zuplo"))){let l=Axt(vde.join(s,".env.zuplo"),"utf8"),_=H9e.default.parse(l);for(let h of Object.keys(_))if(a[h]=_[h],h==="ZUPLO_SYSTEM_CONFIGURATIONS"){let b=Buffer.from(pue.decode(_[h])).toString(),D=JSON.parse(b);for(let N of Object.keys(D))a[N]=D[N]}}if(Pxt(vde.join(s,".env"))){let l=Axt(vde.join(s,".env"),"utf8"),_=H9e.default.parse(l);for(let h of Object.keys(_))a[h]=_[h]}for(let l of Object.keys(a))a[l]===void 0&&delete a[l];return a}t(bde,"setEnvironment");async function nAr(a){let s="unknown";try{let{stdout:l}=await wxt("git",["rev-parse","HEAD"],{cwd:a});l.trim().length===40&&(s=l.trim())}catch{}return s}t(nAr,"getGitSha");async function oAr({buildId:a,output:s,sourceDirectory:l,bundledDir:_,port:h,binaryName:b,publicZuploEnvironmentVariables:D,logger:N,handleRuntimeStdio:M}){if(_){let re=wY.join(l,_,"modules.json");if(!iAr(re))throw new Error("The bundled-dir does not contain a modules.json file.");let ie=await aAr(re,"utf-8").then(JSON.parse),Q=await cB(l);return Q.status===hA?new Promise((Re,Ne)=>{z(Q.config.compatibilityDate,wY.join(l,_),ie,Re,M)().catch(we=>{N.error(we),Ne(we)})}):(N.warn("Failed to get Zuplo config. Using default compatibility date."),new Promise((Re,Ne)=>{z(void 0,l,ie,Re,M)().catch(we=>{N.error(we),Ne(we)})}))}else{let re=new DN({buildId:a,output:s,sourceDirectory:l,command:"dev",logger:N,publicZuploEnvironmentVariables:D??{ZUPLO_ENVIRONMENT_TYPE:"LOCAL_DEVELOPMENT"},deploymentUrl:void 0});try{await re.start()}catch{N.info("Ran into irrecoverable error while building. Fix the error and rerun the command."),process.exit(1)}return new Promise((ie,Q)=>{re.onReload((Re,Ne)=>{(Ne||Re&&Re.errors&&Re.errors.length>0)&&Q(Ne??Re?.errors),z(Re?.compatibilityDate,wY.join(l,"dist"),Uj(l,Re?.metafile),ie,M)().catch(we=>{N.error(we),Q(we)})})})}function z(re,ie,Q,Re,Ne){return async()=>{let we={};await bde(we,l);let wt=new Nxt.ZuploWorkerd({compatibilityDate:re,scriptDirectory:ie,modules:Q,port:h??ih.DEV_SERVER_PORT,bindings:we,handleRuntimeStdio:Ne}),xt=b??"compiled-zup",Tr=wY.join(l,"dist");await sAr(Tr,{recursive:!0}),await wt.compileBinary({binaryPath:wY.join(l,"dist",xt)}),await wt.dispose(),Re(void 0)}}t(z,"compile")}t(oAr,"compileWorkerdServer");var Ixt=ap(S9e(),1);import lAr from"node:path";import cAr from"node:net";function PY(a,s){return new Promise(l=>{let _=new cAr.Socket;_.connect(s,a),_.on("connect",()=>{_.destroy(),l(!1)}),_.on("error",()=>{_.destroy(),l(!0)})})}t(PY,"isPortAvailable");var Sde=class{static{t(this,"WorkerdServer")}sourceDirectory;port;debugPort;buildWatcher;workerd;logger;output;handleRuntimeStdio;onReload;constructor(s){this.sourceDirectory=s.sourceDirectory,this.port=s.port??ih.DEV_SERVER_PORT,this.debugPort=s.debugPort,this.logger=s.logger,this.output=s.output,this.handleRuntimeStdio=s.handleRuntimeStdio,this.onReload=s.onReload,s.zupTestMode||(this.buildWatcher=new DN({...s,logger:this.logger,publicZuploEnvironmentVariables:s.publicZuploEnvironmentVariables??{ZUPLO_ENVIRONMENT_TYPE:"LOCAL_DEVELOPMENT"},deploymentUrl:void 0}),this.buildWatcher.watchEnvFiles())}async start(){if(!await PY("localhost",this.port))throw new Error(`Port ${this.port} is currently in use. Please use a different port.`);if(this.buildWatcher)try{await this.buildWatcher.start()}catch(l){this.output.child("api").error(l.toString());let _="Ran into irrecoverable error while starting watcher. Fix the error and restart the server.";this.output.child("api").error(_),this.logger?.info(_),process.exit(1)}await this.startOrReload(),this.buildWatcher?.onReload((l,_)=>{_||l&&l.errors&&l.errors.length>0||(this.onReload(l,_),this.startOrReload(l).catch(h=>{this.output.child("api").error(h.toString()),this.logger?.error(h)}))})}async startOrReload(s){try{let l={};await bde(l,this.sourceDirectory),await this.workerd?.dispose(),this.workerd=new Ixt.ZuploWorkerd({compatibilityDate:s?.compatibilityDate,scriptDirectory:lAr.join(this.sourceDirectory,"dist"),modules:Uj(this.sourceDirectory,s?.metafile),port:this.port,inspectorPort:this.debugPort??void 0,bindings:l,handleRuntimeStdio:this.handleRuntimeStdio}),await this.workerd.serve()}catch(l){this.logger?.debug(l)}}async stop(){await this.buildWatcher?.close(),await this.workerd?.dispose()}};import{fileURLToPath as Mxt}from"node:url";import{Readable as Fxt}from"node:stream";import Oxt from"node:assert";import uAr from"node:child_process";import fAr from"node:fs";import Tde from"node:os";import _Ar from"node:path";function Lxt(a,s){let l=import.meta.resolve(a),_=new URL(".",l),h=new URL(s,_);if(fAr.existsSync(h))return Mxt(h)}t(Lxt,"getValidExecutablePath");function pAr(){let a=Tde.platform()==="win32"?"deno.exe":"deno",s=Lxt("deno/package.json",a);if(s)return s;let l=dAr(),_=Lxt(`@deno/${l}/package.json`,a);if(_)return _;throw new Error("Failed to locate the managed-dedicated server executable.")}t(pAr,"locateDenoExecutable");function dAr(){let a=Tde.platform();return a==="linux"?a+"-"+Rxt()+"-glibc":a+"-"+Rxt()}t(dAr,"getTarget");function Rxt(){let a=Tde.arch();if(a!=="arm64"&&a!=="x64")throw new Error("Unsupported architecture "+Tde.arch()+". Only x64 and aarch64 binaries are available.");return a}t(Rxt,"getArch");var xde=class{static{t(this,"ZenoServer")}serverProcess;debugPort;processExitPromise;logger;output;buildWatcher;onReload;handleRuntimeStdio;denoExecutablePath;constructor(s){this.debugPort=s.debugPort,this.logger=s.logger,this.output=s.output,this.onReload=s.onReload,this.handleRuntimeStdio=s.handleRuntimeStdio,s.zupTestMode||(this.buildWatcher=new DN({sourceDirectory:s.sourceDirectory,command:"dev",logger:s.logger,publicZuploEnvironmentVariables:s.publicZuploEnvironmentVariables??{ZUPLO_ENVIRONMENT_TYPE:"LOCAL_DEVELOPMENT"},buildId:"dev",output:s.output,deploymentUrl:void 0}),this.buildWatcher.watchEnvFiles()),this.denoExecutablePath=pAr()}getServeArgs(){let s=`${_Ar.dirname(Mxt(import.meta.url))}/zeno.js`,l=["run","--allow-read","--allow-net","--allow-env","--allow-write"];return this.debugPort&&l.push(`--inspect=127.0.0.1:${this.debugPort}`),l.push(s),l}async getUnavailablePorts(){let s=[];return this.debugPort&&!await PY("127.0.0.1",this.debugPort)&&s.push(this.debugPort),await PY("127.0.0.1",9e3)||s.push(9e3),s}async start(){let s=await this.getUnavailablePorts();if(s.length>0)throw new Error("The following ports are not available: "+s.join(", "));if(this.buildWatcher)try{await this.buildWatcher.start()}catch(l){this.output.child("api").error(l.toString());let _="Ran into irrecoverable error while starting watcher. Fix the error and restart the server.";this.output.child("api").error(_),this.logger?.info(_),process.exit(1)}await this.startOrReload(),this.buildWatcher?.onReload((l,_)=>{_||l&&l.errors&&l.errors.length>0||(this.onReload(l,_),this.startOrReload().catch(h=>{this.output.child("api").error(h.toString()),this.logger?.error(h)}))})}async startOrReload(){try{await this.dispose(),this.logger?.info("Starting managed-dedicated local server");let s=this.getServeArgs();this.serverProcess=uAr.spawn(this.denoExecutablePath,s,{stdio:["pipe","pipe","pipe"],env:{...process.env,FORCE_COLOR:"1"}}),Oxt(this.serverProcess.stdout instanceof Fxt),Oxt(this.serverProcess.stderr instanceof Fxt),this.processExitPromise=this.waitForExit(),this.handleRuntimeStdio(this.serverProcess.stdout,this.serverProcess.stderr)}catch(s){this.logger?.debug(s)}}waitForExit(){return new Promise(s=>{this.serverProcess?.once("exit",s)})}dispose(){return this.serverProcess?.kill("SIGKILL"),this.processExitPromise}async stop(){await this.dispose(),await this.buildWatcher?.close()}};async function mAr(a){let s=await cB(a),l=!1;return s.status===hA&&(l=s.config.flags?.managedDedicatedFlags?.useZeno??!1),l||process.env.ZUPLO_DEV_RUNTIME==="zeno"}t(mAr,"useZeno");async function hAr({sourceDirectory:a,port:s,debugPort:l,publicZuploEnvironmentVariables:_,logger:h,output:b,buildId:D,onReload:N,handleRuntimeStdio:M}){process.env.ZUPLO_IS_LOCAL_DEVELOPMENT="true";let z;await mAr(a)?(h.debug("Starting managed-dedicated local dev server."),z=new xde({sourceDirectory:a,debugPort:l,logger:h,output:b,publicZuploEnvironmentVariables:_,onReload:N,handleRuntimeStdio:M})):(h.debug("Starting edge local dev server."),z=new Sde({sourceDirectory:a,command:"dev",port:s,debugPort:l,publicZuploEnvironmentVariables:_,logger:h,output:b,buildId:D,onReload:N,handleRuntimeStdio:M})),await z.start();async function re(){await z.stop()}t(re,"handle"),process.on("SIGTERM",re),process.on("SIGINT",re)}t(hAr,"startDevServer");var fCt=ap(Uxt(),1),_Ct=ap(lCt(),1);import{readFile as XAr}from"node:fs/promises";import LY from"node:path";var KAr=new RegExp("^((https|http)://)?[a-zA-Z0-9]{3}\\.[a-zA-Z0-9][a-zA-Z0-9]{0,61}?[a-zA-Z0-9]\\.(com|net|cn|cc)(:[0-9]{1,4})?/$"),YAr={concat(a,s){return LY.join(a,s)},resolve(a){return this.isAbsolute(a)?this.normalize(a):this.normalize(this.concat(process.cwd(),a))},normalize(a){let s=LY.normalize(a),l=LY.sep,_=[],h=0;return s.split(l).reverse().filter(D=>D!==".").forEach(D=>{D===".."?h++:h===0?_.push(D):h--}),_.reverse().join(l)},isData(a){return a.startsWith("data:")},isURL(a){return KAr.test(a)},isAbsolute(a){return LY.isAbsolute(a)},relativeToFile(a,s){if(this.isData(a)||this.isAbsolute(s))return this.normalize(s);{let l=LY.dirname(a);return this.normalize(this.concat(l,s))}}},Fde=YAr;var uCt=t(a=>{let s=t(l=>l in s.cache?s.cache[l]:s.cache[l]=a(l),"m");return s.forgetEverything=()=>{s.cache=Object.create(null)},s.cache=Object.create(null),s},"memoize");function sLe(a){let s=uCt(async D=>await l(D,await a(D)));async function l(D,N){if(N===void 0)return s(Fde.resolve(D));let M,z,re=t(async Q=>(z=z||await _(ie))(Q),"_resolve"),ie={path:D,text:N,get lines(){return M=M||N.split(`
655
+ `);return wt?(_.originalMessage=_.message,_.message=Tr):_=new Error(Tr),_.shortMessage=xt,_.command=D,_.escapedCommand=N,_.exitCode=b,_.signal=h,_.signalDescription=Q,_.stdout=a,_.stderr=s,l!==void 0&&(_.all=l),"bufferedData"in _&&delete _.bufferedData,_.failed=!0,_.timedOut=!!M,_.isCanceled=z,_.killed=re&&!M,_},"makeError");var _de=["stdin","stdout","stderr"],IPr=t(a=>_de.some(s=>a[s]!==void 0),"hasAlias"),ZTt=t(a=>{if(!a)return;let{stdio:s}=a;if(s===void 0)return _de.map(_=>a[_]);if(IPr(a))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${_de.map(_=>`\`${_}\``).join(", ")}`);if(typeof s=="string")return s;if(!Array.isArray(s))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof s}\``);let l=Math.max(s.length,_de.length);return Array.from({length:l},(_,h)=>s[h])},"normalizeStdio");var axt=ap(sxt(),1);import FPr from"node:os";var OPr=1e3*5,oxt=t((a,s="SIGTERM",l={})=>{let _=a(s);return LPr(a,s,l,_),_},"spawnedKill"),LPr=t((a,s,l,_)=>{if(!RPr(s,l,_))return;let h=jPr(l),b=setTimeout(()=>{a("SIGKILL")},h);b.unref&&b.unref()},"setKillTimeout"),RPr=t((a,{forceKillAfterTimeout:s},l)=>MPr(a)&&s!==!1&&l,"shouldForceKill"),MPr=t(a=>a===FPr.constants.signals.SIGTERM||typeof a=="string"&&a.toUpperCase()==="SIGTERM","isSigterm"),jPr=t(({forceKillAfterTimeout:a=!0})=>{if(a===!0)return OPr;if(!Number.isFinite(a)||a<0)throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${a}\` (${typeof a})`);return a},"getForceKillAfterTimeout"),cxt=t((a,s)=>{a.kill()&&(s.isCanceled=!0)},"spawnedCancel"),BPr=t((a,s,l)=>{a.kill(s),l(Object.assign(new Error("Timed out"),{timedOut:!0,signal:s}))},"timeoutKill"),lxt=t((a,{timeout:s,killSignal:l="SIGTERM"},_)=>{if(s===0||s===void 0)return _;let h,b=new Promise((N,M)=>{h=setTimeout(()=>{BPr(a,l,M)},s)}),D=_.finally(()=>{clearTimeout(h)});return Promise.race([b,D])},"setupTimeout"),uxt=t(({timeout:a})=>{if(a!==void 0&&(!Number.isFinite(a)||a<0))throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${a}\` (${typeof a})`)},"validateTimeout"),fxt=t(async(a,{cleanup:s,detached:l},_)=>{if(!s||l)return _;let h=(0,axt.default)(()=>{a.kill()});return _.finally(()=>{h()})},"setExitHandler");function _xt(a){return a!==null&&typeof a=="object"&&typeof a.pipe=="function"}t(_xt,"isStream");var q9e=ap(mxt(),1),yxt=ap(gxt(),1);var vxt=t((a,s)=>{s===void 0||a.stdin===void 0||(_xt(s)?s.pipe(a.stdin):a.stdin.end(s))},"handleInput"),bxt=t((a,{all:s})=>{if(!s||!a.stdout&&!a.stderr)return;let l=(0,yxt.default)();return a.stdout&&l.add(a.stdout),a.stderr&&l.add(a.stderr),l},"makeAllStream"),z9e=t(async(a,s)=>{if(a){a.destroy();try{return await s}catch(l){return l.bufferedData}}},"getBufferedData"),J9e=t((a,{encoding:s,buffer:l,maxBuffer:_})=>{if(!(!a||!l))return s?(0,q9e.default)(a,{encoding:s,maxBuffer:_}):q9e.default.buffer(a,{maxBuffer:_})},"getStreamPromise"),Sxt=t(async({stdout:a,stderr:s,all:l},{encoding:_,buffer:h,maxBuffer:b},D)=>{let N=J9e(a,{encoding:_,buffer:h,maxBuffer:b}),M=J9e(s,{encoding:_,buffer:h,maxBuffer:b}),z=J9e(l,{encoding:_,buffer:h,maxBuffer:b*2});try{return await Promise.all([D,N,M,z])}catch(re){return Promise.all([{error:re,signal:re.signal,timedOut:re.timedOut},z9e(a,N),z9e(s,M),z9e(l,z)])}},"getSpawnedResult");var HPr=(async()=>{})().constructor.prototype,GPr=["then","catch","finally"].map(a=>[a,Reflect.getOwnPropertyDescriptor(HPr,a)]),V9e=t((a,s)=>{for(let[l,_]of GPr){let h=typeof s=="function"?(...b)=>Reflect.apply(_.value,s(),b):_.value.bind(s);Reflect.defineProperty(a,l,{..._,value:h})}return a},"mergePromise"),Txt=t(a=>new Promise((s,l)=>{a.on("exit",(_,h)=>{s({exitCode:_,signal:h})}),a.on("error",_=>{l(_)}),a.stdin&&a.stdin.on("error",_=>{l(_)})}),"getSpawnedPromise");var xxt=t((a,s=[])=>Array.isArray(s)?[a,...s]:[a],"normalizeArgs"),KPr=/^[\w.-]+$/,YPr=/"/g,XPr=t(a=>typeof a!="string"||KPr.test(a)?a:`"${a.replace(YPr,'\\"')}"`,"escapeArg"),Cxt=t((a,s)=>xxt(a,s).join(" "),"joinCommand"),Ext=t((a,s)=>xxt(a,s).map(l=>XPr(l)).join(" "),"getEscapedCommand");var eAr=1e3*1e3*100,tAr=t(({env:a,extendEnv:s,preferLocal:l,localDir:_,execPath:h})=>{let b=s?{...yde.env,...a}:a;return l?WTt({env:b,cwd:_,execPath:h}):b},"getEnv"),rAr=t((a,s,l={})=>{let _=kxt.default._parse(a,s,l);return a=_.command,s=_.args,l=_.options,l={maxBuffer:eAr,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:l.cwd||yde.cwd(),execPath:yde.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,...l},l.env=tAr(l),l.stdio=ZTt(l),yde.platform==="win32"&&ZPr.basename(a,".exe")==="cmd"&&s.unshift("/q"),{file:a,args:s,options:l,parsed:_}},"handleArguments"),W9e=t((a,s,l)=>typeof s!="string"&&!QPr.isBuffer(s)?l===void 0?void 0:"":a.stripFinalNewline?O9e(s):s,"handleOutput");function wxt(a,s,l){let _=rAr(a,s,l),h=Cxt(a,s),b=Ext(a,s);uxt(_.options);let D;try{D=Dxt.spawn(_.file,_.args,_.options)}catch(Re){let Ne=new Dxt.ChildProcess,we=Promise.reject(j9e({error:Re,stdout:"",stderr:"",all:"",command:h,escapedCommand:b,parsed:_,timedOut:!1,isCanceled:!1,killed:!1}));return V9e(Ne,we)}let N=Txt(D),M=lxt(D,_.options,N),z=fxt(D,_.options,M),re={isCanceled:!1};D.kill=oxt.bind(null,D.kill.bind(D)),D.cancel=cxt.bind(null,D,re);let Q=GTt(t(async()=>{let[{error:Re,exitCode:Ne,signal:we,timedOut:wt},xt,Tr,fn]=await Sxt(D,_.options,z),tn=W9e(_.options,xt),cn=W9e(_.options,Tr),Cr=W9e(_.options,fn);if(Re||Ne!==0||we!==null){let vr=j9e({error:Re,exitCode:Ne,signal:we,stdout:tn,stderr:cn,all:Cr,command:h,escapedCommand:b,parsed:_,timedOut:wt,isCanceled:re.isCanceled||(_.options.signal?_.options.signal.aborted:!1),killed:D.killed});if(!_.options.reject)return vr;throw vr}return{command:h,escapedCommand:b,exitCode:0,stdout:tn,stderr:cn,all:Cr,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}},"handlePromise"));return vxt(D,_.options.input),D.all=bxt(D,_.options),V9e(D,Q)}t(wxt,"execa");async function bde(a,s){if(a.__ZUPLO_LOG_LEVEL=process.env.__ZUPLO_LOG_LEVEL??process.env.LOG_LEVEL,a.__ZUPLO_LOG_FORMAT=process.env.__ZUPLO_LOG_FORMAT??process.env.LOG_FORMAT,a.LOG_LEVEL=process.env.LOG_LEVEL??process.env.LOG_LEVEL,a.LOG_FORMAT=process.env.LOG_FORMAT??process.env.LOG_FORMAT,a.GIT_SHA=process.env.GIT_SHA??await nAr(s),process.env.__ZUPLO_CONFIG&&(a.__ZUPLO_CONFIG=process.env.__ZUPLO_CONFIG),Pxt(vde.join(s,".env.zuplo"))){let l=Axt(vde.join(s,".env.zuplo"),"utf8"),_=H9e.default.parse(l);for(let h of Object.keys(_))if(a[h]=_[h],h==="ZUPLO_SYSTEM_CONFIGURATIONS"){let b=Buffer.from(pue.decode(_[h])).toString(),D=JSON.parse(b);for(let N of Object.keys(D))a[N]=D[N]}}if(Pxt(vde.join(s,".env"))){let l=Axt(vde.join(s,".env"),"utf8"),_=H9e.default.parse(l);for(let h of Object.keys(_))a[h]=_[h]}for(let l of Object.keys(a))a[l]===void 0&&delete a[l];return a}t(bde,"setEnvironment");async function nAr(a){let s="unknown";try{let{stdout:l}=await wxt("git",["rev-parse","HEAD"],{cwd:a});l.trim().length===40&&(s=l.trim())}catch{}return s}t(nAr,"getGitSha");async function oAr({buildId:a,output:s,sourceDirectory:l,bundledDir:_,port:h,binaryName:b,publicZuploEnvironmentVariables:D,logger:N,handleRuntimeStdio:M}){if(_){let re=wY.join(l,_,"modules.json");if(!iAr(re))throw new Error("The bundled-dir does not contain a modules.json file.");let ie=await aAr(re,"utf-8").then(JSON.parse),Q=await cB(l);return Q.status===hA?new Promise((Re,Ne)=>{z(Q.config.compatibilityDate,wY.join(l,_),ie,Re,M)().catch(we=>{N.error(we),Ne(we)})}):(N.warn("Failed to get Zuplo config. Using default compatibility date."),new Promise((Re,Ne)=>{z(void 0,l,ie,Re,M)().catch(we=>{N.error(we),Ne(we)})}))}else{let re=new DN({buildId:a,output:s,sourceDirectory:l,command:"dev",logger:N,publicZuploEnvironmentVariables:D??{ZUPLO_ENVIRONMENT_TYPE:"LOCAL_DEVELOPMENT"},urls:void 0});try{await re.start()}catch{N.info("Ran into irrecoverable error while building. Fix the error and rerun the command."),process.exit(1)}return new Promise((ie,Q)=>{re.onReload((Re,Ne)=>{(Ne||Re&&Re.errors&&Re.errors.length>0)&&Q(Ne??Re?.errors),z(Re?.compatibilityDate,wY.join(l,"dist"),Uj(l,Re?.metafile),ie,M)().catch(we=>{N.error(we),Q(we)})})})}function z(re,ie,Q,Re,Ne){return async()=>{let we={};await bde(we,l);let wt=new Nxt.ZuploWorkerd({compatibilityDate:re,scriptDirectory:ie,modules:Q,port:h??ih.DEV_SERVER_PORT,bindings:we,handleRuntimeStdio:Ne}),xt=b??"compiled-zup",Tr=wY.join(l,"dist");await sAr(Tr,{recursive:!0}),await wt.compileBinary({binaryPath:wY.join(l,"dist",xt)}),await wt.dispose(),Re(void 0)}}t(z,"compile")}t(oAr,"compileWorkerdServer");var Ixt=ap(S9e(),1);import lAr from"node:path";import cAr from"node:net";function PY(a,s){return new Promise(l=>{let _=new cAr.Socket;_.connect(s,a),_.on("connect",()=>{_.destroy(),l(!1)}),_.on("error",()=>{_.destroy(),l(!0)})})}t(PY,"isPortAvailable");var Sde=class{static{t(this,"WorkerdServer")}sourceDirectory;port;debugPort;buildWatcher;workerd;logger;output;handleRuntimeStdio;onReload;constructor(s){this.sourceDirectory=s.sourceDirectory,this.port=s.port??ih.DEV_SERVER_PORT,this.debugPort=s.debugPort,this.logger=s.logger,this.output=s.output,this.handleRuntimeStdio=s.handleRuntimeStdio,this.onReload=s.onReload,s.zupTestMode||(this.buildWatcher=new DN({...s,logger:this.logger,publicZuploEnvironmentVariables:s.publicZuploEnvironmentVariables??{ZUPLO_ENVIRONMENT_TYPE:"LOCAL_DEVELOPMENT"},urls:void 0}),this.buildWatcher.watchEnvFiles())}async start(){if(!await PY("localhost",this.port))throw new Error(`Port ${this.port} is currently in use. Please use a different port.`);if(this.buildWatcher)try{await this.buildWatcher.start()}catch(l){this.output.child("api").error(l.toString());let _="Ran into irrecoverable error while starting watcher. Fix the error and restart the server.";this.output.child("api").error(_),this.logger?.info(_),process.exit(1)}await this.startOrReload(),this.buildWatcher?.onReload((l,_)=>{_||l&&l.errors&&l.errors.length>0||(this.onReload(l,_),this.startOrReload(l).catch(h=>{this.output.child("api").error(h.toString()),this.logger?.error(h)}))})}async startOrReload(s){try{let l={};await bde(l,this.sourceDirectory),await this.workerd?.dispose(),this.workerd=new Ixt.ZuploWorkerd({compatibilityDate:s?.compatibilityDate,scriptDirectory:lAr.join(this.sourceDirectory,"dist"),modules:Uj(this.sourceDirectory,s?.metafile),port:this.port,inspectorPort:this.debugPort??void 0,bindings:l,handleRuntimeStdio:this.handleRuntimeStdio}),await this.workerd.serve()}catch(l){this.logger?.debug(l)}}async stop(){await this.buildWatcher?.close(),await this.workerd?.dispose()}};import{fileURLToPath as Mxt}from"node:url";import{Readable as Fxt}from"node:stream";import Oxt from"node:assert";import uAr from"node:child_process";import fAr from"node:fs";import Tde from"node:os";import _Ar from"node:path";function Lxt(a,s){let l=import.meta.resolve(a),_=new URL(".",l),h=new URL(s,_);if(fAr.existsSync(h))return Mxt(h)}t(Lxt,"getValidExecutablePath");function pAr(){let a=Tde.platform()==="win32"?"deno.exe":"deno",s=Lxt("deno/package.json",a);if(s)return s;let l=dAr(),_=Lxt(`@deno/${l}/package.json`,a);if(_)return _;throw new Error("Failed to locate the managed-dedicated server executable.")}t(pAr,"locateDenoExecutable");function dAr(){let a=Tde.platform();return a==="linux"?a+"-"+Rxt()+"-glibc":a+"-"+Rxt()}t(dAr,"getTarget");function Rxt(){let a=Tde.arch();if(a!=="arm64"&&a!=="x64")throw new Error("Unsupported architecture "+Tde.arch()+". Only x64 and aarch64 binaries are available.");return a}t(Rxt,"getArch");var xde=class{static{t(this,"ZenoServer")}serverProcess;debugPort;processExitPromise;logger;output;buildWatcher;onReload;handleRuntimeStdio;denoExecutablePath;constructor(s){this.debugPort=s.debugPort,this.logger=s.logger,this.output=s.output,this.onReload=s.onReload,this.handleRuntimeStdio=s.handleRuntimeStdio,s.zupTestMode||(this.buildWatcher=new DN({sourceDirectory:s.sourceDirectory,command:"dev",logger:s.logger,publicZuploEnvironmentVariables:s.publicZuploEnvironmentVariables??{ZUPLO_ENVIRONMENT_TYPE:"LOCAL_DEVELOPMENT"},buildId:"dev",output:s.output,urls:void 0}),this.buildWatcher.watchEnvFiles()),this.denoExecutablePath=pAr()}getServeArgs(){let s=`${_Ar.dirname(Mxt(import.meta.url))}/zeno.js`,l=["run","--allow-read","--allow-net","--allow-env","--allow-write"];return this.debugPort&&l.push(`--inspect=127.0.0.1:${this.debugPort}`),l.push(s),l}async getUnavailablePorts(){let s=[];return this.debugPort&&!await PY("127.0.0.1",this.debugPort)&&s.push(this.debugPort),await PY("127.0.0.1",9e3)||s.push(9e3),s}async start(){let s=await this.getUnavailablePorts();if(s.length>0)throw new Error("The following ports are not available: "+s.join(", "));if(this.buildWatcher)try{await this.buildWatcher.start()}catch(l){this.output.child("api").error(l.toString());let _="Ran into irrecoverable error while starting watcher. Fix the error and restart the server.";this.output.child("api").error(_),this.logger?.info(_),process.exit(1)}await this.startOrReload(),this.buildWatcher?.onReload((l,_)=>{_||l&&l.errors&&l.errors.length>0||(this.onReload(l,_),this.startOrReload().catch(h=>{this.output.child("api").error(h.toString()),this.logger?.error(h)}))})}async startOrReload(){try{await this.dispose(),this.logger?.info("Starting managed-dedicated local server");let s=this.getServeArgs();this.serverProcess=uAr.spawn(this.denoExecutablePath,s,{stdio:["pipe","pipe","pipe"],env:{...process.env,FORCE_COLOR:"1"}}),Oxt(this.serverProcess.stdout instanceof Fxt),Oxt(this.serverProcess.stderr instanceof Fxt),this.processExitPromise=this.waitForExit(),this.handleRuntimeStdio(this.serverProcess.stdout,this.serverProcess.stderr)}catch(s){this.logger?.debug(s)}}waitForExit(){return new Promise(s=>{this.serverProcess?.once("exit",s)})}dispose(){return this.serverProcess?.kill("SIGKILL"),this.processExitPromise}async stop(){await this.dispose(),await this.buildWatcher?.close()}};async function mAr(a){let s=await cB(a),l=!1;return s.status===hA&&(l=s.config.flags?.managedDedicatedFlags?.useZeno??!1),l||process.env.ZUPLO_DEV_RUNTIME==="zeno"}t(mAr,"useZeno");async function hAr({sourceDirectory:a,port:s,debugPort:l,publicZuploEnvironmentVariables:_,logger:h,output:b,buildId:D,onReload:N,handleRuntimeStdio:M}){process.env.ZUPLO_IS_LOCAL_DEVELOPMENT="true";let z;await mAr(a)?(h.debug("Starting managed-dedicated local dev server."),z=new xde({sourceDirectory:a,debugPort:l,logger:h,output:b,publicZuploEnvironmentVariables:_,onReload:N,handleRuntimeStdio:M})):(h.debug("Starting edge local dev server."),z=new Sde({sourceDirectory:a,command:"dev",port:s,debugPort:l,publicZuploEnvironmentVariables:_,logger:h,output:b,buildId:D,onReload:N,handleRuntimeStdio:M})),await z.start();async function re(){await z.stop()}t(re,"handle"),process.on("SIGTERM",re),process.on("SIGINT",re)}t(hAr,"startDevServer");var fCt=ap(Uxt(),1),_Ct=ap(lCt(),1);import{readFile as XAr}from"node:fs/promises";import LY from"node:path";var KAr=new RegExp("^((https|http)://)?[a-zA-Z0-9]{3}\\.[a-zA-Z0-9][a-zA-Z0-9]{0,61}?[a-zA-Z0-9]\\.(com|net|cn|cc)(:[0-9]{1,4})?/$"),YAr={concat(a,s){return LY.join(a,s)},resolve(a){return this.isAbsolute(a)?this.normalize(a):this.normalize(this.concat(process.cwd(),a))},normalize(a){let s=LY.normalize(a),l=LY.sep,_=[],h=0;return s.split(l).reverse().filter(D=>D!==".").forEach(D=>{D===".."?h++:h===0?_.push(D):h--}),_.reverse().join(l)},isData(a){return a.startsWith("data:")},isURL(a){return KAr.test(a)},isAbsolute(a){return LY.isAbsolute(a)},relativeToFile(a,s){if(this.isData(a)||this.isAbsolute(s))return this.normalize(s);{let l=LY.dirname(a);return this.normalize(this.concat(l,s))}}},Fde=YAr;var uCt=t(a=>{let s=t(l=>l in s.cache?s.cache[l]:s.cache[l]=a(l),"m");return s.forgetEverything=()=>{s.cache=Object.create(null)},s.cache=Object.create(null),s},"memoize");function sLe(a){let s=uCt(async D=>await l(D,await a(D)));async function l(D,N){if(N===void 0)return s(Fde.resolve(D));let M,z,re=t(async Q=>(z=z||await _(ie))(Q),"_resolve"),ie={path:D,text:N,get lines(){return M=M||N.split(`
656
656
  `)},async resolve(Q){try{return await re(Q)}catch(Re){return Object.assign({},Q,{error:Re})}},_resolve:re};return ie}t(l,"SourceFile");async function _(D){let N=/\u0023 sourceMappingURL=(.+)\n?/g,M;for(;;){let ie=N.exec(D.text);if(ie)M=ie;else break}let z=M&&M[1],re=t(async ie=>Object.assign({},ie,{sourceFile:D,sourceLine:D.lines[ie.line-1]||""}),"defaultResolver");return z?await h(D.path,z,re):re}t(_,"SourceMapResolverFromFetchedFile");async function h(D,N,M){let z=N.startsWith("data:")?await l(D,(0,fCt.dataUriToBuffer)(N).toString()):await l(Fde.relativeToFile(D,N)),re=await new _Ct.SourceMapConsumer(JSON.parse(z.text)),ie=uCt(async Q=>{let Re=Fde.relativeToFile(z.path,Q),Ne=re.sourceContentFor(Q,!0)||void 0;return await l(Re,Ne)});return async Q=>{try{let Re=re.originalPositionFor(Q);return Re.source?await(await ie(Re.source))._resolve(Object.assign({},Q,{line:Re.line,column:(Re.column??0)+1,name:Re.name})):M(Q)}catch(Re){return Object.assign(M(Q),{sourceMapError:Re})}}}t(h,"SourceMapResolver");let b=t(async function(N){try{return await l(N)}catch(M){let z={path:N,text:"",lines:[],error:M,async resolve(re){return Object.assign({},re,{error:M,sourceLine:"",sourceFile:z})},_resolve(re){return this.resolve(re)}};return z}},"getSource");return b.resetCache=()=>s.forgetEverything(),b.getCache=()=>s.cache,b}t(sLe,"buildGetSourceFunction");var QAr=t(async a=>XAr(a,{encoding:"utf8"}),"fetchFile"),pCt=sLe(QAr);import ZAr from"node:path";import e6r from"node:util";var dCt=t(a=>a[a.length-1],"lastOf"),RY=t(a=>a.replace(/\\/g,"/"),"nixSlashes"),t6r=t((a,s)=>{let l=a||[],_=[],h={label:void 0,items:[l[0]]};return l.forEach(b=>{let D=s(b);h.label!==D&&h.items.length?_.push(h={label:D,items:[b]}):h.items.push(b)}),_},"partition"),MY=class a{static{t(this,"StackTracey")}items;getSource;pathRoot;constructor(s,{offset:l,getSource:_}){this.getSource=_,this.pathRoot=`${RY(process.cwd())}/`;let h=s,b=s instanceof SyntaxError;if(l=l||0,s instanceof Error&&(s=s.stack||""),typeof s=="string"&&(s=this.rawParse(s).slice(l).map(D=>this.extractEntryMetadata(D))),Array.isArray(s)){if(b){let D=e6r.inspect(h).split(`
657
657
  `),N=D[0].split(":"),M=N.pop(),z=N.join(":");z&&s.unshift({file:RY(z),line:parseInt(M||"0",10),column:(D[2]||"").indexOf("^")+1,sourceLine:D[1],callee:"(syntax error)",syntaxError:!0,beforeParse:"",index:!1,native:!1,calleeShort:"",fileRelative:"",fileShort:"",fileName:"",thirdParty:!1})}this.items=s}else this.items=[]}extractEntryMetadata(s){let l=this.decomposePath(s.file||""),_=l[0],h=l[1];return Object.assign(s,{calleeShort:s.calleeShort||dCt((s.callee||"").split(".")),fileRelative:_,fileShort:this.shortenPath(_),fileName:dCt((s.file||"").split("/")),thirdParty:this.isThirdParty(_,h)&&!s.index,externalDomain:h})}shortenPath(s){return s.replace(/^node_modules\//,"").replace(/^webpack\/bootstrap\//,"").replace(/^__parcel_source_root\//,"")}decomposePath(s){let l=s,_=l.match(/^(http|https):\/\/([^\/]+)\/(.*)/),h=_?_[2]:void 0;return l=_?_[3]:l,l=ZAr.relative(this.pathRoot,l),[RY(l).replace(/^.*:\/\/?\/?/,""),h]}isThirdParty(s,l){return!!l||s[0]==="~"||s[0]==="/"||s.indexOf("node_modules")===0||s.indexOf("webpack/bootstrap")===0}rawParse(s){return(s||"").split(`
658
658
  `).map(h=>{h=h.trim();let b,D=[],N,M,z;if((M=h.match(/at (.+) \(eval at .+ \((.+)\), .+\)/))||(M=h.match(/at (.+) \((.+)\)/))||h.slice(0,3)!=="at "&&(M=h.match(/(.*)@(.*)/)))b=M[1],N=M[2]==="native",D=(M[2].match(/(.*):(\d+):(\d+)/)||M[2].match(/(.*):(\d+)/)||[]).slice(1);else if(z=h.match(/^(at\s+)*(.+):(\d+):(\d+)/))D=z.slice(2);else return;return b&&!D[0]&&b.split(".")[0]==="Array"&&(N=!0),{beforeParse:h,callee:b||"",index:D[0]==="/",native:N||!1,file:RY(D[0]||""),line:parseInt(D[1]||"",10)||void 0,column:parseInt(D[2]||"",10)||void 0,calleeShort:"",fileRelative:"",fileShort:"",fileName:"",thirdParty:!1}}).filter(h=>h!==void 0)}async withSourceAsyncAt(s){return this.items[s]&&this.withSourceAsync(this.items[s])}async withSourceAsync(s){if(this.shouldSkipResolving(s))return s;{let l=(s.file||"").replace("file://","");try{let h=await(await this.getSource(l)).resolve(s);return this.withSourceResolved(s,h)}catch(_){return this.withSourceResolved(s,{error:_,sourceLine:""})}}}shouldSkipResolving(s){return!!s.sourceFile||!!s.error||!!s.file&&s.file.indexOf("<")>=0}withSourceResolved(s,l){return l.sourceFile&&!l.sourceFile.error&&(l.file=RY(l.sourceFile.path),l=this.extractEntryMetadata(l)),l.sourceLine?.includes("// @hide")&&(l.sourceLine=l.sourceLine.replace("// @hide",""),l.hide=!0),(l.sourceLine?.includes("__webpack_require__")||l.sourceLine?.includes("/******/ ({"))&&(l.thirdParty=!0),Object.assign({sourceLine:""},s,l)}async withSourcesAsync(){let s=await Promise.all(this.items.map(l=>this.withSourceAsync(l)));return new a(s,{getSource:this.getSource})}mergeRepeatedLines(){return new a(t6r(this.items,s=>s.file+s.line).map(s=>s.items.slice(1).reduce((l,_)=>(l.callee=(l.callee||"<anonymous>")+" \u2192 "+(_.callee||"<anonymous>"),l.calleeShort=(l.calleeShort||"<anonymous>")+" \u2192 "+(_.calleeShort||"<anonymous>"),l),Object.assign({},s.items[0]))),{getSource:this.getSource})}async cleanAsync(){let s=await this.withSourcesAsync();return s.mergeRepeatedLines().filter((l,_)=>s.isClean(l,_))}isClean(s,l){return l===0||!(s.thirdParty||s.hide||s.native)}at(s){return Object.assign({beforeParse:"",callee:"<???>",index:!1,native:!1,file:"<???>",line:0,column:0},this.items[s])}map(s,l){return new a(this.items.map(s,l),{getSource:this.getSource})}filter(s,l){return new a(this.items.filter(s,l),{getSource:this.getSource})}slice(s,l){return new a(this.items.slice(s,l),{getSource:this.getSource})}concat(...s){return new a(this.items.concat(...s),{getSource:this.getSource})}maxColumnWidths(){return{callee:30,file:60,sourceLine:80}}static locationsEqual(s,l){return s.file===l.file&&s.line===l.line&&s.column===l.column}};import{relative as o6r}from"node:path";import{fileURLToPath as c6r}from"node:url";import{inspect as l6r}from"node:util";function aLe({onlyFirst:a=!1}={}){let l=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(l,a?void 0:"g")}t(aLe,"ansiRegex");var r6r=aLe();function oLe(a){if(typeof a!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof a}\``);return a.replace(r6r,"")}t(oLe,"stripAnsi");function mCt(a){return a===161||a===164||a===167||a===168||a===170||a===173||a===174||a>=176&&a<=180||a>=182&&a<=186||a>=188&&a<=191||a===198||a===208||a===215||a===216||a>=222&&a<=225||a===230||a>=232&&a<=234||a===236||a===237||a===240||a===242||a===243||a>=247&&a<=250||a===252||a===254||a===257||a===273||a===275||a===283||a===294||a===295||a===299||a>=305&&a<=307||a===312||a>=319&&a<=322||a===324||a>=328&&a<=331||a===333||a===338||a===339||a===358||a===359||a===363||a===462||a===464||a===466||a===468||a===470||a===472||a===474||a===476||a===593||a===609||a===708||a===711||a>=713&&a<=715||a===717||a===720||a>=728&&a<=731||a===733||a===735||a>=768&&a<=879||a>=913&&a<=929||a>=931&&a<=937||a>=945&&a<=961||a>=963&&a<=969||a===1025||a>=1040&&a<=1103||a===1105||a===8208||a>=8211&&a<=8214||a===8216||a===8217||a===8220||a===8221||a>=8224&&a<=8226||a>=8228&&a<=8231||a===8240||a===8242||a===8243||a===8245||a===8251||a===8254||a===8308||a===8319||a>=8321&&a<=8324||a===8364||a===8451||a===8453||a===8457||a===8467||a===8470||a===8481||a===8482||a===8486||a===8491||a===8531||a===8532||a>=8539&&a<=8542||a>=8544&&a<=8555||a>=8560&&a<=8569||a===8585||a>=8592&&a<=8601||a===8632||a===8633||a===8658||a===8660||a===8679||a===8704||a===8706||a===8707||a===8711||a===8712||a===8715||a===8719||a===8721||a===8725||a===8730||a>=8733&&a<=8736||a===8739||a===8741||a>=8743&&a<=8748||a===8750||a>=8756&&a<=8759||a===8764||a===8765||a===8776||a===8780||a===8786||a===8800||a===8801||a>=8804&&a<=8807||a===8810||a===8811||a===8814||a===8815||a===8834||a===8835||a===8838||a===8839||a===8853||a===8857||a===8869||a===8895||a===8978||a>=9312&&a<=9449||a>=9451&&a<=9547||a>=9552&&a<=9587||a>=9600&&a<=9615||a>=9618&&a<=9621||a===9632||a===9633||a>=9635&&a<=9641||a===9650||a===9651||a===9654||a===9655||a===9660||a===9661||a===9664||a===9665||a>=9670&&a<=9672||a===9675||a>=9678&&a<=9681||a>=9698&&a<=9701||a===9711||a===9733||a===9734||a===9737||a===9742||a===9743||a===9756||a===9758||a===9792||a===9794||a===9824||a===9825||a>=9827&&a<=9829||a>=9831&&a<=9834||a===9836||a===9837||a===9839||a===9886||a===9887||a===9919||a>=9926&&a<=9933||a>=9935&&a<=9939||a>=9941&&a<=9953||a===9955||a===9960||a===9961||a>=9963&&a<=9969||a===9972||a>=9974&&a<=9977||a===9979||a===9980||a===9982||a===9983||a===10045||a>=10102&&a<=10111||a>=11094&&a<=11097||a>=12872&&a<=12879||a>=57344&&a<=63743||a>=65024&&a<=65039||a===65533||a>=127232&&a<=127242||a>=127248&&a<=127277||a>=127280&&a<=127337||a>=127344&&a<=127373||a===127375||a===127376||a>=127387&&a<=127404||a>=917760&&a<=917999||a>=983040&&a<=1048573||a>=1048576&&a<=1114109}t(mCt,"isAmbiguous");function hCt(a){return a===12288||a>=65281&&a<=65376||a>=65504&&a<=65510}t(hCt,"isFullWidth");function gCt(a){return a>=4352&&a<=4447||a===8986||a===8987||a===9001||a===9002||a>=9193&&a<=9196||a===9200||a===9203||a===9725||a===9726||a===9748||a===9749||a>=9800&&a<=9811||a===9855||a===9875||a===9889||a===9898||a===9899||a===9917||a===9918||a===9924||a===9925||a===9934||a===9940||a===9962||a===9970||a===9971||a===9973||a===9978||a===9981||a===9989||a===9994||a===9995||a===10024||a===10060||a===10062||a>=10067&&a<=10069||a===10071||a>=10133&&a<=10135||a===10160||a===10175||a===11035||a===11036||a===11088||a===11093||a>=11904&&a<=11929||a>=11931&&a<=12019||a>=12032&&a<=12245||a>=12272&&a<=12287||a>=12289&&a<=12350||a>=12353&&a<=12438||a>=12441&&a<=12543||a>=12549&&a<=12591||a>=12593&&a<=12686||a>=12688&&a<=12771||a>=12783&&a<=12830||a>=12832&&a<=12871||a>=12880&&a<=19903||a>=19968&&a<=42124||a>=42128&&a<=42182||a>=43360&&a<=43388||a>=44032&&a<=55203||a>=63744&&a<=64255||a>=65040&&a<=65049||a>=65072&&a<=65106||a>=65108&&a<=65126||a>=65128&&a<=65131||a>=94176&&a<=94180||a===94192||a===94193||a>=94208&&a<=100343||a>=100352&&a<=101589||a>=101632&&a<=101640||a>=110576&&a<=110579||a>=110581&&a<=110587||a===110589||a===110590||a>=110592&&a<=110882||a===110898||a>=110928&&a<=110930||a===110933||a>=110948&&a<=110951||a>=110960&&a<=111355||a===126980||a===127183||a===127374||a>=127377&&a<=127386||a>=127488&&a<=127490||a>=127504&&a<=127547||a>=127552&&a<=127560||a===127568||a===127569||a>=127584&&a<=127589||a>=127744&&a<=127776||a>=127789&&a<=127797||a>=127799&&a<=127868||a>=127870&&a<=127891||a>=127904&&a<=127946||a>=127951&&a<=127955||a>=127968&&a<=127984||a===127988||a>=127992&&a<=128062||a===128064||a>=128066&&a<=128252||a>=128255&&a<=128317||a>=128331&&a<=128334||a>=128336&&a<=128359||a===128378||a===128405||a===128406||a===128420||a>=128507&&a<=128591||a>=128640&&a<=128709||a===128716||a>=128720&&a<=128722||a>=128725&&a<=128727||a>=128732&&a<=128735||a===128747||a===128748||a>=128756&&a<=128764||a>=128992&&a<=129003||a===129008||a>=129292&&a<=129338||a>=129340&&a<=129349||a>=129351&&a<=129535||a>=129648&&a<=129660||a>=129664&&a<=129672||a>=129680&&a<=129725||a>=129727&&a<=129733||a>=129742&&a<=129755||a>=129760&&a<=129768||a>=129776&&a<=129784||a>=131072&&a<=196605||a>=196608&&a<=262141}t(gCt,"isWide");function n6r(a){if(!Number.isSafeInteger(a))throw new TypeError(`Expected a code point, got \`${typeof a}\`.`)}t(n6r,"validate");function yCt(a,{ambiguousAsWide:s=!1}={}){return n6r(a),hCt(a)||gCt(a)||s&&mCt(a)?2:1}t(yCt,"eastAsianWidth");var SCt=ap(bCt(),1);var i6r=new Intl.Segmenter,s6r=/^\p{Default_Ignorable_Code_Point}$/u;function Ode(a,s={}){if(typeof a!="string"||a.length===0)return 0;let{ambiguousIsNarrow:l=!0,countAnsiEscapeCodes:_=!1}=s;if(_||(a=oLe(a)),a.length===0)return 0;let h=0,b={ambiguousAsWide:!l};for(let{segment:D}of i6r.segment(a)){let N=D.codePointAt(0);if(!(N<=31||N>=127&&N<=159)&&!(N>=8203&&N<=8207||N===65279)&&!(N>=768&&N<=879||N>=6832&&N<=6911||N>=7616&&N<=7679||N>=8400&&N<=8447||N>=65056&&N<=65071)&&!(N>=55296&&N<=57343)&&!(N>=65024&&N<=65039)&&!s6r.test(D)){if((0,SCt.default)().test(D)){h+=2;continue}h+=yCt(N,b)}}return h}t(Ode,"stringWidth");var uLe=ap(xCt(),1);var{platform:CCt,cwd:a6r}=process,{red:tU,yellow:ECt,green:Rde,cyan:jY,dim:cLe}=Jf,DCt=process.stdout.columns,u6r=CCt==="win32"&&!process.env.WT_SESSION?">":"\u276F",f6r=(CCt==="win32"&&!process.env.WT_SESSION,"\u2043"),_6r=a6r();function kCt(a){return a=a.replace("async file:","file:"),o6r(_6r,a.startsWith("file:")?c6r(a):a)}t(kCt,"getRelativePath");function p6r(a){return a.find(s=>s.isApp)||null}t(p6r,"mainFrame");function d6r(a,s){return a.filter(l=>(l.isApp||l.isModule)&&(!s||l.file!==s.file||l.line!==s.line))}t(d6r,"filterNativeFrames");function wCt(a){return a.callee||"anonymous"}t(wCt,"frameMethod");function PCt(a,s){let l="",_=a.length-s.length;for(let h=0;h<=_;h++)l+=" ";return l}t(PCt,"whiteSpace");function lLe(a,s,l,_,h){let b=PCt(String(l),String(s));return _?`${h}${tU(u6r)}${b}${tU(s)}${tU("|")}${b} ${tU(a)}`:`${h} ${b}${cLe(s)}${cLe("|")}${b} ${cLe(a)}`}t(lLe,"codeLine");function m6r(a,s,l){let _,h=(0,uLe.default)(Ode(s)+2,DCt);return l?_=`${s} ${tU(h(`${a.message}`).trim())}`:_=`${s} ${tU(h(`${a.name}: ${a.message}`).trim())}`,[_,s]}t(m6r,"getMessage");function h6r(a,s){let l=a.help;if(!l)return[];let _=(0,uLe.default)(Ode(s)+4,DCt);return Array.isArray(l)?l.map(h=>`${s} ${jY(_(`- ${h}`).trim())}`).concat([s]):[`${s} ${jY(l)}`,s]}t(h6r,"getHelpText");function g6r(a,s,l){if(!a)return[];let _=l?kCt(a.filePath):a.filePath;return[`${s} at ${ECt(`${wCt(a)}`)} ${Rde(_)}:${Rde(a.line)}`]}t(g6r,"getMainFrameLocation");function y6r(a,s){if(!a||!a.context||!a.context.line)return[];let l=a.context.start-1,_=a.context.pre.split(`
package/index.minified.js CHANGED
@@ -579,7 +579,7 @@ globstar while`,s,Q,l,Re,Ne),this.matchOne(s.slice(Q),l.slice(Re),_))return this
579
579
  `),stderr:b.join(`
580
580
  `),exitCode:D},"Tar process logs")}}t(Jar,"tarFolder");async function qar({tarFilePath:a,outputDir:s,logger:l}){let _=[],h=[],b;try{await new Promise((D,N)=>{let M=eft("sh",["-c",`tar -xvf ${a} -C ${s};`]);M.stdout.on("data",z=>{let re=z.toString().trim();re.length>0&&_.push(re.trim())}),M.stderr.on("data",z=>{let re=z.toString().trim();re.length>0&&h.push(re.trim())}),M.on("close",z=>{b=z,z===0?D():N(new Error(`tar process exited with code ${z}`))}),M.on("error",z=>{N(z)})})}catch(D){throw new Error("Failed to untar file",{cause:D})}finally{l.info({stdout:_.join(`
581
581
  `),stderr:h.join(`
582
- `),exitCode:b},"Untar process logs")}}t(qar,"untarFile");async function Var(a){if(await Y3e(a))return await $3.rm(a,{recursive:!0})}t(Var,"deleteFolder");var ou=X3e;var IT=x_(K3e(),1);var lO=class extends Error{static{t(this,"CustomResolveError")}},z3=class{static{t(this,"RefParser")}sourceDirectory;logger;constructor(s,l){this.sourceDirectory=s,this.logger=l}dereference(s,l){return SG.$RefParser.dereference(s,{resolve:{json:!0,file:_ue(this.sourceDirectory,this.logger),external:!0,http:!1},dereference:{circular:"ignore",onDereference:l?.onDereference}})}bundle(s){return SG.$RefParser.bundle(s,{resolve:{file:_ue(this.sourceDirectory,this.logger),external:!0,http:!1}})}parse(s){return SG.$RefParser.parse(s,{resolve:{file:_ue(this.sourceDirectory,this.logger),external:!0,http:!1}})}resolve(s){return SG.$RefParser.resolve(s,{resolve:{file:_ue(this.sourceDirectory,this.logger),external:!0,http:!1}})}};function _ue(a,s){return{order:100,canRead(l){let _=Kar(l.url);if(!(_===void 0||_==="file"))return!1;let b;try{b=ift(l.url)}catch(D){throw new lO(`Malformed URI: ${l.url}`,{cause:D})}try{ou.safePath(a).resolve(b)}catch(D){return s?.warn(D),!1}return!0},async read(l){let _;try{_=ift(l.url)}catch(h){throw new lO(`Malformed URI: ${l.url}`,{cause:h})}try{return await War(_)}catch(h){throw new lO(`Error opening file "${_}"`,{cause:h})}}}}t(_ue,"customResolver");var ij=/^win/.test(globalThis.process?globalThis.process.platform:""),Har=/\//g,Gar=/^(\w{2,}):\/\//i,Q3e=[/%23/g,"#",/%24/g,"$",/%26/g,"&",/%2C/g,",",/%40/g,"@"];function Kar(a){let s=Gar.exec(a);if(s)return s[1].toLowerCase()}t(Kar,"getProtocol");function ift(a,s){a=decodeURI(a);for(let _=0;_<Q3e.length;_+=2)a=a.replace(Q3e[_],Q3e[_+1]);let l=a.substr(0,7).toLowerCase()==="file://";if(l&&(a=a[7]==="/"?a.substr(8):a.substr(7),ij&&a[1]==="/"&&(a=a[0]+":"+a.substr(1)),s?a="file:///"+a:(l=!1,a=ij?a:"/"+a)),!l){let _=a.split(ij?"\\":"/"),h=[];for(let b of _)b===".."?h.length&&h[h.length-1]!==""&&h.pop():(b!==""||h.length===0)&&h.push(b);a=h.join(ij?"\\":"/"),!ij&&h[0]===""&&(a="/"+a.substring(1))}return ij&&!l&&(a=a.replace(Har,"\\"),a.substr(1,2)===":\\"&&(a=a[0].toUpperCase()+a.substr(1))),a}t(ift,"toFileSystemPath");var sft="YOUR_KEY_HERE";async function aft(a){let l=await new z3(a.sourceDirectory,a.logger).bundle(a.openApiDocPath),_=a.openApiDocPath.replace(a.sourceDirectory,"");return Yar({...a,relativeOpenApiPath:_},l)}t(aft,"buildPublicOpenApiFile");async function Yar(a,s){eor({relativeOpenApiPath:a.relativeOpenApiPath},s);let l=s;return l=Qar(l),Xar(l,a.deploymentUrl),l=Zar(l,a),oft(l,"x-zuplo"),l}t(Yar,"buildRawOpenApiFile");function Xar(a,s){s?a.servers=[{url:s}]:a.servers=[]}t(Xar,"addServerHost");function Qar(a){if(!a.paths)return a;let{components:s}=a,l=s?{...s}:void 0,_=[];l&&l.parameters&&(_=Object.entries(l.parameters).reduce((b,[D,N])=>(AM in N&&ile(N[AM])&&(b.push(D),l.parameters&&delete l.parameters[D]),b),[]));let h=Object.entries(a.paths).reduce((b,[D,N])=>{if(!N)return b;let M={...N},z=["delete","get","head","patch","post","put","trace","options"];return z.forEach(re=>{let ie=N[re];if(!ie)return;if(ile(ie[AM])){delete M[re];return}let{parameters:Q}=ie;if(!Q)return;let Re=Q.filter(Ne=>{if(AM in Ne&&ile(Ne[AM]))return!1;if("$ref"in Ne){let we=Ne.$ref.split("/").pop();return we?!_.includes(we):!0}return!0});M[re]={...ie,parameters:Re}}),z.some(re=>!!M[re])&&(b[D]=M),b},{});return{...a,paths:h,components:l}}t(Qar,"removeHiddenRoutesAndParams");function Zar(a,{policiesConfig:s}){if(!a.paths)return a;let l=Object.entries(a.paths).reduce((_,[h,b])=>{if(!b)return _;let D={...b};return[D.delete,D.get,D.head,D.patch,D.post,D.put,D.trace,D.options].forEach(N=>{if(!N)return;let M=N["x-zuplo-route"]?.policies?.inbound?.reduce((ie,Q)=>{let Re=s.policies?.find(({name:wt})=>wt===Q);if(!Re)return ie;if(!(Re.handler.export==="CompositeInboundPolicy"))return ie.concat(Q);let we=Re.handler.options?.policies;return we?ie.concat(we):ie},[]),z=[];if(M&&M.forEach(ie=>{s.policies?.forEach(Q=>{Q.name===ie&&(Q.handler.export==="ApiAuthKeyInboundPolicy"||Q.handler.export==="ApiKeyInboundPolicy")&&!Q.handler.options?.disableAutomaticallyAddingKeyHeaderToOpenApi&&z.push(Q)})}),z.length>0){let ie=z.length>0&&z[0].handler&&z[0].handler.options&&z[0].handler.options.authHeader?z[0].handler.options.authHeader:"Authorization",Q=z.length>0&&z[0].handler&&z[0].handler.options&&(z[0].handler.options.authScheme||z[0].handler.options.authScheme==="")?z[0].handler.options.authScheme:"Bearer",Re=Q!==""?`${Q} ${sft}`:sft,Ne={name:ie,in:"header",required:!0,example:Re,schema:{type:"string"},description:`The \`${ie}\` header is used to authenticate with the API using your API key. Value is of the format \`${Re}\`.`};N.parameters?N.parameters.some(Tr=>"name"in Tr&&Tr.name===Ne.name)||N.parameters.unshift(Ne):N.parameters=[Ne];let we={type:"http",scheme:Q.toLowerCase()},wt="api_key";a.components?.securitySchemes?Object.values(a.components?.securitySchemes).some(Tr=>"name"in Tr&&Tr.type==="apiKey"||"type"in Tr&&Tr.type==="http"&&Tr.scheme===Q)||(a.components.securitySchemes={...a.components.securitySchemes,[wt]:we}):(a.components||(a.components={}),a.components.securitySchemes={[wt]:we});let xt={[wt]:[]};N.security?N.security.some(Tr=>Tr[wt]!==void 0)||N.security.unshift(xt):N.security=[xt]}let re=[];if(M&&M.forEach(ie=>{s.policies?.forEach(Q=>{Q.name===ie&&(Q.handler.export==="RateLimitInboundPolicy"||Q.handler.export==="ComplexRateLimitInboundPolicy")&&re.push(Q)})}),re.length>0){let ie={description:"Rate Limiting Response",content:{"application/json":{schema:{type:"object",required:["type","title","status"],examples:[{type:"https://httpproblems.com/http-status/429",title:"Too Many Requests",status:429,instance:"/foo/bar"}],properties:{type:{type:"string",example:"https://httpproblems.com/http-status/429",description:"A URI reference that identifies the problem."},title:{type:"string",example:"Too Many Requests",description:"A short, human-readable summary of the problem."},status:{type:"number",example:429,description:"The HTTP status code."},instance:{type:"string",example:"/foo/bar"}}}}}},Q={...ie,headers:{"retry-after":{description:"The number of seconds to wait before making a new request.",schema:{type:"integer",example:60}}}};a.components?.responses||a.components||(a.components={}),a.components.responses={...a.components.responses,RateLimitNoRetryAfter:ie,RateLimitWithRetryAfter:Q},N.responses||(N.responses={});let Re=re.some(Ne=>Ne.handler.options?.headerMode!=="none");N.responses[429]||(N.responses[429]={$ref:Re?"#/components/responses/RateLimitWithRetryAfter":"#/components/responses/RateLimitNoRetryAfter"})}}),_[h]=D,_},{});return{...a,paths:l}}t(Zar,"enrichSpecWithZuploData");function oft(a,s){for(let l in a)l.startsWith(s)?delete a[l]:typeof a[l]=="object"&&oft(a[l],s)}t(oft,"removePropertiesByPrefix");function eor({relativeOpenApiPath:a},s){if(!s||typeof s!="object")throw new J1({message:"The OpenAPI Document could not be parsed.",severity:"error"});if(!("info"in s)||typeof s.info!="object"||!s.info)throw new J1({message:"The OpenAPI document does not have the required 'info' property.",location:{file:a,column:0,length:0,line:0,lineText:"",namespace:"",suggestion:"Add the required 'info' property. https://spec.openapis.org/oas/v3.1.0#info-object"},severity:"error"});if(!("title"in s.info)||typeof s.info.title!="string")throw new J1({message:"The OpenAPI document does not have the required 'info.title' property.",location:{file:a,column:0,length:0,line:0,lineText:"",namespace:"",suggestion:"Add the required 'info.title' property. https://spec.openapis.org/oas/v3.1.0#info-object"},severity:"error"})}t(eor,"assertIsZuploOpenApiSpec");import EK from"node:path";function tor(a){if(a.length>=255)throw new TypeError("Alphabet too long");let s=new Uint8Array(256);for(let z=0;z<s.length;z++)s[z]=255;for(let z=0;z<a.length;z++){let re=a.charAt(z),ie=re.charCodeAt(0);if(s[ie]!==255)throw new TypeError(re+" is ambiguous");s[ie]=z}let l=a.length,_=a.charAt(0),h=Math.log(l)/Math.log(256),b=Math.log(256)/Math.log(l);function D(z){if(z instanceof Uint8Array||(ArrayBuffer.isView(z)?z=new Uint8Array(z.buffer,z.byteOffset,z.byteLength):Array.isArray(z)&&(z=Uint8Array.from(z))),!(z instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(z.length===0)return"";let re=0,ie=0,Q=0,Re=z.length;for(;Q!==Re&&z[Q]===0;)Q++,re++;let Ne=(Re-Q)*b+1>>>0,we=new Uint8Array(Ne);for(;Q!==Re;){let Tr=z[Q],fn=0;for(let tn=Ne-1;(Tr!==0||fn<ie)&&tn!==-1;tn--,fn++)Tr+=256*we[tn]>>>0,we[tn]=Tr%l>>>0,Tr=Tr/l>>>0;if(Tr!==0)throw new Error("Non-zero carry");ie=fn,Q++}let wt=Ne-ie;for(;wt!==Ne&&we[wt]===0;)wt++;let xt=_.repeat(re);for(;wt<Ne;++wt)xt+=a.charAt(we[wt]);return xt}t(D,"encode");function N(z){if(typeof z!="string")throw new TypeError("Expected String");if(z.length===0)return new Uint8Array;let re=0,ie=0,Q=0;for(;z[re]===_;)ie++,re++;let Re=(z.length-re)*h+1>>>0,Ne=new Uint8Array(Re);for(;z[re];){let Tr=s[z.charCodeAt(re)];if(Tr===255)return;let fn=0;for(let tn=Re-1;(Tr!==0||fn<Q)&&tn!==-1;tn--,fn++)Tr+=l*Ne[tn]>>>0,Ne[tn]=Tr%256>>>0,Tr=Tr/256>>>0;if(Tr!==0)throw new Error("Non-zero carry");Q=fn,re++}let we=Re-Q;for(;we!==Re&&Ne[we]===0;)we++;let wt=new Uint8Array(ie+(Re-we)),xt=ie;for(;we!==Re;)wt[xt++]=Ne[we++];return wt}t(N,"decodeUnsafe");function M(z){let re=N(z);if(re)return re;throw new Error("Non-base"+l+" character")}return t(M,"decode"),{encode:D,decodeUnsafe:N,decode:M}}t(tor,"base");var cft=tor;var ror="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",pue=cft(ror);var nor=!1;function sj(a,s){return{open:`\x1B[${a.join(";")}m`,close:`\x1B[${s}m`,regexp:new RegExp(`\\x1b\\[${s}m`,"g")}}t(sj,"code");function aj(a,s){return nor?`${s.open}${a.replace(s.regexp,s.open)}${s.close}`:a}t(aj,"run");function ior(a){return aj(a,sj([31],39))}t(ior,"red");function sor(a){return aj(a,sj([32],39))}t(sor,"green");function aor(a){return aj(a,sj([33],39))}t(aor,"yellow");function oor(a){return aj(a,sj([34],39))}t(oor,"blue");function cor(a){return aj(a,sj([35],39))}t(cor,"magenta");function lor(a){return aj(a,sj([36],39))}t(lor,"cyan");var gFr=new RegExp(["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|"),"g");var lft=[ior,sor,aor,oor,cor,lor];function uor(a){let s=0,l=a.length,_=0;if(l>0)for(;_<l;)s=(s<<5)-s+a.charCodeAt(_++)|0;return s}t(uor,"hashCode");function uft(a){let s=Math.abs(uor(a));return lft[s%lft.length]}t(uft,"generateColor");import{inspect as _or}from"node:util";function fft(a,s,...l){let _=0,h=l.length,b=String(s).replace(/%[sdjoO%]/g,D=>{if(D==="%%")return"%";if(_>=h)return D;switch(D){case"%s":return String(l[_++]);case"%d":return Number(l[_++]).toString();case"%o":return a(l[_++]).split(`
582
+ `),exitCode:b},"Untar process logs")}}t(qar,"untarFile");async function Var(a){if(await Y3e(a))return await $3.rm(a,{recursive:!0})}t(Var,"deleteFolder");var ou=X3e;var IT=x_(K3e(),1);var lO=class extends Error{static{t(this,"CustomResolveError")}},z3=class{static{t(this,"RefParser")}sourceDirectory;logger;constructor(s,l){this.sourceDirectory=s,this.logger=l}dereference(s,l){return SG.$RefParser.dereference(s,{resolve:{json:!0,file:_ue(this.sourceDirectory,this.logger),external:!0,http:!1},dereference:{circular:"ignore",onDereference:l?.onDereference}})}bundle(s){return SG.$RefParser.bundle(s,{resolve:{file:_ue(this.sourceDirectory,this.logger),external:!0,http:!1}})}parse(s){return SG.$RefParser.parse(s,{resolve:{file:_ue(this.sourceDirectory,this.logger),external:!0,http:!1}})}resolve(s){return SG.$RefParser.resolve(s,{resolve:{file:_ue(this.sourceDirectory,this.logger),external:!0,http:!1}})}};function _ue(a,s){return{order:100,canRead(l){let _=Kar(l.url);if(!(_===void 0||_==="file"))return!1;let b;try{b=ift(l.url)}catch(D){throw new lO(`Malformed URI: ${l.url}`,{cause:D})}try{ou.safePath(a).resolve(b)}catch(D){return s?.warn(D),!1}return!0},async read(l){let _;try{_=ift(l.url)}catch(h){throw new lO(`Malformed URI: ${l.url}`,{cause:h})}try{return await War(_)}catch(h){throw new lO(`Error opening file "${_}"`,{cause:h})}}}}t(_ue,"customResolver");var ij=/^win/.test(globalThis.process?globalThis.process.platform:""),Har=/\//g,Gar=/^(\w{2,}):\/\//i,Q3e=[/%23/g,"#",/%24/g,"$",/%26/g,"&",/%2C/g,",",/%40/g,"@"];function Kar(a){let s=Gar.exec(a);if(s)return s[1].toLowerCase()}t(Kar,"getProtocol");function ift(a,s){a=decodeURI(a);for(let _=0;_<Q3e.length;_+=2)a=a.replace(Q3e[_],Q3e[_+1]);let l=a.substr(0,7).toLowerCase()==="file://";if(l&&(a=a[7]==="/"?a.substr(8):a.substr(7),ij&&a[1]==="/"&&(a=a[0]+":"+a.substr(1)),s?a="file:///"+a:(l=!1,a=ij?a:"/"+a)),!l){let _=a.split(ij?"\\":"/"),h=[];for(let b of _)b===".."?h.length&&h[h.length-1]!==""&&h.pop():(b!==""||h.length===0)&&h.push(b);a=h.join(ij?"\\":"/"),!ij&&h[0]===""&&(a="/"+a.substring(1))}return ij&&!l&&(a=a.replace(Har,"\\"),a.substr(1,2)===":\\"&&(a=a[0].toUpperCase()+a.substr(1))),a}t(ift,"toFileSystemPath");var sft="YOUR_KEY_HERE";async function aft(a){let l=await new z3(a.sourceDirectory,a.logger).bundle(a.openApiDocPath),_=a.openApiDocPath.replace(a.sourceDirectory,"");return Yar({...a,relativeOpenApiPath:_},l)}t(aft,"buildPublicOpenApiFile");async function Yar(a,s){eor({relativeOpenApiPath:a.relativeOpenApiPath},s);let l=s;return l=Qar(l),Xar(l,a.urls?.api?.defaultUrl),l=Zar(l,a),oft(l,"x-zuplo"),l}t(Yar,"buildRawOpenApiFile");function Xar(a,s){s?a.servers=[{url:s}]:a.servers=[]}t(Xar,"addServerHost");function Qar(a){if(!a.paths)return a;let{components:s}=a,l=s?{...s}:void 0,_=[];l&&l.parameters&&(_=Object.entries(l.parameters).reduce((b,[D,N])=>(AM in N&&ile(N[AM])&&(b.push(D),l.parameters&&delete l.parameters[D]),b),[]));let h=Object.entries(a.paths).reduce((b,[D,N])=>{if(!N)return b;let M={...N},z=["delete","get","head","patch","post","put","trace","options"];return z.forEach(re=>{let ie=N[re];if(!ie)return;if(ile(ie[AM])){delete M[re];return}let{parameters:Q}=ie;if(!Q)return;let Re=Q.filter(Ne=>{if(AM in Ne&&ile(Ne[AM]))return!1;if("$ref"in Ne){let we=Ne.$ref.split("/").pop();return we?!_.includes(we):!0}return!0});M[re]={...ie,parameters:Re}}),z.some(re=>!!M[re])&&(b[D]=M),b},{});return{...a,paths:h,components:l}}t(Qar,"removeHiddenRoutesAndParams");function Zar(a,{policiesConfig:s}){if(!a.paths)return a;let l=Object.entries(a.paths).reduce((_,[h,b])=>{if(!b)return _;let D={...b};return[D.delete,D.get,D.head,D.patch,D.post,D.put,D.trace,D.options].forEach(N=>{if(!N)return;let M=N["x-zuplo-route"]?.policies?.inbound?.reduce((ie,Q)=>{let Re=s.policies?.find(({name:wt})=>wt===Q);if(!Re)return ie;if(!(Re.handler.export==="CompositeInboundPolicy"))return ie.concat(Q);let we=Re.handler.options?.policies;return we?ie.concat(we):ie},[]),z=[];if(M&&M.forEach(ie=>{s.policies?.forEach(Q=>{Q.name===ie&&(Q.handler.export==="ApiAuthKeyInboundPolicy"||Q.handler.export==="ApiKeyInboundPolicy")&&!Q.handler.options?.disableAutomaticallyAddingKeyHeaderToOpenApi&&z.push(Q)})}),z.length>0){let ie=z.length>0&&z[0].handler&&z[0].handler.options&&z[0].handler.options.authHeader?z[0].handler.options.authHeader:"Authorization",Q=z.length>0&&z[0].handler&&z[0].handler.options&&(z[0].handler.options.authScheme||z[0].handler.options.authScheme==="")?z[0].handler.options.authScheme:"Bearer",Re=Q!==""?`${Q} ${sft}`:sft,Ne={name:ie,in:"header",required:!0,example:Re,schema:{type:"string"},description:`The \`${ie}\` header is used to authenticate with the API using your API key. Value is of the format \`${Re}\`.`};N.parameters?N.parameters.some(Tr=>"name"in Tr&&Tr.name===Ne.name)||N.parameters.unshift(Ne):N.parameters=[Ne];let we={type:"http",scheme:Q.toLowerCase()},wt="api_key";a.components?.securitySchemes?Object.values(a.components?.securitySchemes).some(Tr=>"name"in Tr&&Tr.type==="apiKey"||"type"in Tr&&Tr.type==="http"&&Tr.scheme===Q)||(a.components.securitySchemes={...a.components.securitySchemes,[wt]:we}):(a.components||(a.components={}),a.components.securitySchemes={[wt]:we});let xt={[wt]:[]};N.security?N.security.some(Tr=>Tr[wt]!==void 0)||N.security.unshift(xt):N.security=[xt]}let re=[];if(M&&M.forEach(ie=>{s.policies?.forEach(Q=>{Q.name===ie&&(Q.handler.export==="RateLimitInboundPolicy"||Q.handler.export==="ComplexRateLimitInboundPolicy")&&re.push(Q)})}),re.length>0){let ie={description:"Rate Limiting Response",content:{"application/json":{schema:{type:"object",required:["type","title","status"],examples:[{type:"https://httpproblems.com/http-status/429",title:"Too Many Requests",status:429,instance:"/foo/bar"}],properties:{type:{type:"string",example:"https://httpproblems.com/http-status/429",description:"A URI reference that identifies the problem."},title:{type:"string",example:"Too Many Requests",description:"A short, human-readable summary of the problem."},status:{type:"number",example:429,description:"The HTTP status code."},instance:{type:"string",example:"/foo/bar"}}}}}},Q={...ie,headers:{"retry-after":{description:"The number of seconds to wait before making a new request.",schema:{type:"integer",example:60}}}};a.components?.responses||a.components||(a.components={}),a.components.responses={...a.components.responses,RateLimitNoRetryAfter:ie,RateLimitWithRetryAfter:Q},N.responses||(N.responses={});let Re=re.some(Ne=>Ne.handler.options?.headerMode!=="none");N.responses[429]||(N.responses[429]={$ref:Re?"#/components/responses/RateLimitWithRetryAfter":"#/components/responses/RateLimitNoRetryAfter"})}}),_[h]=D,_},{});return{...a,paths:l}}t(Zar,"enrichSpecWithZuploData");function oft(a,s){for(let l in a)l.startsWith(s)?delete a[l]:typeof a[l]=="object"&&oft(a[l],s)}t(oft,"removePropertiesByPrefix");function eor({relativeOpenApiPath:a},s){if(!s||typeof s!="object")throw new J1({message:"The OpenAPI Document could not be parsed.",severity:"error"});if(!("info"in s)||typeof s.info!="object"||!s.info)throw new J1({message:"The OpenAPI document does not have the required 'info' property.",location:{file:a,column:0,length:0,line:0,lineText:"",namespace:"",suggestion:"Add the required 'info' property. https://spec.openapis.org/oas/v3.1.0#info-object"},severity:"error"});if(!("title"in s.info)||typeof s.info.title!="string")throw new J1({message:"The OpenAPI document does not have the required 'info.title' property.",location:{file:a,column:0,length:0,line:0,lineText:"",namespace:"",suggestion:"Add the required 'info.title' property. https://spec.openapis.org/oas/v3.1.0#info-object"},severity:"error"})}t(eor,"assertIsZuploOpenApiSpec");import EK from"node:path";function tor(a){if(a.length>=255)throw new TypeError("Alphabet too long");let s=new Uint8Array(256);for(let z=0;z<s.length;z++)s[z]=255;for(let z=0;z<a.length;z++){let re=a.charAt(z),ie=re.charCodeAt(0);if(s[ie]!==255)throw new TypeError(re+" is ambiguous");s[ie]=z}let l=a.length,_=a.charAt(0),h=Math.log(l)/Math.log(256),b=Math.log(256)/Math.log(l);function D(z){if(z instanceof Uint8Array||(ArrayBuffer.isView(z)?z=new Uint8Array(z.buffer,z.byteOffset,z.byteLength):Array.isArray(z)&&(z=Uint8Array.from(z))),!(z instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(z.length===0)return"";let re=0,ie=0,Q=0,Re=z.length;for(;Q!==Re&&z[Q]===0;)Q++,re++;let Ne=(Re-Q)*b+1>>>0,we=new Uint8Array(Ne);for(;Q!==Re;){let Tr=z[Q],fn=0;for(let tn=Ne-1;(Tr!==0||fn<ie)&&tn!==-1;tn--,fn++)Tr+=256*we[tn]>>>0,we[tn]=Tr%l>>>0,Tr=Tr/l>>>0;if(Tr!==0)throw new Error("Non-zero carry");ie=fn,Q++}let wt=Ne-ie;for(;wt!==Ne&&we[wt]===0;)wt++;let xt=_.repeat(re);for(;wt<Ne;++wt)xt+=a.charAt(we[wt]);return xt}t(D,"encode");function N(z){if(typeof z!="string")throw new TypeError("Expected String");if(z.length===0)return new Uint8Array;let re=0,ie=0,Q=0;for(;z[re]===_;)ie++,re++;let Re=(z.length-re)*h+1>>>0,Ne=new Uint8Array(Re);for(;z[re];){let Tr=s[z.charCodeAt(re)];if(Tr===255)return;let fn=0;for(let tn=Re-1;(Tr!==0||fn<Q)&&tn!==-1;tn--,fn++)Tr+=l*Ne[tn]>>>0,Ne[tn]=Tr%256>>>0,Tr=Tr/256>>>0;if(Tr!==0)throw new Error("Non-zero carry");Q=fn,re++}let we=Re-Q;for(;we!==Re&&Ne[we]===0;)we++;let wt=new Uint8Array(ie+(Re-we)),xt=ie;for(;we!==Re;)wt[xt++]=Ne[we++];return wt}t(N,"decodeUnsafe");function M(z){let re=N(z);if(re)return re;throw new Error("Non-base"+l+" character")}return t(M,"decode"),{encode:D,decodeUnsafe:N,decode:M}}t(tor,"base");var cft=tor;var ror="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",pue=cft(ror);var nor=!1;function sj(a,s){return{open:`\x1B[${a.join(";")}m`,close:`\x1B[${s}m`,regexp:new RegExp(`\\x1b\\[${s}m`,"g")}}t(sj,"code");function aj(a,s){return nor?`${s.open}${a.replace(s.regexp,s.open)}${s.close}`:a}t(aj,"run");function ior(a){return aj(a,sj([31],39))}t(ior,"red");function sor(a){return aj(a,sj([32],39))}t(sor,"green");function aor(a){return aj(a,sj([33],39))}t(aor,"yellow");function oor(a){return aj(a,sj([34],39))}t(oor,"blue");function cor(a){return aj(a,sj([35],39))}t(cor,"magenta");function lor(a){return aj(a,sj([36],39))}t(lor,"cyan");var gFr=new RegExp(["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|"),"g");var lft=[ior,sor,aor,oor,cor,lor];function uor(a){let s=0,l=a.length,_=0;if(l>0)for(;_<l;)s=(s<<5)-s+a.charCodeAt(_++)|0;return s}t(uor,"hashCode");function uft(a){let s=Math.abs(uor(a));return lft[s%lft.length]}t(uft,"generateColor");import{inspect as _or}from"node:util";function fft(a,s,...l){let _=0,h=l.length,b=String(s).replace(/%[sdjoO%]/g,D=>{if(D==="%%")return"%";if(_>=h)return D;switch(D){case"%s":return String(l[_++]);case"%d":return Number(l[_++]).toString();case"%o":return a(l[_++]).split(`
583
583
  `).map(N=>N.trim()).join(" ");case"%O":return a(l[_++]);case"%j":try{return JSON.stringify(l[_++])}catch{return"[Circular]"}default:return D}});for(let D of l.splice(_))D===null||!(typeof D=="object"&&D!==null)?b+=" "+D:b+=" "+a(D);return b}t(fft,"format");var _ft=t((a,...s)=>fft(_or,a,s),"format");var Z3e=class{static{t(this,"Debugger")}manager;ns;color;last;enabled;constructor(s,l){this.manager=s,this.ns=l,this.color=uft(l),this.last=0,this.enabled=s.enabled.some(_=>_.test(l))}log(...s){if(!this.enabled)return;let l,_=s[0];typeof _=="function"?l=_():l=String(_);let h=Date.now()-(this.last||Date.now());l=_ft(l,...s);let b=`${this.color(this.ns)} ${l} ${this.color(`+${h}ms`)}`;console.log(b),this.last=Date.now()}},eNe=class{static{t(this,"DebugManager")}debuggers;enabled;constructor(s){this.debuggers=new Map,this.enabled=s??[]}};function por(a){return!a||a.length===0?[]:(a=a.replace(/\s/g,"").replace(/\*/g,".+"),a.split(",").map(s=>new RegExp(`^${s}$`)))}t(por,"extract");var due;function mue(a){due||(due=new eNe(por(process.env.DEBUG)));let s=new Z3e(due,a);return due.debuggers.set(a,s),Object.assign(s.log.bind(s),{self:s})}t(mue,"debug");var J3=class extends Error{static{t(this,"RuntimeError")}extensionMembers;constructor(s,l){typeof s=="string"?super(s,l):(super(s.message,l),this.extensionMembers=s.extensionMembers),this.name="RuntimeError"}};var uO=mue("zuplo:runtime:external-service");function dor(){let a,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:s}=F0.instance.runtime;if(s&&s!=="undefined")try{let l=atob(s);a=JSON.parse(l)}catch{}return a}t(dor,"getServiceAuth");async function pft(a,s){let l=dor();if(l)if(uO(`Using external service auth. ClientId: ${l.clientId})`),typeof a=="string"){let _=new URL(a),h=_.hostname,b=s??{},D=new Headers(b.headers||{});D.set("CF-Access-Client-Id",l.clientId),D.set("CF-Access-Client-Secret",l.clientSecret),b.headers=D;let N;if(l.customServiceMapping&&l.customServiceMapping[h])N=`https://${l.customServiceMapping[h]}`;else if(F0.instance.useLegacyServiceRouting)N=`https://${h}.zuptunnel.com`;else{uO("Using sha256 service routing");let re=F0.instance.build;if(re.ACCOUNT_NAME&&re.PROJECT_NAME&&re.ENVIRONMENT_TYPE){let ie=await mor(h,re.ACCOUNT_NAME,re.PROJECT_NAME,re.ENVIRONMENT_TYPE),Q=mft(re.ENVIRONMENT_TYPE),Re=await tNe(`${re.ACCOUNT_NAME}-${re.PROJECT_NAME}-${Q}`);Re==="40d7ad502f5d743997999594c177184a00161a77865423511f3a1ea21eb5a5e"||Re==="d05bffe8fa91a300187d2cf43e8aa4a56bd809c442ae10d1ee49af7d29a5a11"?N=`https://${ie}.zuptunnel.com`:N=`https://${ie}.t.zuplo.app`}else throw uO("Cannot use sha256 service routing, missing build variables"),new J3("Failed to generate fully qualified tunnel url.")}let M=new URL(`${N}${_.pathname}${_.search}`);uO(`Calling external service: ${M.toString()}`);let z=await TG(M.toString(),b);if(z.status===403&&z.headers.get("cf-access-domain")!==null)throw xG.console.error("403 Forbidden when calling external service.",{clientId:l.clientId,tunnelHost:N}),new J3("Could not connect to secure tunnel.");return z}else throw uO("Cannot call external service with Request object"),new J3("Currently, we only support fetch(<some_string>, ...).");else throw uO("There is no external service auth configured for this zup."),new J3("There are no external services configured for this zup.")}t(pft,"externalServiceHandler");async function dft(a,s){if(typeof a=="string"){let l=new URL(a),h=`http://${l.hostname}.zuplo.svc.cluster.local:9000`,b=new URL(`${h}${l.pathname}${l.search}`);return await TG(b.toString(),s)}else throw new J3("Currently, we only support fetch(<some_string>, ...).")}t(dft,"clusterServiceHandler");async function mor(a,s,l,_){let h=a.toLowerCase(),b=s.toLowerCase(),D=l.toLowerCase(),N=mft(_);uO(`Hashing service name: ${b}-${h}.${b}-${D}-${N}`);let M=await tNe(`${b}-${h}`),z=await tNe(`${b}-${D}-${N}`);return`${M}.${z}`}t(mor,"hashServiceName");async function tNe(a){let s=new TextEncoder().encode(a),l=await crypto.subtle.digest("SHA-256",s);return Array.from(new Uint8Array(l)).map(b=>b.toString(16).padStart(2,"0")).join("").slice(0,-1)}t(tNe,"hashSegment");function mft(a){let s=a.toLowerCase();switch(s){case"production":case"preview":return s;default:return"working-copy"}}t(mft,"sanitizeEnvironmentType");var rNe=new Map;rNe.set("service:",pft);rNe.set("local:",dft);var TG=globalThis.fetch;function nNe(a,s){let l=hor(s);if(typeof a=="string"){let _=new URL(a),h=rNe.get(_.protocol);return h?h(a,l):TG(a,l)}else return TG(a,l)}t(nNe,"internalFetch");globalThis.fetch=nNe;var hor=t(a=>{if(!a||a instanceof Request)return a;let s=a;if(!s.zuplo)return a;let l=a;return l.cf={cacheEverything:s.zuplo?.cacheEverything,cacheTtl:s.zuplo?.cacheTtlSeconds},delete a.zuplo,a},"transformInit");var gor={console:{log:console.log.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console),debug:console.debug.bind(console),assert:console.assert.bind(console),clear:console.clear.bind(console),count:console.count.bind(console),countReset:console.countReset.bind(console),dir:console.dir.bind(console),dirxml:console.dirxml.bind(console),group:console.group.bind(console),groupCollapsed:console.groupCollapsed.bind(console),groupEnd:console.groupEnd.bind(console),table:console.table.bind(console),time:console.time.bind(console),timeEnd:console.timeEnd.bind(console),timeLog:console.timeLog.bind(console),timeStamp:console.timeStamp.bind(console),trace:console.trace.bind(console),profile:console.profile.bind(console),profileEnd:console.profileEnd.bind(console)},fetch:nNe},xG=gor;var iNe="2025-02-06",hft=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1,allowCustomPorts:!1,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1,allowCustomPorts:!1,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!1,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!1,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2024-09-02":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!0,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2025-02-06":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!0,removeLegacyLogInitialization:!0,useForwardRedirectsPropOnUrlForwardHandler:!0}});function gft(){return new F0({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:iNe,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,IS_LOCAL_DEVELOPMENT:!1,COMPATIBILITY_FLAGS:hft[iNe]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}t(gft,"getMockEnvironment");var F0=class a{static{t(this,"Environment")}config;static#r;static#n=!1;static initialize(s){this.#r||(this.#r=new a(s),this.#n=!0)}static get instance(){return this.#n||(xG.console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#r=gft()),this.#r}constructor({build:s,runtime:l}){let _;try{if(l.ZUPLO_SYSTEM_CONFIGURATIONS){let h=new TextDecoder().decode(pue.decode(l.ZUPLO_SYSTEM_CONFIGURATIONS)),b=JSON.parse(h);for(let D of Object.keys(b))l[D]||(l[D]=b[D])}if(l.__ZUPLO_CONFIG){let h=atob(l.__ZUPLO_CONFIG);_=JSON.parse(h)}}catch(h){xG.console.error("Failed to parse runtime configuration",h)}this.config=_??{},this.build=s,this.runtime=l,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get zuploEdgeApiUrl(){return this.config.zuplo_edge_api_url??"https://api.zuploedge.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get zuploClientAuthBucketId(){return this.config.zuplo_auth_client_bucket_id??"auth_o8PUdhKxSTOiB794GWPwLQCD"}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get developerApiUrl(){return this.config.developer_api_url??"https://dev.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuploedge.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuploedge.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuploedge.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuploedge.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get authClientId(){return this.runtime.__ZUPLO_AUTH_CLIENT_ID}get authClientSecret(){return this.runtime.__ZUPLO_AUTH_CLIENT_SECRET}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.IS_LOCAL_DEVELOPMENT}get isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var yor=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function yft(a){return a.startsWith("__ZUPLO")||a.startsWith("ZUPLO_")?!yor.includes(a)&&!a.startsWith("ZUPLO_PUBLIC_"):!1}t(yft,"isRestrictedEnvVariableName");function vft(a){return!!a.startsWith("ZUPLO_")}t(vft,"isZuploReadableEnvVariableName");var rOr=new Proxy({},{get(a,s){let l=String(s);switch(l){case"ZUPLO_ENVIRONMENT_TYPE":return F0.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return F0.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return F0.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return F0.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return F0.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return F0.instance.build.BUILD_ID;case"ZUPLO_COMPATIBILITY_DATE":return F0.instance.build.COMPATIBILITY_DATE}if(!(yft(l)&&!vft(l)))return F0.instance.runtime[l]}});function CG(a,s,l){return`_${wA(`${a}_${s}_${l}`)}`}t(CG,"getRawOperationDataIdentifierName");function sNe(a,s,l,_){return`_${wA(a.toLowerCase())}_${s.toLowerCase()}_${l.toLowerCase()}_${_.toLowerCase()}`}t(sNe,"getIdForParameterSchema");function aNe(a,s,l){return`_${wA(a.toLowerCase())}_${s.toLowerCase()}_rb_${wA(l.toLowerCase())}`}t(aNe,"getIdForRequestBodySchema");function EG(a,s){return`_${wA(a)}_${wA(s)}`}t(EG,"getIdForRefSchema");function wA(a){let s=a.replace(/\[/g,"_LBRACKET_").replace(/\]/g,"_RBRACKET_").replace(/\{/g,"_LCURLY_").replace(/\}/g,"_RCURLY_").replace(/\//g,"_SLASH_").replace(/-/g,"_DASH_").replace(/\./g,"_DOT_").replace(/\+/g,"_PLUS_").replace(/:/g,"_COLON_").replace(/@/g,"_AT_").replace(/\$/g,"_DOLLAR_").replace(/[^a-zA-Z0-9_]/g,"_");return/^[a-zA-Z_]/.test(s)||(s="_"+s),s}t(wA,"sanitizedIdentifierName");var Xht=x_(lpt(),1);var $G=class{static{t(this,"R")}type=3;name="";prefix="";value="";suffix="";modifier=3;constructor(a,s,l,_,h,b){this.type=a,this.name=s,this.prefix=l,this.value=_,this.suffix=h,this.modifier=b}hasCustomName(){return this.name!==""&&typeof this.name!="number"}},uur=/[$_\p{ID_Start}]/u,fur=/[$_\u200C\u200D\p{ID_Continue}]/u,eIe=".*";function _ur(a,s){return(s?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test(a)}t(_ur,"Re");function _pt(a,s=!1){let l=[],_=0;for(;_<a.length;){let h=a[_],b=t(function(D){if(!s)throw new TypeError(D);l.push({type:"INVALID_CHAR",index:_,value:a[_++]})},"c");if(h==="*"){l.push({type:"ASTERISK",index:_,value:a[_++]});continue}if(h==="+"||h==="?"){l.push({type:"OTHER_MODIFIER",index:_,value:a[_++]});continue}if(h==="\\"){l.push({type:"ESCAPED_CHAR",index:_++,value:a[_++]});continue}if(h==="{"){l.push({type:"OPEN",index:_,value:a[_++]});continue}if(h==="}"){l.push({type:"CLOSE",index:_,value:a[_++]});continue}if(h===":"){let D="",N=_+1;for(;N<a.length;){let M=a.substr(N,1);if(N===_+1&&uur.test(M)||N!==_+1&&fur.test(M)){D+=a[N++];continue}break}if(!D){b(`Missing parameter name at ${_}`);continue}l.push({type:"NAME",index:_,value:D}),_=N;continue}if(h==="("){let D=1,N="",M=_+1,z=!1;if(a[M]==="?"){b(`Pattern cannot start with "?" at ${M}`);continue}for(;M<a.length;){if(!_ur(a[M],!1)){b(`Invalid character '${a[M]}' at ${M}.`),z=!0;break}if(a[M]==="\\"){N+=a[M++]+a[M++];continue}if(a[M]===")"){if(D--,D===0){M++;break}}else if(a[M]==="("&&(D++,a[M+1]!=="?")){b(`Capturing groups are not allowed at ${M}`),z=!0;break}N+=a[M++]}if(z)continue;if(D){b(`Unbalanced pattern at ${_}`);continue}if(!N){b(`Missing pattern at ${_}`);continue}l.push({type:"REGEX",index:_,value:N}),_=M;continue}l.push({type:"CHAR",index:_,value:a[_++]})}return l.push({type:"END",index:_,value:""}),l}t(_pt,"v");function ppt(a,s={}){let l=_pt(a);s.delimiter??="/#?",s.prefixes??="./";let _=`[^${RT(s.delimiter)}]+?`,h=[],b=0,D=0,N="",M=new Set,z=t(fn=>{if(D<l.length&&l[D].type===fn)return l[D++].value},"a"),re=t(()=>z("OTHER_MODIFIER")??z("ASTERISK"),"f"),ie=t(fn=>{let tn=z(fn);if(tn!==void 0)return tn;let{type:cn,index:Cr}=l[D];throw new TypeError(`Unexpected ${cn} at ${Cr}, expected ${fn}`)},"d"),Q=t(()=>{let fn="",tn;for(;tn=z("CHAR")??z("ESCAPED_CHAR");)fn+=tn;return fn},"T"),Re=t(fn=>fn,"Se"),Ne=s.encodePart||Re,we="",wt=t(fn=>{we+=fn},"U"),xt=t(()=>{we.length&&(h.push(new $G(3,"","",Ne(we),"",3)),we="")},"$"),Tr=t((fn,tn,cn,Cr,vr)=>{let fs=3;switch(vr){case"?":fs=1;break;case"*":fs=0;break;case"+":fs=2;break}if(!tn&&!cn&&fs===3){wt(fn);return}if(xt(),!tn&&!cn){if(!fn)return;h.push(new $G(3,"","",Ne(fn),"",fs));return}let Fi;cn?cn==="*"?Fi=eIe:Fi=cn:Fi=_;let Ho=2;Fi===_?(Ho=1,Fi=""):Fi===eIe&&(Ho=0,Fi="");let di;if(tn?di=tn:cn&&(di=b++),M.has(di))throw new TypeError(`Duplicate name '${di}'.`);M.add(di),h.push(new $G(Ho,di,Ne(fn),Fi,Ne(Cr),fs))},"V");for(;D<l.length;){let fn=z("CHAR"),tn=z("NAME"),cn=z("REGEX");if(!tn&&!cn&&(cn=z("ASTERISK")),tn||cn){let vr=fn??"";s.prefixes.indexOf(vr)===-1&&(wt(vr),vr=""),xt();let fs=re();Tr(vr,tn,cn,"",fs);continue}let Cr=fn??z("ESCAPED_CHAR");if(Cr){wt(Cr);continue}if(z("OPEN")){let vr=Q(),fs=z("NAME"),Fi=z("REGEX");!fs&&!Fi&&(Fi=z("ASTERISK"));let Ho=Q();ie("CLOSE");let di=re();Tr(vr,fs,Fi,Ho,di);continue}xt(),ie("END")}return h}t(ppt,"D");function RT(a){return a.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}t(RT,"S");function upt(a){return a&&a.ignoreCase?"ui":"u"}t(upt,"X");function pur(a,s,l){return dpt(ppt(a,l),s,l)}t(pur,"Z");function hj(a){switch(a){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}t(hj,"k");function dpt(a,s,l={}){l.delimiter??="/#?",l.prefixes??="./",l.sensitive??=!1,l.strict??=!1,l.end??=!0,l.start??=!0,l.endsWith="";let _=l.start?"^":"";for(let N of a){if(N.type===3){N.modifier===3?_+=RT(N.value):_+=`(?:${RT(N.value)})${hj(N.modifier)}`;continue}s&&s.push(N.name);let M=`[^${RT(l.delimiter)}]+?`,z=N.value;if(N.type===1?z=M:N.type===0&&(z=eIe),!N.prefix.length&&!N.suffix.length){N.modifier===3||N.modifier===1?_+=`(${z})${hj(N.modifier)}`:_+=`((?:${z})${hj(N.modifier)})`;continue}if(N.modifier===3||N.modifier===1){_+=`(?:${RT(N.prefix)}(${z})${RT(N.suffix)})`,_+=hj(N.modifier);continue}_+=`(?:${RT(N.prefix)}`,_+=`((?:${z})(?:`,_+=RT(N.suffix),_+=RT(N.prefix),_+=`(?:${z}))*)${RT(N.suffix)})`,N.modifier===0&&(_+="?")}let h=`[${RT(l.endsWith)}]|$`,b=`[${RT(l.delimiter)}]`;if(l.end)return l.strict||(_+=`${b}?`),l.endsWith.length?_+=`(?=${h})`:_+="$",new RegExp(_,upt(l));l.strict||(_+=`(?:${b}(?=${h}))?`);let D=!1;if(a.length){let N=a[a.length-1];N.type===3&&N.modifier===3&&(D=l.delimiter.indexOf(N)>-1)}return D||(_+=`(?=${b}|${h})`),new RegExp(_,upt(l))}t(dpt,"F");var H3={delimiter:"",prefixes:"",sensitive:!0,strict:!0},dur={delimiter:".",prefixes:"",sensitive:!0,strict:!0},mur={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function hur(a,s){return a.length?a[0]==="/"?!0:!s||a.length<2?!1:(a[0]=="\\"||a[0]=="{")&&a[1]=="/":!1}t(hur,"J");function mpt(a,s){return a.startsWith(s)?a.substring(s.length,a.length):a}t(mpt,"Q");function gur(a,s){return a.endsWith(s)?a.substr(0,a.length-s.length):a}t(gur,"Ee");function hpt(a){return!a||a.length<2?!1:a[0]==="["||(a[0]==="\\"||a[0]==="{")&&a[1]==="["}t(hpt,"W");var gpt=["ftp","file","http","https","ws","wss"];function ypt(a){if(!a)return!0;for(let s of gpt)if(a.test(s))return!0;return!1}t(ypt,"N");function yur(a,s){if(a=mpt(a,"#"),s||a==="")return a;let l=new URL("https://example.com");return l.hash=a,l.hash?l.hash.substring(1,l.hash.length):""}t(yur,"te");function vur(a,s){if(a=mpt(a,"?"),s||a==="")return a;let l=new URL("https://example.com");return l.search=a,l.search?l.search.substring(1,l.search.length):""}t(vur,"re");function bur(a,s){return s||a===""?a:hpt(a)?Spt(a):bpt(a)}t(bur,"ne");function Sur(a,s){if(s||a==="")return a;let l=new URL("https://example.com");return l.password=a,l.password}t(Sur,"se");function Tur(a,s){if(s||a==="")return a;let l=new URL("https://example.com");return l.username=a,l.username}t(Tur,"ie");function xur(a,s,l){if(l||a==="")return a;if(s&&!gpt.includes(s))return new URL(`${s}:${a}`).pathname;let _=a[0]=="/";return a=new URL(_?a:"/-"+a,"https://example.com").pathname,_||(a=a.substring(2,a.length)),a}t(xur,"ae");function Cur(a,s,l){return vpt(s)===a&&(a=""),l||a===""?a:Tpt(a)}t(Cur,"oe");function Eur(a,s){return a=gur(a,":"),s||a===""?a:tIe(a)}t(Eur,"ce");function vpt(a){switch(a){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}t(vpt,"_");function tIe(a){if(a==="")return a;if(/^[-+.A-Za-z0-9]*$/.test(a))return a.toLowerCase();throw new TypeError(`Invalid protocol '${a}'.`)}t(tIe,"y");function Dur(a){if(a==="")return a;let s=new URL("https://example.com");return s.username=a,s.username}t(Dur,"le");function kur(a){if(a==="")return a;let s=new URL("https://example.com");return s.password=a,s.password}t(kur,"fe");function bpt(a){if(a==="")return a;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test(a))throw new TypeError(`Invalid hostname '${a}'`);let s=new URL("https://example.com");return s.hostname=a,s.hostname}t(bpt,"z");function Spt(a){if(a==="")return a;if(/[^0-9a-fA-F[\]:]/g.test(a))throw new TypeError(`Invalid IPv6 hostname '${a}'`);return a.toLowerCase()}t(Spt,"j");function Tpt(a){if(a===""||/^[0-9]*$/.test(a)&&parseInt(a)<=65535)return a;throw new TypeError(`Invalid port '${a}'.`)}t(Tpt,"K");function wur(a){if(a==="")return a;let s=new URL("https://example.com");return s.pathname=a[0]!=="/"?"/-"+a:a,a[0]!=="/"?s.pathname.substring(2,s.pathname.length):s.pathname}t(wur,"he");function Pur(a){return a===""?a:new URL(`data:${a}`).pathname}t(Pur,"ue");function Aur(a){if(a==="")return a;let s=new URL("https://example.com");return s.search=a,s.search.substring(1,s.search.length)}t(Aur,"de");function Nur(a){if(a==="")return a;let s=new URL("https://example.com");return s.hash=a,s.hash.substring(1,s.hash.length)}t(Nur,"pe");var Iur=class{static{t(this,"H")}#r;#n=[];#e={};#t=0;#s=1;#p=0;#a=0;#_=0;#c=0;#l=!1;constructor(a){this.#r=a}get result(){return this.#e}parse(){for(this.#n=_pt(this.#r,!0);this.#t<this.#n.length;this.#t+=this.#s){if(this.#s=1,this.#n[this.#t].type==="END"){if(this.#a===0){this.#v(),this.#D()?this.#i(9,1):this.#y()?this.#i(8,1):this.#i(7,0);continue}else if(this.#a===2){this.#d(5);continue}this.#i(10,0);break}if(this.#_>0)if(this.#o())this.#_-=1;else continue;if(this.#w()){this.#_+=1;continue}switch(this.#a){case 0:this.#g()&&this.#d(1);break;case 1:if(this.#g()){this.#I();let a=7,s=1;this.#E()?(a=2,s=3):this.#l&&(a=2),this.#i(a,s)}break;case 2:this.#x()?this.#d(3):(this.#C()||this.#y()||this.#D())&&this.#d(5);break;case 3:this.#b()?this.#i(4,1):this.#x()&&this.#i(5,1);break;case 4:this.#x()&&this.#i(5,1);break;case 5:this.#N()?this.#c+=1:this.#S()&&(this.#c-=1),this.#k()&&!this.#c?this.#i(6,1):this.#C()?this.#i(7,0):this.#y()?this.#i(8,1):this.#D()&&this.#i(9,1);break;case 6:this.#C()?this.#i(7,0):this.#y()?this.#i(8,1):this.#D()&&this.#i(9,1);break;case 7:this.#y()?this.#i(8,1):this.#D()&&this.#i(9,1);break;case 8:this.#D()&&this.#i(9,1);break;case 9:break;case 10:break}}this.#e.hostname!==void 0&&this.#e.port===void 0&&(this.#e.port="")}#i(a,s){switch(this.#a){case 0:break;case 1:this.#e.protocol=this.#T();break;case 2:break;case 3:this.#e.username=this.#T();break;case 4:this.#e.password=this.#T();break;case 5:this.#e.hostname=this.#T();break;case 6:this.#e.port=this.#T();break;case 7:this.#e.pathname=this.#T();break;case 8:this.#e.search=this.#T();break;case 9:this.#e.hash=this.#T();break;case 10:break}this.#a!==0&&a!==10&&([1,2,3,4].includes(this.#a)&&[6,7,8,9].includes(a)&&(this.#e.hostname??=""),[1,2,3,4,5,6].includes(this.#a)&&[8,9].includes(a)&&(this.#e.pathname??=this.#l?"/":""),[1,2,3,4,5,6,7].includes(this.#a)&&a===9&&(this.#e.search??="")),this.#f(a,s)}#f(a,s){this.#a=a,this.#p=this.#t+s,this.#t+=s,this.#s=0}#v(){this.#t=this.#p,this.#s=0}#d(a){this.#v(),this.#a=a}#u(a){return a<0&&(a=this.#n.length-a),a<this.#n.length?this.#n[a]:this.#n[this.#n.length-1]}#m(a,s){let l=this.#u(a);return l.value===s&&(l.type==="CHAR"||l.type==="ESCAPED_CHAR"||l.type==="INVALID_CHAR")}#g(){return this.#m(this.#t,":")}#E(){return this.#m(this.#t+1,"/")&&this.#m(this.#t+2,"/")}#x(){return this.#m(this.#t,"@")}#b(){return this.#m(this.#t,":")}#k(){return this.#m(this.#t,":")}#C(){return this.#m(this.#t,"/")}#y(){if(this.#m(this.#t,"?"))return!0;if(this.#n[this.#t].value!=="?")return!1;let a=this.#u(this.#t-1);return a.type!=="NAME"&&a.type!=="REGEX"&&a.type!=="CLOSE"&&a.type!=="ASTERISK"}#D(){return this.#m(this.#t,"#")}#w(){return this.#n[this.#t].type=="OPEN"}#o(){return this.#n[this.#t].type=="CLOSE"}#N(){return this.#m(this.#t,"[")}#S(){return this.#m(this.#t,"]")}#T(){let a=this.#n[this.#t],s=this.#u(this.#p).index;return this.#r.substring(s,a.index)}#I(){let a={};Object.assign(a,H3),a.encodePart=tIe;let s=pur(this.#T(),void 0,a);this.#l=ypt(s)}},ZNe=["protocol","username","password","hostname","port","pathname","search","hash"],W3="*";function fpt(a,s){if(typeof a!="string")throw new TypeError("parameter 1 is not of type 'string'.");let l=new URL(a,s);return{protocol:l.protocol.substring(0,l.protocol.length-1),username:l.username,password:l.password,hostname:l.hostname,port:l.port,pathname:l.pathname,search:l.search!==""?l.search.substring(1,l.search.length):void 0,hash:l.hash!==""?l.hash.substring(1,l.hash.length):void 0}}t(fpt,"ge");function FA(a,s){return s?UG(a):a}t(FA,"b");function BG(a,s,l){let _;if(typeof s.baseURL=="string")try{_=new URL(s.baseURL),s.protocol===void 0&&(a.protocol=FA(_.protocol.substring(0,_.protocol.length-1),l)),!l&&s.protocol===void 0&&s.hostname===void 0&&s.port===void 0&&s.username===void 0&&(a.username=FA(_.username,l)),!l&&s.protocol===void 0&&s.hostname===void 0&&s.port===void 0&&s.username===void 0&&s.password===void 0&&(a.password=FA(_.password,l)),s.protocol===void 0&&s.hostname===void 0&&(a.hostname=FA(_.hostname,l)),s.protocol===void 0&&s.hostname===void 0&&s.port===void 0&&(a.port=FA(_.port,l)),s.protocol===void 0&&s.hostname===void 0&&s.port===void 0&&s.pathname===void 0&&(a.pathname=FA(_.pathname,l)),s.protocol===void 0&&s.hostname===void 0&&s.port===void 0&&s.pathname===void 0&&s.search===void 0&&(a.search=FA(_.search.substring(1,_.search.length),l)),s.protocol===void 0&&s.hostname===void 0&&s.port===void 0&&s.pathname===void 0&&s.search===void 0&&s.hash===void 0&&(a.hash=FA(_.hash.substring(1,_.hash.length),l))}catch{throw new TypeError(`invalid baseURL '${s.baseURL}'.`)}if(typeof s.protocol=="string"&&(a.protocol=Eur(s.protocol,l)),typeof s.username=="string"&&(a.username=Tur(s.username,l)),typeof s.password=="string"&&(a.password=Sur(s.password,l)),typeof s.hostname=="string"&&(a.hostname=bur(s.hostname,l)),typeof s.port=="string"&&(a.port=Cur(s.port,a.protocol,l)),typeof s.pathname=="string"){if(a.pathname=s.pathname,_&&!hur(a.pathname,l)){let h=_.pathname.lastIndexOf("/");h>=0&&(a.pathname=FA(_.pathname.substring(0,h+1),l)+a.pathname)}a.pathname=xur(a.pathname,a.protocol,l)}return typeof s.search=="string"&&(a.search=vur(s.search,l)),typeof s.hash=="string"&&(a.hash=yur(s.hash,l)),a}t(BG,"w");function UG(a){return a.replace(/([+*?:{}()\\])/g,"\\$1")}t(UG,"C");function Fur(a){return a.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}t(Fur,"Oe");function Our(a,s){s.delimiter??="/#?",s.prefixes??="./",s.sensitive??=!1,s.strict??=!1,s.end??=!0,s.start??=!0,s.endsWith="";let l=".*",_=`[^${Fur(s.delimiter)}]+?`,h=/[$_\u200C\u200D\p{ID_Continue}]/u,b="";for(let D=0;D<a.length;++D){let N=a[D];if(N.type===3){if(N.modifier===3){b+=UG(N.value);continue}b+=`{${UG(N.value)}}${hj(N.modifier)}`;continue}let M=N.hasCustomName(),z=!!N.suffix.length||!!N.prefix.length&&(N.prefix.length!==1||!s.prefixes.includes(N.prefix)),re=D>0?a[D-1]:null,ie=D<a.length-1?a[D+1]:null;if(!z&&M&&N.type===1&&N.modifier===3&&ie&&!ie.prefix.length&&!ie.suffix.length)if(ie.type===3){let Q=ie.value.length>0?ie.value[0]:"";z=h.test(Q)}else z=!ie.hasCustomName();if(!z&&!N.prefix.length&&re&&re.type===3){let Q=re.value[re.value.length-1];z=s.prefixes.includes(Q)}z&&(b+="{"),b+=UG(N.prefix),M&&(b+=`:${N.name}`),N.type===2?b+=`(${N.value})`:N.type===1?M||(b+=`(${_})`):N.type===0&&(!M&&(!re||re.type===3||re.modifier!==3||z||N.prefix!=="")?b+="*":b+=`(${l})`),N.type===1&&M&&N.suffix.length&&h.test(N.suffix[0])&&(b+="\\"),b+=UG(N.suffix),z&&(b+="}"),N.modifier!==3&&(b+=hj(N.modifier))}return b}t(Our,"ke");var xpt=class{static{t(this,"me")}#r;#n={};#e={};#t={};#s={};#p=!1;constructor(a={},s,l){try{let _;if(typeof s=="string"?_=s:l=s,typeof a=="string"){let N=new Iur(a);if(N.parse(),a=N.result,_===void 0&&typeof a.protocol!="string")throw new TypeError("A base URL must be provided for a relative constructor string.");a.baseURL=_}else{if(!a||typeof a!="object")throw new TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(_)throw new TypeError("parameter 1 is not of type 'string'.")}typeof l>"u"&&(l={ignoreCase:!1});let h={ignoreCase:l.ignoreCase===!0},b={pathname:W3,protocol:W3,username:W3,password:W3,hostname:W3,port:W3,search:W3,hash:W3};this.#r=BG(b,a,!0),vpt(this.#r.protocol)===this.#r.port&&(this.#r.port="");let D;for(D of ZNe){if(!(D in this.#r))continue;let N={},M=this.#r[D];switch(this.#e[D]=[],D){case"protocol":Object.assign(N,H3),N.encodePart=tIe;break;case"username":Object.assign(N,H3),N.encodePart=Dur;break;case"password":Object.assign(N,H3),N.encodePart=kur;break;case"hostname":Object.assign(N,dur),hpt(M)?N.encodePart=Spt:N.encodePart=bpt;break;case"port":Object.assign(N,H3),N.encodePart=Tpt;break;case"pathname":ypt(this.#n.protocol)?(Object.assign(N,mur,h),N.encodePart=wur):(Object.assign(N,H3,h),N.encodePart=Pur);break;case"search":Object.assign(N,H3,h),N.encodePart=Aur;break;case"hash":Object.assign(N,H3,h),N.encodePart=Nur;break}try{this.#s[D]=ppt(M,N),this.#n[D]=dpt(this.#s[D],this.#e[D],N),this.#t[D]=Our(this.#s[D],N),this.#p=this.#p||this.#s[D].some(z=>z.type===2)}catch{throw new TypeError(`invalid ${D} pattern '${this.#r[D]}'.`)}}}catch(_){throw new TypeError(`Failed to construct 'URLPattern': ${_.message}`)}}test(a={},s){let l={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof a!="string"&&s)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof a>"u")return!1;try{typeof a=="object"?l=BG(l,a,!1):l=BG(l,fpt(a,s),!1)}catch{return!1}let _;for(_ of ZNe)if(!this.#n[_].exec(l[_]))return!1;return!0}exec(a={},s){let l={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof a!="string"&&s)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof a>"u")return;try{typeof a=="object"?l=BG(l,a,!1):l=BG(l,fpt(a,s),!1)}catch{return null}let _={};s?_.inputs=[a,s]:_.inputs=[a];let h;for(h of ZNe){let b=this.#n[h].exec(l[h]);if(!b)return null;let D={};for(let[N,M]of this.#e[h].entries())if(typeof M=="string"||typeof M=="number"){let z=b[N+1];D[M]=z}_[h]={input:l[h]??"",groups:D}}return _}static compareComponent(a,s,l){let _=t((N,M)=>{for(let z of["type","modifier","prefix","value","suffix"]){if(N[z]<M[z])return-1;if(N[z]!==M[z])return 1}return 0},"o"),h=new $G(3,"","","","",3),b=new $G(0,"","","","",3),D=t((N,M)=>{let z=0;for(;z<Math.min(N.length,M.length);++z){let re=_(N[z],M[z]);if(re)return re}return N.length===M.length?0:_(N[z]??h,M[z]??h)},"s");return!s.#t[a]&&!l.#t[a]?0:s.#t[a]&&!l.#t[a]?D(s.#s[a],[b]):!s.#t[a]&&l.#t[a]?D([b],l.#s[a]):D(s.#s[a],l.#s[a])}get protocol(){return this.#t.protocol}get username(){return this.#t.username}get password(){return this.#t.password}get hostname(){return this.#t.hostname}get port(){return this.#t.port}get pathname(){return this.#t.pathname}get search(){return this.#t.search}get hash(){return this.#t.hash}get hasRegExpGroups(){return this.#p}};globalThis.URLPattern||(globalThis.URLPattern=xpt);import{AssertionError as Lur}from"node:assert";function OA(a,s){if(a===!1)throw new Lur({message:s})}t(OA,"assert");var ec;(function(a){a.Object="Object",a.Property="Property",a.Array="Array",a.Literal="Literal",a.TemplateString="TemplateString",a.Identifier="Identifier",a.FunctionCall="FunctionCall",a.Raw="Raw"})(ec||(ec={}));function gj(a){return a.type===ec.Object}t(gj,"isAstObject");function LA(a){return a.type===ec.Property}t(LA,"isAstProperty");function Cpt(a){return a.type===ec.Array}t(Cpt,"isAstArray");function yj(a){return a.type===ec.Literal}t(yj,"isAstLiteral");function G3(a){if(a===void 0)throw new Error("Node is undefined");if(!gj(a))throw new Error("Node is not object")}t(G3,"assertAstObject");import{findNodeAtLocation as Rur,getNodeValue as Mur,printParseErrorCode as jur,visit as Bur}from"jsonc-parser";var Uur={DEFAULT:{allowTrailingComma:!1}};function zG(a,s=[],l=Uur.DEFAULT){let _={type:"array",offset:-1,length:-1,line:-1,column:-1,children:[],parent:void 0};function h(M){_.type==="property"&&(_.length=M-_.offset,_=_.parent)}t(h,"ensurePropertyComplete");function b(M){return _.children?.push(M),M}t(b,"onValue"),Bur(a,{onObjectBegin:t((M,z,re)=>{_=b({type:"object",offset:M,length:-1,line:z+1,column:re+1,parent:_,children:[]})},"onObjectBegin"),onObjectProperty:t((M,z,re,ie,Q)=>{_=b({type:"property",offset:z,length:-1,line:ie+1,column:Q+1,parent:_,children:[]}),_.children?.push({type:"string",value:M,offset:z,length:re,line:ie,column:Q,parent:_})},"onObjectProperty"),onObjectEnd:t((M,z)=>{h(M+z),_.length=M+z-_.offset,_=_.parent,h(M+z)},"onObjectEnd"),onArrayBegin:t((M,z,re,ie)=>{_=b({type:"array",offset:M,length:-1,line:re+1,column:ie+1,parent:_,children:[]})},"onArrayBegin"),onArrayEnd:t((M,z)=>{_.length=M+z-_.offset,_=_.parent,h(M+z)},"onArrayEnd"),onLiteralValue:t((M,z,re,ie,Q)=>{b({type:$ur(M),offset:z,length:re,line:ie+1,column:Q+1,parent:_,value:M}),h(z+re)},"onLiteralValue"),onSeparator:t((M,z)=>{_.type==="property"&&(M===":"?_.colonOffset=z:M===","&&h(z))},"onSeparator"),onError:t((M,z,re,ie,Q)=>{s.push({error:M,offset:z,length:re,line:ie+1,column:Q+1})},"onError")},l);let N=_.children[0];return N&&delete N.parent,N}t(zG,"parse");function $ur(a){switch(typeof a){case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"object":{if(a){if(Array.isArray(a))return"array"}else return"null";return"object"}default:return"null"}}t($ur,"getNodeType");function rIe(a,s){return Rur(a,s)}t(rIe,"findNodeAtLocation");function JG(a){return Mur(a)}t(JG,"getNodeValue");function Ept(a){return jur(a)}t(Ept,"printParseErrorCode");var qG=class{static{t(this,"AstAdapter")}parse(s){let _=zG(s,[]);if(_)return this.parseNode(_,void 0);throw new Error("Failed to parse JSON")}convert(s){return this.parseNode(s,void 0)}parseNode(s,l){switch(s.type){case"object":return this.createObject(s,l);case"array":return this.createArray(s,l);case"property":return this.createProperty(s,l);case"string":return this.createLiteral(s,l);case"number":return this.createLiteral(s,l);case"boolean":return this.createLiteral(s,l);case"null":return this.createLiteral(s,l)}}createLiteral(s,l){return{type:ec.Literal,location:{line:s.line,column:s.column},parent:l,value:s.type==="null"?null:s.value}}createObject(s,l){let _={type:ec.Object,children:[],parent:l,location:{line:s.line,column:s.column}};return s.children?.forEach(h=>{_.children.push(this.parseNode(h,_))}),_}createProperty(s,l){OA(s.children?.length===2,"Invalid property node");let _={type:ec.Property,location:{line:s.line,column:s.column},parent:l,name:null,value:null};return _.name={value:s.children[0].value,location:{line:s.line,column:s.column},type:ec.Identifier,parent:_},_.value=this.parseNode(s.children[1],_),_}createArray(s,l){let _={type:ec.Array,location:{line:s.line,column:s.column},parent:l,children:[]};return s.children?.forEach(h=>_.children.push(this.parseNode(h,_))),_}};var MT={createLiteral:t((a,s)=>({type:ec.Literal,parent:s,value:a}),"createLiteral"),createTemplateString:t((a,s)=>({type:ec.TemplateString,parent:s,value:a}),"createTemplateString"),createIdentifier:t((a,s)=>({type:ec.Identifier,value:a,parent:s}),"createIdentifier"),createProperty:t((a,s,l)=>{let _={type:ec.Property,parent:l,name:null,value:s};return _.name={value:a,type:ec.Identifier,parent:_},_.value.parent=_,_},"createProperty"),createArrayOfLiterals:t((a,s)=>{let l={type:ec.Array,parent:s,children:[]};for(let _ of a)l.children.push(MT.createLiteral(_,l));return l},"createArrayOfLiterals")};var zur=/^[a-zA-Z_$][a-zA-Z0-9_$]*$/,VG=class{static{t(this,"SourceGenerator")}generate(s){let l=[];return this.generateSource(l,s),l.join("")}generateSource(s,l){switch(l.type){case ec.Array:return this.generateArray(s,l);case ec.Object:return this.generateObject(s,l);case ec.Property:return this.generateProperty(s,l);case ec.Literal:return this.generateLiteral(s,l);case ec.FunctionCall:return this.generateFunctionCall(s,l);case ec.Identifier:return this.generateIdentifier(s,l);case ec.Raw:return this.generateRaw(s,l);case ec.TemplateString:return this.generateTemplateString(s,l)}}generateArray(s,l){s.push("["),l.children.map(_=>{this.generateSource(s,_),s.push(",")}),s.push("]")}generateObject(s,l){s.push("{"),l.children.forEach(_=>{this.generateSource(s,_),s.push(",")}),s.push("}")}generateProperty(s,l){this.generateIdentifier(s,l.name),s.push(":"),this.generateSource(s,l.value)}generateFunctionCall(s,l){s.push(l.name.value),s.push("("),l.children.forEach((_,h,b)=>{this.generateSource(s,_),h<b.length&&s.push(",")}),s.push(")")}generateRaw(s,l){s.push(l.value)}generateTemplateString(s,l){s.push("`"),s.push(l.value.replaceAll("`","\\`")),s.push("`")}generateLiteral(s,l){if(l.value===null)return s.push("null");switch(typeof l.value){case"number":case"boolean":return s.push(`${l.value}`);case"string":{let _=l.value,h=JSON.stringify(_);return s.push(`${h}`)}}}generateIdentifier(s,l){let _=zur.test(l.value)?l.value:`'${l.value}'`;s.push(_)}};import Jur from"node:fs/promises";import{parse as qur}from"@swc/core";var Dpt=t(async a=>{let s=new Set;try{let l=await Jur.readFile(a,"utf-8");(await qur(l,{syntax:"typescript"})).body.forEach(h=>{h.type==="ExportDefaultDeclaration"||h.type==="ExportDefaultExpression"?s.add("default"):h.type==="ExportDeclaration"&&h.declaration.type==="FunctionDeclaration"?s.add(h.declaration.identifier.value):h.type==="ExportDeclaration"&&h.declaration.type==="VariableDeclaration"&&h.declaration.declarations[0].id.type==="Identifier"&&s.add(h.declaration.declarations[0].id.value)})}catch{return null}return s},"getJSFileExports");var kpt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/fragments.schema.json",$defs:{corsPolicyConfiguration:{type:"object",required:["name","allowedOrigins"],additionalProperties:!1,properties:{name:{type:"string",pattern:"^[0-9a-z-]+$"},allowCredentials:{type:"boolean"},maxAge:{type:"number"},allowedOrigins:{oneOf:[{type:"array",items:{type:"string"}},{type:"string"}]},allowedMethods:{oneOf:[{type:"array",items:{$ref:"fragments.schema.json#/$defs/httpMethod"}},{type:"string"}]},allowedHeaders:{oneOf:[{type:"array",items:{type:"string"}},{type:"string"}]},exposeHeaders:{oneOf:[{type:"array",items:{type:"string"}},{type:"string"}]}}},handlerDefinition:{type:"object",properties:{module:{type:"string",pattern:"^\\$import\\([^ )]*?\\)$"},export:{type:"string"},options:{type:"object",additionalProperties:!0}},additionalProperties:!1,required:["module","export"]},httpMethod:{type:"string",enum:["GET","HEAD","POST","PUT","DELETE","CONNECT","OPTIONS","TRACE","PATCH"]}}};var nIe={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/policies.schema.json",title:"Policies Config File",type:"object",additionalProperties:!1,properties:{policies:{type:"array",items:{$ref:"policy-configuration.schema.json"}},corsPolicies:{type:"array",items:{$ref:"fragments.schema.json#/$defs/corsPolicyConfiguration"}}}};var wpt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/policy-configuration.schema.json",title:"Policy Configuration Fragment",type:"object",required:["name","policyType","handler"],additionalProperties:!1,properties:{name:{type:"string",pattern:"^[0-9a-z-]+$"},policyType:{type:"string"},handler:{$ref:"fragments.schema.json#/$defs/handlerDefinition"},options:{type:"object",additionalProperties:!0}}};var iIe={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/route-configuration-open-api.schema.json",title:"Open API Route Configuration Fragment",description:"These are the properties that can appear under the x-zuplo-route extension in a PathObject in Open API. It's a subset of what can appear in Zuplo's routes.json.",type:"object",required:["handler"],additionalProperties:!1,properties:{label:{type:"string",description:"An internal user-friendly identifier of the route."},key:{type:"string",deprecated:!0},handler:{$ref:"fragments.schema.json#/$defs/handlerDefinition"},corsPolicy:{type:"string",pattern:"^[0-9a-z-]+$"},custom:{},mcp:{type:"object",additionalProperties:!1,properties:{enabled:{type:"boolean"}}},policies:{type:"object",additionalProperties:!1,properties:{inbound:{type:"array",items:{type:"string",pattern:"^[0-9a-z-]+$"}},outbound:{type:"array",items:{type:"string",pattern:"^[0-9a-z-]+$"}}}},tags:{type:"array",items:{type:"string"}}}};var sIe={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/route-configuration.schema.json",title:"Route Configuration Fragment",description:"",type:"object",required:["path","methods","handler"],additionalProperties:!1,$defs:{corsPolicy:{type:"string",pattern:"^[0-9a-z-]+$"}},properties:{operationId:{type:"string"},path:{type:"string",pattern:"^/[^\\s]*$"},methods:{type:"array",items:{$ref:"fragments.schema.json#/$defs/httpMethod"}},label:{type:"string",description:"An internal user-friendly identifier of the route."},enforceOpenApi:{type:"boolean",description:"If true, schema validation found in the OpenAPI spec will be enforced on requests/responses."},key:{type:"string",deprecated:!0},handler:{$ref:"fragments.schema.json#/$defs/handlerDefinition"},corsPolicy:{$ref:"#/$defs/corsPolicy"},custom:{},mcp:{type:"object",additionalProperties:!1,properties:{enabled:{type:"boolean"}}},policies:{type:"object",additionalProperties:!1,properties:{inbound:{type:"array",items:{type:"string",pattern:"^[0-9a-z-]+$"}},outbound:{type:"array",items:{type:"string",pattern:"^[0-9a-z-]+$"}}}},summary:{type:"string"},description:{type:"string"},excludeFromOpenApi:{type:"boolean"},tags:{type:"array",items:{type:"string"}}}};var $ht=x_(uht(),1),zht=x_(Uht(),1);var Ffe=class a{static{t(this,"JsonValidator")}static#r=new a;static get instance(){return a.#r}ajv;constructor(){this.ajv=new zht.Ajv2020({allErrors:!0,allowUnionTypes:!0}),this.ajv.addKeyword("faker"),(0,$ht.default)(this.ajv,{mode:"fast"})}addSchema(s,l){this.ajv.addSchema(s,l)}compile(s){let l=this.ajv.compile(s);return t(h=>({isValid:l(h),errors:this.toSimpleErrors(l.errors,h),warnings:[]}),"validator")}toSimpleErrors(s,l){let _=[];return s?.forEach(h=>{h.keyword==="enum"&&h.params.allowedValues&&Array.isArray(h.params.allowedValues)&&(h.message+=`; ${h.params.allowedValues.join(", ")}`),h.instancePath&&(h.instancePath=h.instancePath.replaceAll(/(\/)?(~1)(\/)?/gm,"/"));let b={details:{}},D=h.instancePath.split("/");if(D.length>2){let M=D[1],z=D[2]?parseInt(D[2]):0,re=D[3],ie=isNaN(z)?void 0:l[M][z][re];b={details:{property:M,index:z,field:re,fieldValue:ie}}}if(h.keyword==="required"&&h.params.missingProperty&&h.instancePath&&(h.message=`A 'path' is missing required property '${h.params.missingProperty}'`),h.keyword==="additionalProperties"&&h.params.additionalProperty&&h.instancePath&&(h.message=`A 'path' should NOT include property '${h.params.additionalProperty}'`),h.keyword==="type"&&h.params.type&&h.instancePath){let M=h.instancePath.split("/"),z=M[M.length-1];h.message=`Value of property '${z}' must be '${h.params.type}'`}let N=Object.assign(h,b);_.push(N)}),_}};var iN=Ffe.instance;iN.addSchema(sIe,"route-configuration.schema.json");iN.addSchema(wpt,"policy-configuration.schema.json");iN.addSchema(nIe,"policies.schema.json");iN.addSchema(iIe,"open-api-route-configuration.schema.json");iN.addSchema(kpt,"fragments.schema.json");var tRr=iN.compile(sIe),Jht=iN.compile(iIe),bFe=iN.compile(nIe);var Ofe=class{static{t(this,"PoliciesConfigurationValidator")}results;validate(s){return this.results=bFe(s),this.results}};var Lfe=class{static{t(this,"OpenAPILocalizedValidator")}results;validate(s){return this.results=Jht(s),this.results}};import Xgr from"node:path";var SFe=/\$import\((.*)\)/,Rfe=/\$env\((.*?)\)/g;var UA=class extends Error{static{t(this,"CodeGenError")}location;constructor(s,l,_,h){super(s),this.location={file:l,namespace:"",line:_?_.line:0,column:_?_.column:0,length:0,lineText:h??"",suggestion:""}}},Ygr=t(a=>{let s=[],l=a;for(;l.parent;)s.push(l),l=l.parent;return s.reverse()},"invertTree"),sN=t((a,s)=>{if(!a)return!1;let l=Ygr(a);return s.split("/").every((b,D)=>{let N=l[D];return N?b==="*"||LA(N)&&N.name.value===b?!0:b==="{}"?N.type===ec.Object:b==="[]"?N.type===ec.Array:!1:!1})},"testPosition");var Mfe=class{static{t(this,"AstTransformer")}errors=[];transform(s){return this.visitor(s),s}visitor(s){this.visit(s),gj(s)?s.children.forEach(l=>{this.visitor(l)}):Cpt(s)?s.children.forEach(l=>{this.visitor(l)}):LA(s)&&this.visitor(s.value)}},qht=t((a,s,l)=>_=>{if(!LA(_)||!yj(_.value)||typeof _.value.value!="string")return;if(!a.some(b=>sN(_,b))){Rfe.test(_.value.value)&&s.push(new UA("An $env() statement is not expected at this location.",l,_.location,_.value.value));return}let h=new RegExp(Rfe).exec(_.value.value);if(h?.length===2&&h[0]===_.value.value){let b={type:ec.Raw,parent:null,value:`environment["${h[1]}"]`};_.value=b}else{let b=_.value.value.replaceAll(new RegExp(Rfe),(D,N)=>`\${environment["${N}"] ? environment["${N}"] : ""}`);b!==_.value.value&&(_.value=MT.createTemplateString(b,_))}},"getEnvStatementTransformer");var CK="config/routes.json",Qgr=["handler/{}/options/*","policies/[]/{}/handler/{}/options/*","corsPolicies/[]/{}/*"],Zgr=["handler/{}/module","handler/{}/options/{}/policies/{}/inbound/[]/{}/module","handler/{}/options/{}/policies/{}/outbound/[]/{}/module","policies/[]/{}/handler/{}/module","policies/[]/{}/handler/{}/options/{}/identifier/{}/module","policies/[]/{}/handler/{}/options/{}/validator"],Vht=["handler/{}/options/*","policies/[]/{}/handler/{}/options/*"],e0r="handler/{}/options/{}/rewritePattern",t0r="handler/{}/options/{}/baseUrl",jfe=class extends Mfe{static{t(this,"OpenAPIRoutesFragmentAstTransformer")}importCount=0;addedImports=new Map;getImportName(s){this.addedImports.has(s)||this.addedImports.set(s,`__import${this.importCount++}`);let l=this.addedImports.get(s);if(!l)throw new Error("Import name is undefined. This should not happen.");return l}getImports(){let s=[];return this.addedImports.forEach((l,_)=>{s.push({name:l,path:_})}),s}visit(s){this.rewriteHandlerFunction(s),this.rewriteForwardFunction(s),this.replaceImportStatements(s),this.replaceEnvStatements(s)}rewriteHandlerFunction(s){if(!(!LA(s)||!yj(s.value)||typeof s.value.value!="string")&&sN(s,e0r)){if(!s.parent||!gj(s.parent)){this.errors.push(new UA("Invalid node, expected object",CK,s.parent?s.parent.location:s.location,void 0));return}let l=s.value.value,_={type:ec.Raw,parent:null,value:Wht(l)},h=MT.createProperty("__rewriteFunction",_,s);s.parent.children.push(h)}}rewriteForwardFunction(s){if(!(!LA(s)||!yj(s.value)||typeof s.value.value!="string")&&sN(s,t0r)){if(!s.parent||!gj(s.parent)){this.errors.push(new UA("Invalid node, expected object",CK,s.parent?s.parent.location:s.location,void 0));return}let l=s.value.value,_={type:ec.Raw,parent:null,value:Wht(l)},h=MT.createProperty("__rewriteFunction",_,s);s.parent.children.push(h)}}replaceImportStatements(s){if(!LA(s)||!yj(s.value))return;let l=s.value.value;if(typeof l!="string")return;if(!Zgr.some(N=>sN(s,N))&&!Vht.some(N=>sN(s,N))){if(SFe.test(l)){if(s.name.value==="$ref")return;this.errors.push(new UA("An $import() statement is not expected at this location.",CK,s.location,l))}return}let _=SFe.exec(l);if(Vht.some(N=>sN(s,N))&&!_)return;if(!_){this.errors.push(new UA("Invalid $import() statement",CK,s.location,l));return}let h=_[1];h=h.replace(/\\/g,"/"),h.startsWith(".")&&(h=Xgr.posix.join("..",h));let b=this.getImportName(h),D={type:ec.Identifier,parent:s.parent,value:b};s.value=D}replaceEnvStatements=qht(Qgr,this.errors,CK)};function Wht(a){return`(request, context) => {
584
584
  const { params, url, query, method, headers } = request;
585
585
  const { host, hostname, origin, pathname, port, search } = new URL(url);
@@ -622,7 +622,7 @@ ${Pk}${l.detail.toString().split(`
622
622
  `).join(`
623
623
  ${Pk}`)}`:""}`);_.push(D);let N=lxr(l.location??void 0);if(N&&_.push(`${Pk}${b(`The error was found in the file: ${N}`)}`),l.location&&l.location.file&&l.location.column!==0&&l.location.line!==0)try{let M=cxr.join(a,l.location.file),z=await oxr(M,"utf-8"),re=(0,rvt.codeFrameColumns)(z,{start:{line:l.location.line,column:l.location.column}},{highlightCode:!0,message:l.message,linesAbove:3,linesBelow:3});_.push(Pk),_.push(re)}catch{}else l.location&&l.location.file&&_.push(KT.red(`${Pk}File: ${l.location.file}:${l.location.line}:${l.location.column}`));_.push(""),l.severity==="warning"?s.warn(_.join(`
624
624
  `)):s.error(_.join(`
625
- `))}t(tvt,"logIssue");function lxr(a){if(a&&a.file){let s=a.file;if(a.line)return`${s}:${a.line}`;if(a.column)return`${s}:${a.column}`}}t(lxr,"getFileLocation");var YT=class{static{t(this,"PluginResult")}errors=[];warnings=[];constructor(s){s&&this.errors.push(s)}};async function nvt(a,s,l){let _=[],h=[],b=new Map;for await(let D of a)try{let N=await D(s,{data:b,errors:h,warnings:_});if(h.push(...N.errors.map(M=>(M.pluginName===""&&(M.pluginName=D.name),M))),_.push(...N.warnings),N.errors.length>0)break}catch(N){if(N instanceof J1?h.push({...N.issue,pluginName:N.pluginName??"unknown"}):h.push(N),l?.throwOnException)throw N;break}return{errors:h,warnings:_,data:b}}t(nvt,"runPlugins");import{readFile as uxr}from"node:fs/promises";import ivt from"node:path";import{parse as fxr}from"jsonc-parser";async function cB(a){let s=ivt.join(a,X6e),l=ivt.join(a,Q6e),_=!1,h=s;await ou.fileExists(s)?(_=!0,h=s):await ou.fileExists(l)&&(_=!0,h=l);let b,D;if(_){let M=await uxr(h,"utf-8"),re=fxr(M,[]);if(typeof re!="object")return{status:GF,errors:[{message:"Invalid zuplo.jsonc file.",detail:"The zuplo.jsonc file is not a valid JSON object",pluginName:"buildData",severity:"error"}]};if("version"in re&&re.version!==1)return{status:GF,errors:[{message:"Invalid version set in zuplo.jsonc file.",detail:"version in zuplo.jsonc must be set to 1",pluginName:"buildData",severity:"error"}]};if("compatibilityDate"in re&&PM&&typeof re.compatibilityDate=="string"){if(!PM.includes(re.compatibilityDate)){let ie={message:"Invalid compatibilityDate set in zuplo.jsonc file.",detail:`compatibilityDate was set to ${re.compatibilityDate}. Valid compatibility dates are ${PM.join(", ")}`,pluginName:"buildData",severity:"error"};return{status:GF,errors:[ie]}}b=re.compatibilityDate}D=rle(b,re.flags)}else D=rle(void 0,void 0);return{status:vA,config:{version:1,compatibilityDate:b,flags:D}}}t(cB,"getZuploConfig");import _xr from"node:fs";import{mkdir as svt,readFile as pxr,readdir as dxr,writeFile as mxr}from"node:fs/promises";import lY from"node:path";import hxr from"node:readline";var avt=t(async function({sourceDirectory:a,logger:s,outputDirectory:l,deploymentName:_,environmentType:h,deploymentUrl:b}){return Bu.timeFn("Building OpenAPI files",async()=>{s.debug("Building OpenAPI files");let D=lY.join(a,ub),N=lY.join(D,cle),M=lY.join(l,Yat,ub);try{if(await ou.dirExists(l)||await svt(l),await ou.dirExists(M)||await svt(M,{recursive:!0}),!await JM(a))return new YT({message:"Failed to build project because no OpenAPI file was found on the 'config' folder",pluginName:"build-open-api-files",severity:"error"});let ie=(await dxr(D)).filter(we=>we.endsWith(".oas.json"));if(!await ou.fileExists(N))return new YT({message:"The project must include a policies file ('/config/policies.json')",pluginName:"build-open-api-files",severity:"error"});let Q=await pxr(N,"utf-8"),Re=JSON.parse(Q),Ne=t(async we=>{let wt=lY.join(D,we);if(!await gxr(wt)){s.debug(`Skipping ${we} as it does not use the OpenAPI handler`);return}let xt;try{xt=await aft({sourceDirectory:a,openApiDocPath:wt,policiesConfig:Re,logger:s,environmentType:h,deploymentName:_,deploymentUrl:b})}catch(tn){if(s.error(tn),tn instanceof SyntaxError||tn instanceof IT.ResolverError||tn instanceof IT.JSONParserError||tn instanceof IT.ParserError||tn instanceof IT.MissingPointerError||tn instanceof lO)return new YT({message:tn.message,location:{file:we,column:0,length:0,line:0,lineText:"",namespace:"",suggestion:""},pluginName:"build-open-api-files",severity:"error"});if(tn instanceof J1)return new YT({...tn.issue,pluginName:"build-open-api-files"});throw tn}let Tr=JSON.stringify(xt,null,2),fn=lY.join(M,we);await mxr(fn,Tr,"utf-8")},"processFile");await Promise.all(ie.map(Ne))}catch(z){return s.error(z),new YT({message:"Error building OpenAPI files",pluginName:"build-open-api-files",severity:"error"})}return new YT})},"buildOpenApiFiles");async function gxr(a){let s=_xr.createReadStream(a),l=hxr.createInterface({input:s,crlfDelay:1/0}),_=!1,h=!1;for await(let b of l)if(b.includes('"openApiSpecHandler"')&&(_=!0),b.includes('"openApiFilePath"')&&(h=!0),_&&h)break;return l.close(),s.destroy(),_&&h}t(gxr,"usesOpenApiHandler");import yxr from"node:fs/promises";import vxr from"node:path";var ovt=t(async function({outputDirectory:a,systemDirectory:s,cacheDirectory:l,logger:_}){return Bu.timeFn("Cleaning output",async()=>{_.debug("Cleaning output");let h=vxr.join(l,"routes");return await Promise.all([a,s,h].map(async b=>{try{await yxr.rm(b,{recursive:!0,force:!0})}catch(D){_.error(D)}})),{warnings:[],errors:[]}})},"cleanOutput");import cvt from"node:fs/promises";var lvt=t(async function({systemDirectory:a,cacheDirectory:s,logger:l}){return Bu.timeFn("Creating system directory",async()=>{l.debug("Creating system directory");try{return await Promise.all([cvt.mkdir(a,{recursive:!0}),cvt.mkdir(s,{recursive:!0})]),{warnings:[],errors:[]}}catch(_){return l.error(_),{warnings:[],errors:[]}}return{warnings:[],errors:[]}})},"createSystemDir");var uvt=t(async function({logger:a}){return Bu.timeFn("Checking for breaking changes",async()=>(a.debug("Checking for breaking changes"),{warnings:[],errors:[]}))},"checkForDeprecations");import{readFile as bxr,writeFile as Sxr}from"node:fs/promises";import Txr from"node:path";var fvt=t(async function({systemDirectory:a,buildId:s,logger:l,config:_,publicZuploEnvironmentVariables:h}){return Bu.timeFn("Generating build data",async()=>{l.debug("Generating build data");let b=await bxr(new URL("../../../package.json",import.meta.url),"utf-8"),D=JSON.parse(b),N={BUILD_ID:s??"",GIT_SHA:process.env.GIT_SHA,TIMESTAMP:new Date().toISOString(),BUILD_ENV:Om.NODE_ENV,ZUPLO_VERSION:D.version,API_VERSION:process.env.API_VERSION,COMPATIBILITY_DATE:_?.compatibilityDate,ACCOUNT_NAME:h?.ZUPLO_ACCOUNT_NAME,PROJECT_NAME:h?.ZUPLO_PROJECT_NAME,ENVIRONMENT_TYPE:h?.ZUPLO_ENVIRONMENT_TYPE,IS_LOCAL_DEVELOPMENT:Om.isLocalDevelopment(),COMPATIBILITY_FLAGS:W6e[_?.compatibilityDate??"none"]},M=JSON.stringify(N,void 0,2),z=Txr.join(a,lle);try{await Sxr(z,M.trimStart(),"utf-8")}catch(re){l.error(re);let ie={message:`Error creating file at ${z}`,pluginName:"buildData",severity:"error"};return{warnings:[],errors:[ie]}}return{warnings:[],errors:[]}})},"generateBuildData");import xxr from"node:fs/promises";import Cxr from"node:path";var Exr=`import { Handler, ServiceProviderImpl } from "@zuplo/runtime";
625
+ `))}t(tvt,"logIssue");function lxr(a){if(a&&a.file){let s=a.file;if(a.line)return`${s}:${a.line}`;if(a.column)return`${s}:${a.column}`}}t(lxr,"getFileLocation");var YT=class{static{t(this,"PluginResult")}errors=[];warnings=[];constructor(s){s&&this.errors.push(s)}};async function nvt(a,s,l){let _=[],h=[],b=new Map;for await(let D of a)try{let N=await D(s,{data:b,errors:h,warnings:_});if(h.push(...N.errors.map(M=>(M.pluginName===""&&(M.pluginName=D.name),M))),_.push(...N.warnings),N.errors.length>0)break}catch(N){if(N instanceof J1?h.push({...N.issue,pluginName:N.pluginName??"unknown"}):h.push(N),l?.throwOnException)throw N;break}return{errors:h,warnings:_,data:b}}t(nvt,"runPlugins");import{readFile as uxr}from"node:fs/promises";import ivt from"node:path";import{parse as fxr}from"jsonc-parser";async function cB(a){let s=ivt.join(a,X6e),l=ivt.join(a,Q6e),_=!1,h=s;await ou.fileExists(s)?(_=!0,h=s):await ou.fileExists(l)&&(_=!0,h=l);let b,D;if(_){let M=await uxr(h,"utf-8"),re=fxr(M,[]);if(typeof re!="object")return{status:GF,errors:[{message:"Invalid zuplo.jsonc file.",detail:"The zuplo.jsonc file is not a valid JSON object",pluginName:"buildData",severity:"error"}]};if("version"in re&&re.version!==1)return{status:GF,errors:[{message:"Invalid version set in zuplo.jsonc file.",detail:"version in zuplo.jsonc must be set to 1",pluginName:"buildData",severity:"error"}]};if("compatibilityDate"in re&&PM&&typeof re.compatibilityDate=="string"){if(!PM.includes(re.compatibilityDate)){let ie={message:"Invalid compatibilityDate set in zuplo.jsonc file.",detail:`compatibilityDate was set to ${re.compatibilityDate}. Valid compatibility dates are ${PM.join(", ")}`,pluginName:"buildData",severity:"error"};return{status:GF,errors:[ie]}}b=re.compatibilityDate}D=rle(b,re.flags)}else D=rle(void 0,void 0);return{status:vA,config:{version:1,compatibilityDate:b,flags:D}}}t(cB,"getZuploConfig");import _xr from"node:fs";import{mkdir as svt,readFile as pxr,readdir as dxr,writeFile as mxr}from"node:fs/promises";import lY from"node:path";import hxr from"node:readline";var avt=t(async function({sourceDirectory:a,logger:s,outputDirectory:l,deploymentName:_,environmentType:h,urls:b}){return Bu.timeFn("Building OpenAPI files",async()=>{s.debug("Building OpenAPI files");let D=lY.join(a,ub),N=lY.join(D,cle),M=lY.join(l,Yat,ub);try{if(await ou.dirExists(l)||await svt(l),await ou.dirExists(M)||await svt(M,{recursive:!0}),!await JM(a))return new YT({message:"Failed to build project because no OpenAPI file was found on the 'config' folder",pluginName:"build-open-api-files",severity:"error"});let ie=(await dxr(D)).filter(we=>we.endsWith(".oas.json"));if(!await ou.fileExists(N))return new YT({message:"The project must include a policies file ('/config/policies.json')",pluginName:"build-open-api-files",severity:"error"});let Q=await pxr(N,"utf-8"),Re=JSON.parse(Q),Ne=t(async we=>{let wt=lY.join(D,we);if(!await gxr(wt)){s.debug(`Skipping ${we} as it does not use the OpenAPI handler`);return}let xt;try{xt=await aft({sourceDirectory:a,openApiDocPath:wt,policiesConfig:Re,logger:s,environmentType:h,deploymentName:_,urls:b})}catch(tn){if(s.error(tn),tn instanceof SyntaxError||tn instanceof IT.ResolverError||tn instanceof IT.JSONParserError||tn instanceof IT.ParserError||tn instanceof IT.MissingPointerError||tn instanceof lO)return new YT({message:tn.message,location:{file:we,column:0,length:0,line:0,lineText:"",namespace:"",suggestion:""},pluginName:"build-open-api-files",severity:"error"});if(tn instanceof J1)return new YT({...tn.issue,pluginName:"build-open-api-files"});throw tn}let Tr=JSON.stringify(xt,null,2),fn=lY.join(M,we);await mxr(fn,Tr,"utf-8")},"processFile");await Promise.all(ie.map(Ne))}catch(z){return s.error(z),new YT({message:"Error building OpenAPI files",pluginName:"build-open-api-files",severity:"error"})}return new YT})},"buildOpenApiFiles");async function gxr(a){let s=_xr.createReadStream(a),l=hxr.createInterface({input:s,crlfDelay:1/0}),_=!1,h=!1;for await(let b of l)if(b.includes('"openApiSpecHandler"')&&(_=!0),b.includes('"openApiFilePath"')&&(h=!0),_&&h)break;return l.close(),s.destroy(),_&&h}t(gxr,"usesOpenApiHandler");import yxr from"node:fs/promises";import vxr from"node:path";var ovt=t(async function({outputDirectory:a,systemDirectory:s,cacheDirectory:l,logger:_}){return Bu.timeFn("Cleaning output",async()=>{_.debug("Cleaning output");let h=vxr.join(l,"routes");return await Promise.all([a,s,h].map(async b=>{try{await yxr.rm(b,{recursive:!0,force:!0})}catch(D){_.error(D)}})),{warnings:[],errors:[]}})},"cleanOutput");import cvt from"node:fs/promises";var lvt=t(async function({systemDirectory:a,cacheDirectory:s,logger:l}){return Bu.timeFn("Creating system directory",async()=>{l.debug("Creating system directory");try{return await Promise.all([cvt.mkdir(a,{recursive:!0}),cvt.mkdir(s,{recursive:!0})]),{warnings:[],errors:[]}}catch(_){return l.error(_),{warnings:[],errors:[]}}return{warnings:[],errors:[]}})},"createSystemDir");var uvt=t(async function({logger:a}){return Bu.timeFn("Checking for breaking changes",async()=>(a.debug("Checking for breaking changes"),{warnings:[],errors:[]}))},"checkForDeprecations");import{readFile as bxr,writeFile as Sxr}from"node:fs/promises";import Txr from"node:path";var fvt=t(async function({systemDirectory:a,buildId:s,logger:l,config:_,publicZuploEnvironmentVariables:h}){return Bu.timeFn("Generating build data",async()=>{l.debug("Generating build data");let b=await bxr(new URL("../../../package.json",import.meta.url),"utf-8"),D=JSON.parse(b),N={BUILD_ID:s??"",GIT_SHA:process.env.GIT_SHA,TIMESTAMP:new Date().toISOString(),BUILD_ENV:Om.NODE_ENV,ZUPLO_VERSION:D.version,API_VERSION:process.env.API_VERSION,COMPATIBILITY_DATE:_?.compatibilityDate,ACCOUNT_NAME:h?.ZUPLO_ACCOUNT_NAME,PROJECT_NAME:h?.ZUPLO_PROJECT_NAME,ENVIRONMENT_TYPE:h?.ZUPLO_ENVIRONMENT_TYPE,IS_LOCAL_DEVELOPMENT:Om.isLocalDevelopment(),COMPATIBILITY_FLAGS:W6e[_?.compatibilityDate??"none"]},M=JSON.stringify(N,void 0,2),z=Txr.join(a,lle);try{await Sxr(z,M.trimStart(),"utf-8")}catch(re){l.error(re);let ie={message:`Error creating file at ${z}`,pluginName:"buildData",severity:"error"};return{warnings:[],errors:[ie]}}return{warnings:[],errors:[]}})},"generateBuildData");import xxr from"node:fs/promises";import Cxr from"node:path";var Exr=`import { Handler, ServiceProviderImpl } from "@zuplo/runtime";
626
626
  import routeLoader from "zuplo:routes";
627
627
  import * as schemaValidations from "zuplo:schema-validations";
628
628
  import { runtimeInit } from "../modules/zuplo.runtime.ts";
@@ -653,11 +653,11 @@ export default {
653
653
  },
654
654
  };
655
655
  `,_vt=t(async function({systemDirectory:a,logger:s}){return Bu.timeFn("Generating Worker shim",async()=>{s.debug("Generating Worker shim");let l=Cxr.join(a,ule);try{await xxr.writeFile(l,Exr,"utf-8")}catch(_){s.error(_);let h={message:`Error creating file at ${l}`,pluginName:"generate-worker-entry",severity:"error"};return{warnings:[],errors:[h]}}return{warnings:[],errors:[]}})},"generateWorker");import{readFile as Dxr,readdir as kxr}from"node:fs/promises";import pvt from"node:path";var N_e="validate-open-api-files",dvt=t(async function({sourceDirectory:a,logger:s}){return Bu.timeFn("Validating OpenAPI files",async()=>{s.debug("Validating OpenAPI files");let l=pvt.join(a,ub),_=[];try{if(!await JM(a))return new YT({message:"Failed to build project because no open-api file was found on the 'config' folder",pluginName:N_e,severity:"error"});let D=(await kxr(l)).filter(M=>M.endsWith(".oas.json")),N=t(async M=>{let z=pvt.join(l,M);try{M==="zp.oas.json"&&_.push({message:"Open API files cannot be named 'zp.oas.json' since 'zp' is a reserved prefix. Update the file name to solve this build issue.",pluginName:N_e,severity:"error"});let re=await Dxr(z,"utf-8"),ie=JSON.parse(re);if(ie&&ie.paths){let Q=Object.entries(ie.paths).filter(Re=>Re[0]==="zp"||Re[0]==="/zp");if(Q.length>0){let Re=Q.length===1?"includes one route path":`includes '${Q.length}' routes`;_.push({message:`Open API file '${M}' ${Re} that's named '/zp' which is a reserved route name. Updating the route to something other than '/zp' will solve this build issue.`,pluginName:N_e,severity:"error"})}}}catch(re){s.error(re)}},"validateOpenApiFile");await Promise.all(D.map(N))}catch(h){return s.error(h),_.length>0?{errors:_,warnings:[]}:new YT({message:"Failed while validating the open api files in the project",pluginName:N_e,severity:"warning"})}return{errors:_,warnings:[]}})},"validateOpenAPIFiles");import{readFile as Hxr,writeFile as Ovt}from"node:fs/promises";import Gxr from"node:path";var fB=x_(m5e(),1);import{parse as Kxr}from"jsonc-parser";var uB=x_(m5e(),1);var Fvt=t(()=>({include:["modules/**/*",".zuplo/**/*","tests/**/*"],exclude:["./node_modules","./dist"],compilerOptions:{module:uB.ModuleKind.ESNext,target:uB.ScriptTarget.ES2022,moduleResolution:uB.ModuleResolutionKind.Bundler,lib:["ESNext","WebWorker","Webworker.Iterable"],preserveConstEnums:!0,useUnknownInCatchVariables:!1,forceConsistentCasingInFileNames:!0,importHelpers:!0,esModuleInterop:!0,strictNullChecks:!0,noEmit:!0}}),"getZuploTsConfigTemplate");var JO="validate-tsconfig",Lvt=t(async function({sourceDirectory:a,logger:s,command:l,environmentType:_}){return Bu.timeFn("Validate TSConfig",async()=>{s.debug("Validate TSConfig");let h=_==="WORKING_COPY"||l==="dev";try{let b=Fvt(),D=Gxr.join(a,"tsconfig.json");if(!await ou.fileExists(D))return h?(await Ovt(D,JSON.stringify(b,null,2)),{warnings:[{message:"This project does not have a tsconfig.json file. The file has been created for you.",severity:"warning",pluginName:JO,helpUrl:"https://zuplo.com/docs/articles/tsconfig"}],errors:[]}):{warnings:[],errors:[{message:"This project does not have a tsconfig.json file.",severity:"error",pluginName:JO,helpUrl:"https://zuplo.com/docs/articles/tsconfig"}]};let N=await Hxr(D,"utf-8"),M=Kxr(N);if(!(M&&typeof M=="object"&&"compilerOptions"in M))return h?(await Ovt(D,JSON.stringify(b,null,2)),{warnings:[{message:"This project's tsconfig.json file was invalid. A valid file has been written for you.",severity:"warning",pluginName:JO,helpUrl:"https://zuplo.com/docs/articles/tsconfig"}],errors:[]}):{warnings:[],errors:[{message:"This project's tsconfig.json file is invalid. It must have a compilerOptions.",severity:"error",pluginName:JO,helpUrl:"https://zuplo.com/docs/articles/tsconfig"}]};let z=fB.default.convertCompilerOptionsFromJson(M.compilerOptions,a);if(z.errors.length>0)return{warnings:[],errors:z.errors.map(cn=>({severity:"error",pluginName:JO,message:cn.messageText.toString(),detail:"You will need to modify your tsconfig.json file to build this project.",helpUrl:"https://zuplo.com/docs/articles/tsconfig",location:cn.file?{line:cn.file.getLineStarts()[0],length:cn.file.getWidth(),file:cn.file.fileName,column:cn.file.getStart(),lineText:"",namespace:"",suggestion:""}:void 0}))};if(!M||typeof M!="object")throw new TypeError("The userConfigRaw is not an object, this should not happen.");if(!("compilerOptions"in M)||M.compilerOptions===null||M.compilerOptions===void 0||typeof M.compilerOptions!="object")throw new TypeError("The userConfigRaw.compilerOptions property is not an object, this should not happen.");let re=t((cn,Cr,vr)=>`The compiler option '${cn}' should ${Cr===void 0?"not be set":`be set to '${typeof Cr=="string"?Cr:JSON.stringify(Cr)}'`}, it was ${vr===void 0?"not set":`set to '${typeof vr=="string"?vr:JSON.stringify(vr)}'`}`,"getMessage"),ie="ESNext",Q=fB.ModuleKind.ESNext,Re=[];z.options.module!==Q&&Re.push(re("module",ie,M.compilerOptions.module));let Ne="ES2022",we=fB.default.ScriptTarget.ES2022;z.options.target!==we&&Re.push(re("target",Ne,M.compilerOptions.target));let wt="Bundler",xt=fB.default.ModuleResolutionKind.Bundler;z.options.moduleResolution!==xt&&Re.push(re("moduleResolution",wt,M.compilerOptions.moduleResolution));let Tr=["ESNext","WebWorker","Webworker.Iterable"];t(cn=>{let Cr=Tr.map(fs=>fs.toLowerCase()),vr=cn.map(fs=>fs.toLowerCase());return Cr.every(fs=>vr.includes(fs))},"includesAllLibs")(M.compilerOptions.lib??[])||Re.push(re("lib",Tr,M.compilerOptions.lib)),z.options.baseUrl&&Re.push(re("baseUrl",void 0,M.compilerOptions.baseUrl));let tn=[];return Re.length>0&&tn.push({message:"This project's tsconfig.json was not set to the recommended settings. Custom settings may cause build issues. For guidance on how to adjust your settings, please visit: https://zuplo.com/docs/articles/tsconfig",severity:"warning",detail:Re.join(`
656
- `),pluginName:JO,helpUrl:"https://zuplo.com/docs/articles/tsconfig"}),{warnings:tn,errors:[]}}catch(b){s.error(b);let D={message:`Error validating tsconfig.json : ${b.message}`,severity:"error",pluginName:JO};return{warnings:[],errors:[D]}}})},"validateTSConfig");var _B;try{let a=Yxr(new URL("../../package.json",import.meta.url),"utf-8");_B=JSON.parse(a).version}catch{_B="0.0.0"}function Xxr(a){let{ZUPLO:s,ZUPLO_BUILD_ID:l,ZUPLO_BUILD_CONFIG:_}=process.env;if(s&&l&&_){let h;try{h=JSON.parse(_)}catch{throw new Error("Couuld not parse ZUPLO_BUILD_CONFIG")}let b={ZUPLO_PROJECT_ID:h.projectId,ZUPLO_ACCOUNT_NAME:h.accountName,ZUPLO_PROJECT_NAME:h.projectName,ZUPLO_ENVIRONMENT_TYPE:h.environmentType};for(let[D,N]of Object.entries(process.env))D.startsWith("ZUPLO_PUBLIC_")&&(b[D]=N??"");return{...a,buildId:l,...h,publicZuploEnvironmentVariables:b}}return a}t(Xxr,"getBuildConfig");async function h5e(a){let s=performance.now(),{buildId:l,sourceDirectory:_,deploymentName:h=L_e.basename(_),command:b,minify:D,entitlements:N,environmentType:M,logger:z,output:re,noCompile:ie=!1,projectId:Q,deploymentUrl:Re,publicZuploEnvironmentVariables:Ne}=Xxr(a),we=await cB(_),wt=L_e.join(_,KF),xt;if("errors"in we)e5e({output:re.child("api"),buildId:l,runtimeVersion:_B}),xt={status:"Failed",flags:void 0,compatibilityDate:void 0,runtimeVersion:_B,outputPath:wt,buildTime:new Date().toISOString(),buildTimeMs:0,buildId:l,warnings:[],errors:we.errors,metafile:void 0};else{ie||e5e({output:re.child("api"),buildId:l,runtimeVersion:_B,compatibilityDate:we.config.compatibilityDate});let tn={command:b,minify:D,deploymentName:h,sourceDirectory:_,outputDirectory:wt,systemDirectory:L_e.join(_,A3),cacheDirectory:L_e.join(_,"node_modules",A3),buildId:l,logger:z,output:re,config:we.config,publicZuploEnvironmentVariables:Ne,projectId:Q,entitlements:N,environmentType:M,deploymentUrl:Re},cn=[];cn.push(ovt),cn.push(lvt),cn.push(uvt),cn.push(fvt),cn.push(Lvt),cn.push(dvt),cn.push(_vt),ie||cn.push(Q1t),cn.push(avt);let Cr=await nvt(cn,tn),vr=Cr.errors.length>0?GF:Cr.warnings.length>0?q6e:vA,fs=Cr.data.get("metafile");xt={status:vr,compatibilityDate:we.config.compatibilityDate,runtimeVersion:_B,outputPath:wt,buildTime:new Date().toISOString(),buildTimeMs:0,metafile:fs,buildId:l,warnings:Cr.warnings,errors:Cr.errors,flags:we.config.flags}}xt.warnings.length>0&&xt.warnings.forEach(tn=>{z.warn(tn)}),xt.errors.length>0&&xt.errors.forEach(tn=>{z.error(tn)});let{metafile:Tr,...fn}=xt;if(z.debug(fn,"Compiler completed"),xt.buildTimeMs=performance.now()-s,ie||await A_e(_,re.child("api"),xt),process.env.ZUPLO_SHOW_PERF){console.log();let tn=xt.buildTimeMs<2e3?"green":xt.buildTimeMs<5e3?"yellow":"red";console.log(Jf[tn](`Build time: ${xt.buildTimeMs.toFixed(0)}ms`)),Bu.report()}return Bu.clear(),xt}t(h5e,"build");import{randomUUID as Rvt}from"node:crypto";import Qxr from"node:events";import pB from"node:path";import Zxr from"chokidar";import*as Mvt from"esbuild";var g5e=class extends Qxr{static{t(this,"WatchEmitter")}},VA=class{static{t(this,"BuildWatcher")}esbuildContext;emitter=new g5e;envFilesWatcher;outputDirectory;sourceDirectory;command;logger;publicZuploEnvironmentVariables;projectName;buildId;output;constructor({sourceDirectory:s,command:l,logger:_,publicZuploEnvironmentVariables:h={},buildId:b,output:D}){this.sourceDirectory=s,this.command=l,this.outputDirectory=pB.join(s,KF),this.logger=_,this.publicZuploEnvironmentVariables=h,this.projectName=pB.basename(s),this.buildId=b,this.output=D,this.envFilesWatcher=Zxr.watch([pB.join(s,".env"),pB.join(s,".env.zuplo")])}watchEnvFiles(){this.envFilesWatcher.on("change",()=>{this.emitter.emit("reload",null,null)}),this.envFilesWatcher.on("add",()=>{this.emitter.emit("reload",null,null)}),this.envFilesWatcher.on("unlink",()=>{this.emitter.emit("reload",null,null)})}onReload=t(s=>{this.emitter.on("reload",s)},"onReload");async start(){let{sourceDirectory:s}=this;if(this.esbuildContext!==void 0)throw new Error("Watcher cannot be started more than once");let l=await h5e({buildId:this.buildId,output:this.output,sourceDirectory:s,noCompile:!0,command:this.command,publicZuploEnvironmentVariables:this.publicZuploEnvironmentVariables,logger:this.logger,deploymentUrl:void 0}),_=await cY({command:this.command,systemDirectory:pB.join(s,A3),cacheDirectory:pB.join(s,"node_modules",A3),outputDirectory:this.outputDirectory,sourceDirectory:s,logger:this.logger,flags:l.flags,compatibilityDate:l.compatibilityDate}),h=this;_.plugins?.push({name:"on-end",setup(b){b.onEnd(D=>{h.logger.debug("Watcher (build) reloaded");let N=Q7e({buildId:Rvt(),result:D});N.errors.length>0?h.logger.error(N.errors,"Build errors"):h.logger.debug(`Successfully rebuilt watched project. Build id ${N.buildId}`);let M={...N,compatibilityDate:l.compatibilityDate,flags:l.flags};h.emitter.emit("reload",M,null)})}}),this.esbuildContext=await Mvt.context(_);try{if((await this.esbuildContext.rebuild()).errors.length>0){let D={status:"Failed",runtimeVersion:"0.0.0",buildTime:"",buildTimeMs:0,buildId:Rvt(),warnings:[],errors:[],metafile:void 0};await A_e(s,h.output.child("api"),D),this.logger.error(D.errors,"Build errors")}}catch(b){throw await this.close(),b}await this.esbuildContext.watch()}async close(){try{await this.envFilesWatcher.close(),this.esbuildContext&&(await this.esbuildContext.dispose(),this.logger.debug("ESBuild watcher closed"))}catch(s){this.logger.error(s)}}};import{existsSync as dAr}from"node:fs";import{mkdir as mAr,readFile as hAr}from"node:fs/promises";import wY from"node:path";var Nxt=x_(w9e(),1);import{existsSync as Pxt,readFileSync as Axt}from"node:fs";import vde from"node:path";var X9e=x_(J6e(),1);var kxt=x_(qTt(),1);import{Buffer as cAr}from"node:buffer";import lAr from"node:path";import Dxt from"node:child_process";import yde from"node:process";function j9e(a){let s=typeof a=="string"?`
656
+ `),pluginName:JO,helpUrl:"https://zuplo.com/docs/articles/tsconfig"}),{warnings:tn,errors:[]}}catch(b){s.error(b);let D={message:`Error validating tsconfig.json : ${b.message}`,severity:"error",pluginName:JO};return{warnings:[],errors:[D]}}})},"validateTSConfig");var _B;try{let a=Yxr(new URL("../../package.json",import.meta.url),"utf-8");_B=JSON.parse(a).version}catch{_B="0.0.0"}function Xxr(a){let{ZUPLO:s,ZUPLO_BUILD_ID:l,ZUPLO_BUILD_CONFIG:_}=process.env;if(s&&l&&_){let h;try{h=JSON.parse(_)}catch{throw new Error("Couuld not parse ZUPLO_BUILD_CONFIG")}let b={ZUPLO_PROJECT_ID:h.projectId,ZUPLO_ACCOUNT_NAME:h.accountName,ZUPLO_PROJECT_NAME:h.projectName,ZUPLO_ENVIRONMENT_TYPE:h.environmentType};for(let[D,N]of Object.entries(process.env))D.startsWith("ZUPLO_PUBLIC_")&&(b[D]=N??"");return{...a,buildId:l,...h,publicZuploEnvironmentVariables:b}}return a}t(Xxr,"getBuildConfig");async function h5e(a){let s=performance.now(),{buildId:l,sourceDirectory:_,deploymentName:h=L_e.basename(_),command:b,minify:D,entitlements:N,environmentType:M,logger:z,output:re,noCompile:ie=!1,projectId:Q,urls:Re,publicZuploEnvironmentVariables:Ne}=Xxr(a),we=await cB(_),wt=L_e.join(_,KF),xt;if("errors"in we)e5e({output:re.child("api"),buildId:l,runtimeVersion:_B}),xt={status:"Failed",flags:void 0,compatibilityDate:void 0,runtimeVersion:_B,outputPath:wt,buildTime:new Date().toISOString(),buildTimeMs:0,buildId:l,warnings:[],errors:we.errors,metafile:void 0};else{ie||e5e({output:re.child("api"),buildId:l,runtimeVersion:_B,compatibilityDate:we.config.compatibilityDate});let tn={command:b,minify:D,deploymentName:h,sourceDirectory:_,outputDirectory:wt,systemDirectory:L_e.join(_,A3),cacheDirectory:L_e.join(_,"node_modules",A3),buildId:l,logger:z,output:re,config:we.config,publicZuploEnvironmentVariables:Ne,projectId:Q,entitlements:N,environmentType:M,urls:Re},cn=[];cn.push(ovt),cn.push(lvt),cn.push(uvt),cn.push(fvt),cn.push(Lvt),cn.push(dvt),cn.push(_vt),ie||cn.push(Q1t),cn.push(avt);let Cr=await nvt(cn,tn),vr=Cr.errors.length>0?GF:Cr.warnings.length>0?q6e:vA,fs=Cr.data.get("metafile");xt={status:vr,compatibilityDate:we.config.compatibilityDate,runtimeVersion:_B,outputPath:wt,buildTime:new Date().toISOString(),buildTimeMs:0,metafile:fs,buildId:l,warnings:Cr.warnings,errors:Cr.errors,flags:we.config.flags}}xt.warnings.length>0&&xt.warnings.forEach(tn=>{z.warn(tn)}),xt.errors.length>0&&xt.errors.forEach(tn=>{z.error(tn)});let{metafile:Tr,...fn}=xt;if(z.debug(fn,"Compiler completed"),xt.buildTimeMs=performance.now()-s,ie||await A_e(_,re.child("api"),xt),process.env.ZUPLO_SHOW_PERF){console.log();let tn=xt.buildTimeMs<2e3?"green":xt.buildTimeMs<5e3?"yellow":"red";console.log(Jf[tn](`Build time: ${xt.buildTimeMs.toFixed(0)}ms`)),Bu.report()}return Bu.clear(),xt}t(h5e,"build");import{randomUUID as Rvt}from"node:crypto";import Qxr from"node:events";import pB from"node:path";import Zxr from"chokidar";import*as Mvt from"esbuild";var g5e=class extends Qxr{static{t(this,"WatchEmitter")}},VA=class{static{t(this,"BuildWatcher")}esbuildContext;emitter=new g5e;envFilesWatcher;outputDirectory;sourceDirectory;command;logger;publicZuploEnvironmentVariables;projectName;buildId;output;constructor({sourceDirectory:s,command:l,logger:_,publicZuploEnvironmentVariables:h={},buildId:b,output:D}){this.sourceDirectory=s,this.command=l,this.outputDirectory=pB.join(s,KF),this.logger=_,this.publicZuploEnvironmentVariables=h,this.projectName=pB.basename(s),this.buildId=b,this.output=D,this.envFilesWatcher=Zxr.watch([pB.join(s,".env"),pB.join(s,".env.zuplo")])}watchEnvFiles(){this.envFilesWatcher.on("change",()=>{this.emitter.emit("reload",null,null)}),this.envFilesWatcher.on("add",()=>{this.emitter.emit("reload",null,null)}),this.envFilesWatcher.on("unlink",()=>{this.emitter.emit("reload",null,null)})}onReload=t(s=>{this.emitter.on("reload",s)},"onReload");async start(){let{sourceDirectory:s}=this;if(this.esbuildContext!==void 0)throw new Error("Watcher cannot be started more than once");let l=await h5e({buildId:this.buildId,output:this.output,sourceDirectory:s,noCompile:!0,command:this.command,publicZuploEnvironmentVariables:this.publicZuploEnvironmentVariables,logger:this.logger,urls:void 0}),_=await cY({command:this.command,systemDirectory:pB.join(s,A3),cacheDirectory:pB.join(s,"node_modules",A3),outputDirectory:this.outputDirectory,sourceDirectory:s,logger:this.logger,flags:l.flags,compatibilityDate:l.compatibilityDate}),h=this;_.plugins?.push({name:"on-end",setup(b){b.onEnd(D=>{h.logger.debug("Watcher (build) reloaded");let N=Q7e({buildId:Rvt(),result:D});N.errors.length>0?h.logger.error(N.errors,"Build errors"):h.logger.debug(`Successfully rebuilt watched project. Build id ${N.buildId}`);let M={...N,compatibilityDate:l.compatibilityDate,flags:l.flags};h.emitter.emit("reload",M,null)})}}),this.esbuildContext=await Mvt.context(_);try{if((await this.esbuildContext.rebuild()).errors.length>0){let D={status:"Failed",runtimeVersion:"0.0.0",buildTime:"",buildTimeMs:0,buildId:Rvt(),warnings:[],errors:[],metafile:void 0};await A_e(s,h.output.child("api"),D),this.logger.error(D.errors,"Build errors")}}catch(b){throw await this.close(),b}await this.esbuildContext.watch()}async close(){try{await this.envFilesWatcher.close(),this.esbuildContext&&(await this.esbuildContext.dispose(),this.logger.debug("ESBuild watcher closed"))}catch(s){this.logger.error(s)}}};import{existsSync as dAr}from"node:fs";import{mkdir as mAr,readFile as hAr}from"node:fs/promises";import wY from"node:path";var Nxt=x_(w9e(),1);import{existsSync as Pxt,readFileSync as Axt}from"node:fs";import vde from"node:path";var X9e=x_(J6e(),1);var kxt=x_(qTt(),1);import{Buffer as cAr}from"node:buffer";import lAr from"node:path";import Dxt from"node:child_process";import yde from"node:process";function j9e(a){let s=typeof a=="string"?`
657
657
  `:10,l=typeof a=="string"?"\r":13;return a[a.length-1]===s&&(a=a.slice(0,-1)),a[a.length-1]===l&&(a=a.slice(0,-1)),a}t(j9e,"stripFinalNewline");import ude from"node:process";import EY from"node:path";import{fileURLToPath as VTt}from"node:url";function lde(a={}){let{env:s=process.env,platform:l=process.platform}=a;return l!=="win32"?"PATH":Object.keys(s).reverse().find(_=>_.toUpperCase()==="PATH")||"Path"}t(lde,"pathKey");var TPr=t(({cwd:a=ude.cwd(),path:s=ude.env[lde()],preferLocal:l=!0,execPath:_=ude.execPath,addExecPath:h=!0}={})=>{let b=a instanceof URL?VTt(a):a,D=EY.resolve(b),N=[];return l&&xPr(N,D),h&&CPr(N,_,D),[...N,s].join(EY.delimiter)},"npmRunPath"),xPr=t((a,s)=>{let l;for(;l!==s;)a.push(EY.join(s,"node_modules/.bin")),l=s,s=EY.resolve(s,"..")},"applyPreferLocal"),CPr=t((a,s,l)=>{let _=s instanceof URL?VTt(s):s;a.push(EY.resolve(l,_,".."))},"applyExecPath"),WTt=t(({env:a=ude.env,...s}={})=>{a={...a};let l=lde({env:a});return s.path=a[l],a[l]=TPr(s),a},"npmRunPathEnv");var EPr=t((a,s,l,_)=>{if(l==="length"||l==="prototype"||l==="arguments"||l==="caller")return;let h=Object.getOwnPropertyDescriptor(a,l),b=Object.getOwnPropertyDescriptor(s,l);!DPr(h,b)&&_||Object.defineProperty(a,l,b)},"copyProperty"),DPr=t(function(a,s){return a===void 0||a.configurable||a.writable===s.writable&&a.enumerable===s.enumerable&&a.configurable===s.configurable&&(a.writable||a.value===s.value)},"canCopyProperty"),kPr=t((a,s)=>{let l=Object.getPrototypeOf(s);l!==Object.getPrototypeOf(a)&&Object.setPrototypeOf(a,l)},"changePrototype"),wPr=t((a,s)=>`/* Wrapped ${a}*/
658
658
  ${s}`,"wrappedToString"),PPr=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),APr=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),NPr=t((a,s,l)=>{let _=l===""?"":`with ${l.trim()}() `,h=wPr.bind(null,_,s.toString());Object.defineProperty(h,"name",APr),Object.defineProperty(a,"toString",{...PPr,value:h})},"changeToString");function B9e(a,s,{ignoreNonConfigurable:l=!1}={}){let{name:_}=a;for(let h of Reflect.ownKeys(s))EPr(a,s,h,l);return kPr(a,s),NPr(a,s,_),a}t(B9e,"mimicFunction");var fde=new WeakMap,HTt=t((a,s={})=>{if(typeof a!="function")throw new TypeError("Expected a function");let l,_=0,h=a.displayName||a.name||"<anonymous>",b=t(function(...D){if(fde.set(b,++_),_===1)l=a.apply(this,D),a=null;else if(s.throw===!0)throw new Error(`Function \`${h}\` can only be called once`);return l},"onetime");return B9e(b,a),fde.set(b,_),b},"onetime");HTt.callCount=a=>{if(!fde.has(a))throw new Error(`The given function \`${a.name}\` is not wrapped by the \`onetime\` package`);return fde.get(a)};var GTt=HTt;import{constants as LPr}from"os";var KTt=t(function(){let a=U9e-YTt+1;return Array.from({length:a},IPr)},"getRealtimeSignals"),IPr=t(function(a,s){return{name:`SIGRT${s+1}`,number:YTt+s,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}},"getRealtimeSignal"),YTt=34,U9e=64;import{constants as FPr}from"os";var XTt=[{name:"SIGHUP",number:1,action:"terminate",description:"Terminal closed",standard:"posix"},{name:"SIGINT",number:2,action:"terminate",description:"User interruption with CTRL-C",standard:"ansi"},{name:"SIGQUIT",number:3,action:"core",description:"User interruption with CTRL-\\",standard:"posix"},{name:"SIGILL",number:4,action:"core",description:"Invalid machine instruction",standard:"ansi"},{name:"SIGTRAP",number:5,action:"core",description:"Debugger breakpoint",standard:"posix"},{name:"SIGABRT",number:6,action:"core",description:"Aborted",standard:"ansi"},{name:"SIGIOT",number:6,action:"core",description:"Aborted",standard:"bsd"},{name:"SIGBUS",number:7,action:"core",description:"Bus error due to misaligned, non-existing address or paging error",standard:"bsd"},{name:"SIGEMT",number:7,action:"terminate",description:"Command should be emulated but is not implemented",standard:"other"},{name:"SIGFPE",number:8,action:"core",description:"Floating point arithmetic error",standard:"ansi"},{name:"SIGKILL",number:9,action:"terminate",description:"Forced termination",standard:"posix",forced:!0},{name:"SIGUSR1",number:10,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGSEGV",number:11,action:"core",description:"Segmentation fault",standard:"ansi"},{name:"SIGUSR2",number:12,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGPIPE",number:13,action:"terminate",description:"Broken pipe or socket",standard:"posix"},{name:"SIGALRM",number:14,action:"terminate",description:"Timeout or timer",standard:"posix"},{name:"SIGTERM",number:15,action:"terminate",description:"Termination",standard:"ansi"},{name:"SIGSTKFLT",number:16,action:"terminate",description:"Stack is empty or overflowed",standard:"other"},{name:"SIGCHLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"posix"},{name:"SIGCLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"other"},{name:"SIGCONT",number:18,action:"unpause",description:"Unpaused",standard:"posix",forced:!0},{name:"SIGSTOP",number:19,action:"pause",description:"Paused",standard:"posix",forced:!0},{name:"SIGTSTP",number:20,action:"pause",description:'Paused using CTRL-Z or "suspend"',standard:"posix"},{name:"SIGTTIN",number:21,action:"pause",description:"Background process cannot read terminal input",standard:"posix"},{name:"SIGBREAK",number:21,action:"terminate",description:"User interruption with CTRL-BREAK",standard:"other"},{name:"SIGTTOU",number:22,action:"pause",description:"Background process cannot write to terminal output",standard:"posix"},{name:"SIGURG",number:23,action:"ignore",description:"Socket received out-of-band data",standard:"bsd"},{name:"SIGXCPU",number:24,action:"core",description:"Process timed out",standard:"bsd"},{name:"SIGXFSZ",number:25,action:"core",description:"File too big",standard:"bsd"},{name:"SIGVTALRM",number:26,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGPROF",number:27,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGWINCH",number:28,action:"ignore",description:"Terminal window size changed",standard:"bsd"},{name:"SIGIO",number:29,action:"terminate",description:"I/O is available",standard:"other"},{name:"SIGPOLL",number:29,action:"terminate",description:"Watched event",standard:"other"},{name:"SIGINFO",number:29,action:"ignore",description:"Request for process information",standard:"other"},{name:"SIGPWR",number:30,action:"terminate",description:"Device running out of power",standard:"systemv"},{name:"SIGSYS",number:31,action:"core",description:"Invalid system call",standard:"other"},{name:"SIGUNUSED",number:31,action:"terminate",description:"Invalid system call",standard:"other"}];var $9e=t(function(){let a=KTt();return[...XTt,...a].map(OPr)},"getSignals"),OPr=t(function({name:a,number:s,description:l,action:_,forced:h=!1,standard:b}){let{signals:{[a]:D}}=FPr,N=D!==void 0;return{name:a,number:N?D:s,description:l,supported:N,action:_,forced:h,standard:b}},"normalizeSignal");var RPr=t(function(){return $9e().reduce(MPr,{})},"getSignalsByName"),MPr=t(function(a,{name:s,number:l,description:_,supported:h,action:b,forced:D,standard:N}){return{...a,[s]:{name:s,number:l,description:_,supported:h,action:b,forced:D,standard:N}}},"getSignalByName"),QTt=RPr(),jPr=t(function(){let a=$9e(),s=U9e+1,l=Array.from({length:s},(_,h)=>BPr(h,a));return Object.assign({},...l)},"getSignalsByNumber"),BPr=t(function(a,s){let l=UPr(a,s);if(l===void 0)return{};let{name:_,description:h,supported:b,action:D,forced:N,standard:M}=l;return{[a]:{name:_,number:a,description:h,supported:b,action:D,forced:N,standard:M}}},"getSignalByNumber"),UPr=t(function(a,s){let l=s.find(({name:_})=>LPr.signals[_]===a);return l!==void 0?l:s.find(_=>_.number===a)},"findSignalByNumber"),YHr=jPr();var $Pr=t(({timedOut:a,timeout:s,errorCode:l,signal:_,signalDescription:h,exitCode:b,isCanceled:D})=>a?`timed out after ${s} milliseconds`:D?"was canceled":l!==void 0?`failed with ${l}`:_!==void 0?`was killed with ${_} (${h})`:b!==void 0?`failed with exit code ${b}`:"failed","getErrorPrefix"),z9e=t(({stdout:a,stderr:s,all:l,error:_,signal:h,exitCode:b,command:D,escapedCommand:N,timedOut:M,isCanceled:z,killed:re,parsed:{options:{timeout:ie}}})=>{b=b===null?void 0:b,h=h===null?void 0:h;let Q=h===void 0?void 0:QTt[h].description,Re=_&&_.code,we=`Command ${$Pr({timedOut:M,timeout:ie,errorCode:Re,signal:h,signalDescription:Q,exitCode:b,isCanceled:z})}: ${D}`,wt=Object.prototype.toString.call(_)==="[object Error]",xt=wt?`${we}
659
659
  ${_.message}`:we,Tr=[xt,s,a].filter(Boolean).join(`
660
- `);return wt?(_.originalMessage=_.message,_.message=Tr):_=new Error(Tr),_.shortMessage=xt,_.command=D,_.escapedCommand=N,_.exitCode=b,_.signal=h,_.signalDescription=Q,_.stdout=a,_.stderr=s,l!==void 0&&(_.all=l),"bufferedData"in _&&delete _.bufferedData,_.failed=!0,_.timedOut=!!M,_.isCanceled=z,_.killed=re&&!M,_},"makeError");var _de=["stdin","stdout","stderr"],zPr=t(a=>_de.some(s=>a[s]!==void 0),"hasAlias"),ZTt=t(a=>{if(!a)return;let{stdio:s}=a;if(s===void 0)return _de.map(_=>a[_]);if(zPr(a))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${_de.map(_=>`\`${_}\``).join(", ")}`);if(typeof s=="string")return s;if(!Array.isArray(s))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof s}\``);let l=Math.max(s.length,_de.length);return Array.from({length:l},(_,h)=>s[h])},"normalizeStdio");var axt=x_(sxt(),1);import JPr from"node:os";var qPr=1e3*5,oxt=t((a,s="SIGTERM",l={})=>{let _=a(s);return VPr(a,s,l,_),_},"spawnedKill"),VPr=t((a,s,l,_)=>{if(!WPr(s,l,_))return;let h=GPr(l),b=setTimeout(()=>{a("SIGKILL")},h);b.unref&&b.unref()},"setKillTimeout"),WPr=t((a,{forceKillAfterTimeout:s},l)=>HPr(a)&&s!==!1&&l,"shouldForceKill"),HPr=t(a=>a===JPr.constants.signals.SIGTERM||typeof a=="string"&&a.toUpperCase()==="SIGTERM","isSigterm"),GPr=t(({forceKillAfterTimeout:a=!0})=>{if(a===!0)return qPr;if(!Number.isFinite(a)||a<0)throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${a}\` (${typeof a})`);return a},"getForceKillAfterTimeout"),cxt=t((a,s)=>{a.kill()&&(s.isCanceled=!0)},"spawnedCancel"),KPr=t((a,s,l)=>{a.kill(s),l(Object.assign(new Error("Timed out"),{timedOut:!0,signal:s}))},"timeoutKill"),lxt=t((a,{timeout:s,killSignal:l="SIGTERM"},_)=>{if(s===0||s===void 0)return _;let h,b=new Promise((N,M)=>{h=setTimeout(()=>{KPr(a,l,M)},s)}),D=_.finally(()=>{clearTimeout(h)});return Promise.race([b,D])},"setupTimeout"),uxt=t(({timeout:a})=>{if(a!==void 0&&(!Number.isFinite(a)||a<0))throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${a}\` (${typeof a})`)},"validateTimeout"),fxt=t(async(a,{cleanup:s,detached:l},_)=>{if(!s||l)return _;let h=(0,axt.default)(()=>{a.kill()});return _.finally(()=>{h()})},"setExitHandler");function _xt(a){return a!==null&&typeof a=="object"&&typeof a.pipe=="function"}t(_xt,"isStream");var G9e=x_(mxt(),1),yxt=x_(gxt(),1);var vxt=t((a,s)=>{s===void 0||a.stdin===void 0||(_xt(s)?s.pipe(a.stdin):a.stdin.end(s))},"handleInput"),bxt=t((a,{all:s})=>{if(!s||!a.stdout&&!a.stderr)return;let l=(0,yxt.default)();return a.stdout&&l.add(a.stdout),a.stderr&&l.add(a.stderr),l},"makeAllStream"),W9e=t(async(a,s)=>{if(a){a.destroy();try{return await s}catch(l){return l.bufferedData}}},"getBufferedData"),H9e=t((a,{encoding:s,buffer:l,maxBuffer:_})=>{if(!(!a||!l))return s?(0,G9e.default)(a,{encoding:s,maxBuffer:_}):G9e.default.buffer(a,{maxBuffer:_})},"getStreamPromise"),Sxt=t(async({stdout:a,stderr:s,all:l},{encoding:_,buffer:h,maxBuffer:b},D)=>{let N=H9e(a,{encoding:_,buffer:h,maxBuffer:b}),M=H9e(s,{encoding:_,buffer:h,maxBuffer:b}),z=H9e(l,{encoding:_,buffer:h,maxBuffer:b*2});try{return await Promise.all([D,N,M,z])}catch(re){return Promise.all([{error:re,signal:re.signal,timedOut:re.timedOut},W9e(a,N),W9e(s,M),W9e(l,z)])}},"getSpawnedResult");var nAr=(async()=>{})().constructor.prototype,iAr=["then","catch","finally"].map(a=>[a,Reflect.getOwnPropertyDescriptor(nAr,a)]),K9e=t((a,s)=>{for(let[l,_]of iAr){let h=typeof s=="function"?(...b)=>Reflect.apply(_.value,s(),b):_.value.bind(s);Reflect.defineProperty(a,l,{..._,value:h})}return a},"mergePromise"),Txt=t(a=>new Promise((s,l)=>{a.on("exit",(_,h)=>{s({exitCode:_,signal:h})}),a.on("error",_=>{l(_)}),a.stdin&&a.stdin.on("error",_=>{l(_)})}),"getSpawnedPromise");var xxt=t((a,s=[])=>Array.isArray(s)?[a,...s]:[a],"normalizeArgs"),sAr=/^[\w.-]+$/,aAr=/"/g,oAr=t(a=>typeof a!="string"||sAr.test(a)?a:`"${a.replace(aAr,'\\"')}"`,"escapeArg"),Cxt=t((a,s)=>xxt(a,s).join(" "),"joinCommand"),Ext=t((a,s)=>xxt(a,s).map(l=>oAr(l)).join(" "),"getEscapedCommand");var uAr=1e3*1e3*100,fAr=t(({env:a,extendEnv:s,preferLocal:l,localDir:_,execPath:h})=>{let b=s?{...yde.env,...a}:a;return l?WTt({env:b,cwd:_,execPath:h}):b},"getEnv"),_Ar=t((a,s,l={})=>{let _=kxt.default._parse(a,s,l);return a=_.command,s=_.args,l=_.options,l={maxBuffer:uAr,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:l.cwd||yde.cwd(),execPath:yde.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,...l},l.env=fAr(l),l.stdio=ZTt(l),yde.platform==="win32"&&lAr.basename(a,".exe")==="cmd"&&s.unshift("/q"),{file:a,args:s,options:l,parsed:_}},"handleArguments"),Y9e=t((a,s,l)=>typeof s!="string"&&!cAr.isBuffer(s)?l===void 0?void 0:"":a.stripFinalNewline?j9e(s):s,"handleOutput");function wxt(a,s,l){let _=_Ar(a,s,l),h=Cxt(a,s),b=Ext(a,s);uxt(_.options);let D;try{D=Dxt.spawn(_.file,_.args,_.options)}catch(Re){let Ne=new Dxt.ChildProcess,we=Promise.reject(z9e({error:Re,stdout:"",stderr:"",all:"",command:h,escapedCommand:b,parsed:_,timedOut:!1,isCanceled:!1,killed:!1}));return K9e(Ne,we)}let N=Txt(D),M=lxt(D,_.options,N),z=fxt(D,_.options,M),re={isCanceled:!1};D.kill=oxt.bind(null,D.kill.bind(D)),D.cancel=cxt.bind(null,D,re);let Q=GTt(t(async()=>{let[{error:Re,exitCode:Ne,signal:we,timedOut:wt},xt,Tr,fn]=await Sxt(D,_.options,z),tn=Y9e(_.options,xt),cn=Y9e(_.options,Tr),Cr=Y9e(_.options,fn);if(Re||Ne!==0||we!==null){let vr=z9e({error:Re,exitCode:Ne,signal:we,stdout:tn,stderr:cn,all:Cr,command:h,escapedCommand:b,parsed:_,timedOut:wt,isCanceled:re.isCanceled||(_.options.signal?_.options.signal.aborted:!1),killed:D.killed});if(!_.options.reject)return vr;throw vr}return{command:h,escapedCommand:b,exitCode:0,stdout:tn,stderr:cn,all:Cr,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}},"handlePromise"));return vxt(D,_.options.input),D.all=bxt(D,_.options),K9e(D,Q)}t(wxt,"execa");async function bde(a,s){if(a.__ZUPLO_LOG_LEVEL=process.env.__ZUPLO_LOG_LEVEL??process.env.LOG_LEVEL,a.__ZUPLO_LOG_FORMAT=process.env.__ZUPLO_LOG_FORMAT??process.env.LOG_FORMAT,a.LOG_LEVEL=process.env.LOG_LEVEL??process.env.LOG_LEVEL,a.LOG_FORMAT=process.env.LOG_FORMAT??process.env.LOG_FORMAT,a.GIT_SHA=process.env.GIT_SHA??await pAr(s),process.env.__ZUPLO_CONFIG&&(a.__ZUPLO_CONFIG=process.env.__ZUPLO_CONFIG),Pxt(vde.join(s,".env.zuplo"))){let l=Axt(vde.join(s,".env.zuplo"),"utf8"),_=X9e.default.parse(l);for(let h of Object.keys(_))if(a[h]=_[h],h==="ZUPLO_SYSTEM_CONFIGURATIONS"){let b=Buffer.from(pue.decode(_[h])).toString(),D=JSON.parse(b);for(let N of Object.keys(D))a[N]=D[N]}}if(Pxt(vde.join(s,".env"))){let l=Axt(vde.join(s,".env"),"utf8"),_=X9e.default.parse(l);for(let h of Object.keys(_))a[h]=_[h]}for(let l of Object.keys(a))a[l]===void 0&&delete a[l];return a}t(bde,"setEnvironment");async function pAr(a){let s="unknown";try{let{stdout:l}=await wxt("git",["rev-parse","HEAD"],{cwd:a});l.trim().length===40&&(s=l.trim())}catch{}return s}t(pAr,"getGitSha");async function gAr({buildId:a,output:s,sourceDirectory:l,bundledDir:_,port:h,binaryName:b,publicZuploEnvironmentVariables:D,logger:N,handleRuntimeStdio:M}){if(_){let re=wY.join(l,_,"modules.json");if(!dAr(re))throw new Error("The bundled-dir does not contain a modules.json file.");let ie=await hAr(re,"utf-8").then(JSON.parse),Q=await cB(l);return Q.status===vA?new Promise((Re,Ne)=>{z(Q.config.compatibilityDate,wY.join(l,_),ie,Re,M)().catch(we=>{N.error(we),Ne(we)})}):(N.warn("Failed to get Zuplo config. Using default compatibility date."),new Promise((Re,Ne)=>{z(void 0,l,ie,Re,M)().catch(we=>{N.error(we),Ne(we)})}))}else{let re=new VA({buildId:a,output:s,sourceDirectory:l,command:"dev",logger:N,publicZuploEnvironmentVariables:D??{ZUPLO_ENVIRONMENT_TYPE:"LOCAL_DEVELOPMENT"},deploymentUrl:void 0});try{await re.start()}catch{N.info("Ran into irrecoverable error while building. Fix the error and rerun the command."),process.exit(1)}return new Promise((ie,Q)=>{re.onReload((Re,Ne)=>{(Ne||Re&&Re.errors&&Re.errors.length>0)&&Q(Ne??Re?.errors),z(Re?.compatibilityDate,wY.join(l,"dist"),Uj(l,Re?.metafile),ie,M)().catch(we=>{N.error(we),Q(we)})})})}function z(re,ie,Q,Re,Ne){return async()=>{let we={};await bde(we,l);let wt=new Nxt.ZuploWorkerd({compatibilityDate:re,scriptDirectory:ie,modules:Q,port:h??Om.DEV_SERVER_PORT,bindings:we,handleRuntimeStdio:Ne}),xt=b??"compiled-zup",Tr=wY.join(l,"dist");await mAr(Tr,{recursive:!0}),await wt.compileBinary({binaryPath:wY.join(l,"dist",xt)}),await wt.dispose(),Re(void 0)}}t(z,"compile")}t(gAr,"compileWorkerdServer");var Ixt=x_(w9e(),1);import vAr from"node:path";import yAr from"node:net";function PY(a,s){return new Promise(l=>{let _=new yAr.Socket;_.connect(s,a),_.on("connect",()=>{_.destroy(),l(!1)}),_.on("error",()=>{_.destroy(),l(!0)})})}t(PY,"isPortAvailable");var Sde=class{static{t(this,"WorkerdServer")}sourceDirectory;port;debugPort;buildWatcher;workerd;logger;output;handleRuntimeStdio;onReload;constructor(s){this.sourceDirectory=s.sourceDirectory,this.port=s.port??Om.DEV_SERVER_PORT,this.debugPort=s.debugPort,this.logger=s.logger,this.output=s.output,this.handleRuntimeStdio=s.handleRuntimeStdio,this.onReload=s.onReload,s.zupTestMode||(this.buildWatcher=new VA({...s,logger:this.logger,publicZuploEnvironmentVariables:s.publicZuploEnvironmentVariables??{ZUPLO_ENVIRONMENT_TYPE:"LOCAL_DEVELOPMENT"},deploymentUrl:void 0}),this.buildWatcher.watchEnvFiles())}async start(){if(!await PY("localhost",this.port))throw new Error(`Port ${this.port} is currently in use. Please use a different port.`);if(this.buildWatcher)try{await this.buildWatcher.start()}catch(l){this.output.child("api").error(l.toString());let _="Ran into irrecoverable error while starting watcher. Fix the error and restart the server.";this.output.child("api").error(_),this.logger?.info(_),process.exit(1)}await this.startOrReload(),this.buildWatcher?.onReload((l,_)=>{_||l&&l.errors&&l.errors.length>0||(this.onReload(l,_),this.startOrReload(l).catch(h=>{this.output.child("api").error(h.toString()),this.logger?.error(h)}))})}async startOrReload(s){try{let l={};await bde(l,this.sourceDirectory),await this.workerd?.dispose(),this.workerd=new Ixt.ZuploWorkerd({compatibilityDate:s?.compatibilityDate,scriptDirectory:vAr.join(this.sourceDirectory,"dist"),modules:Uj(this.sourceDirectory,s?.metafile),port:this.port,inspectorPort:this.debugPort??void 0,bindings:l,handleRuntimeStdio:this.handleRuntimeStdio}),await this.workerd.serve()}catch(l){this.logger?.debug(l)}}async stop(){await this.buildWatcher?.close(),await this.workerd?.dispose()}};import{fileURLToPath as Mxt}from"node:url";import{Readable as Fxt}from"node:stream";import Oxt from"node:assert";import bAr from"node:child_process";import SAr from"node:fs";import Tde from"node:os";import TAr from"node:path";function Lxt(a,s){let l=import.meta.resolve(a),_=new URL(".",l),h=new URL(s,_);if(SAr.existsSync(h))return Mxt(h)}t(Lxt,"getValidExecutablePath");function xAr(){let a=Tde.platform()==="win32"?"deno.exe":"deno",s=Lxt("deno/package.json",a);if(s)return s;let l=CAr(),_=Lxt(`@deno/${l}/package.json`,a);if(_)return _;throw new Error("Failed to locate the managed-dedicated server executable.")}t(xAr,"locateDenoExecutable");function CAr(){let a=Tde.platform();return a==="linux"?a+"-"+Rxt()+"-glibc":a+"-"+Rxt()}t(CAr,"getTarget");function Rxt(){let a=Tde.arch();if(a!=="arm64"&&a!=="x64")throw new Error("Unsupported architecture "+Tde.arch()+". Only x64 and aarch64 binaries are available.");return a}t(Rxt,"getArch");var xde=class{static{t(this,"ZenoServer")}serverProcess;debugPort;processExitPromise;logger;output;buildWatcher;onReload;handleRuntimeStdio;denoExecutablePath;constructor(s){this.debugPort=s.debugPort,this.logger=s.logger,this.output=s.output,this.onReload=s.onReload,this.handleRuntimeStdio=s.handleRuntimeStdio,s.zupTestMode||(this.buildWatcher=new VA({sourceDirectory:s.sourceDirectory,command:"dev",logger:s.logger,publicZuploEnvironmentVariables:s.publicZuploEnvironmentVariables??{ZUPLO_ENVIRONMENT_TYPE:"LOCAL_DEVELOPMENT"},buildId:"dev",output:s.output,deploymentUrl:void 0}),this.buildWatcher.watchEnvFiles()),this.denoExecutablePath=xAr()}getServeArgs(){let s=`${TAr.dirname(Mxt(import.meta.url))}/zeno.js`,l=["run","--allow-read","--allow-net","--allow-env","--allow-write"];return this.debugPort&&l.push(`--inspect=127.0.0.1:${this.debugPort}`),l.push(s),l}async getUnavailablePorts(){let s=[];return this.debugPort&&!await PY("127.0.0.1",this.debugPort)&&s.push(this.debugPort),await PY("127.0.0.1",9e3)||s.push(9e3),s}async start(){let s=await this.getUnavailablePorts();if(s.length>0)throw new Error("The following ports are not available: "+s.join(", "));if(this.buildWatcher)try{await this.buildWatcher.start()}catch(l){this.output.child("api").error(l.toString());let _="Ran into irrecoverable error while starting watcher. Fix the error and restart the server.";this.output.child("api").error(_),this.logger?.info(_),process.exit(1)}await this.startOrReload(),this.buildWatcher?.onReload((l,_)=>{_||l&&l.errors&&l.errors.length>0||(this.onReload(l,_),this.startOrReload().catch(h=>{this.output.child("api").error(h.toString()),this.logger?.error(h)}))})}async startOrReload(){try{await this.dispose(),this.logger?.info("Starting managed-dedicated local server");let s=this.getServeArgs();this.serverProcess=bAr.spawn(this.denoExecutablePath,s,{stdio:["pipe","pipe","pipe"],env:{...process.env,FORCE_COLOR:"1"}}),Oxt(this.serverProcess.stdout instanceof Fxt),Oxt(this.serverProcess.stderr instanceof Fxt),this.processExitPromise=this.waitForExit(),this.handleRuntimeStdio(this.serverProcess.stdout,this.serverProcess.stderr)}catch(s){this.logger?.debug(s)}}waitForExit(){return new Promise(s=>{this.serverProcess?.once("exit",s)})}dispose(){return this.serverProcess?.kill("SIGKILL"),this.processExitPromise}async stop(){await this.dispose(),await this.buildWatcher?.close()}};async function EAr(a){let s=await cB(a),l=!1;return s.status===vA&&(l=s.config.flags?.managedDedicatedFlags?.useZeno??!1),l||process.env.ZUPLO_DEV_RUNTIME==="zeno"}t(EAr,"useZeno");async function DAr({sourceDirectory:a,port:s,debugPort:l,publicZuploEnvironmentVariables:_,logger:h,output:b,buildId:D,onReload:N,handleRuntimeStdio:M}){process.env.ZUPLO_IS_LOCAL_DEVELOPMENT="true";let z;await EAr(a)?(h.debug("Starting managed-dedicated local dev server."),z=new xde({sourceDirectory:a,debugPort:l,logger:h,output:b,publicZuploEnvironmentVariables:_,onReload:N,handleRuntimeStdio:M})):(h.debug("Starting edge local dev server."),z=new Sde({sourceDirectory:a,command:"dev",port:s,debugPort:l,publicZuploEnvironmentVariables:_,logger:h,output:b,buildId:D,onReload:N,handleRuntimeStdio:M})),await z.start();async function re(){await z.stop()}t(re,"handle"),process.on("SIGTERM",re),process.on("SIGINT",re)}t(DAr,"startDevServer");var fCt=x_(Uxt(),1),_Ct=x_(lCt(),1);import{readFile as o6r}from"node:fs/promises";import LY from"node:path";var s6r=new RegExp("^((https|http)://)?[a-zA-Z0-9]{3}\\.[a-zA-Z0-9][a-zA-Z0-9]{0,61}?[a-zA-Z0-9]\\.(com|net|cn|cc)(:[0-9]{1,4})?/$"),a6r={concat(a,s){return LY.join(a,s)},resolve(a){return this.isAbsolute(a)?this.normalize(a):this.normalize(this.concat(process.cwd(),a))},normalize(a){let s=LY.normalize(a),l=LY.sep,_=[],h=0;return s.split(l).reverse().filter(D=>D!==".").forEach(D=>{D===".."?h++:h===0?_.push(D):h--}),_.reverse().join(l)},isData(a){return a.startsWith("data:")},isURL(a){return s6r.test(a)},isAbsolute(a){return LY.isAbsolute(a)},relativeToFile(a,s){if(this.isData(a)||this.isAbsolute(s))return this.normalize(s);{let l=LY.dirname(a);return this.normalize(this.concat(l,s))}}},Fde=a6r;var uCt=t(a=>{let s=t(l=>l in s.cache?s.cache[l]:s.cache[l]=a(l),"m");return s.forgetEverything=()=>{s.cache=Object.create(null)},s.cache=Object.create(null),s},"memoize");function lLe(a){let s=uCt(async D=>await l(D,await a(D)));async function l(D,N){if(N===void 0)return s(Fde.resolve(D));let M,z,re=t(async Q=>(z=z||await _(ie))(Q),"_resolve"),ie={path:D,text:N,get lines(){return M=M||N.split(`
660
+ `);return wt?(_.originalMessage=_.message,_.message=Tr):_=new Error(Tr),_.shortMessage=xt,_.command=D,_.escapedCommand=N,_.exitCode=b,_.signal=h,_.signalDescription=Q,_.stdout=a,_.stderr=s,l!==void 0&&(_.all=l),"bufferedData"in _&&delete _.bufferedData,_.failed=!0,_.timedOut=!!M,_.isCanceled=z,_.killed=re&&!M,_},"makeError");var _de=["stdin","stdout","stderr"],zPr=t(a=>_de.some(s=>a[s]!==void 0),"hasAlias"),ZTt=t(a=>{if(!a)return;let{stdio:s}=a;if(s===void 0)return _de.map(_=>a[_]);if(zPr(a))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${_de.map(_=>`\`${_}\``).join(", ")}`);if(typeof s=="string")return s;if(!Array.isArray(s))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof s}\``);let l=Math.max(s.length,_de.length);return Array.from({length:l},(_,h)=>s[h])},"normalizeStdio");var axt=x_(sxt(),1);import JPr from"node:os";var qPr=1e3*5,oxt=t((a,s="SIGTERM",l={})=>{let _=a(s);return VPr(a,s,l,_),_},"spawnedKill"),VPr=t((a,s,l,_)=>{if(!WPr(s,l,_))return;let h=GPr(l),b=setTimeout(()=>{a("SIGKILL")},h);b.unref&&b.unref()},"setKillTimeout"),WPr=t((a,{forceKillAfterTimeout:s},l)=>HPr(a)&&s!==!1&&l,"shouldForceKill"),HPr=t(a=>a===JPr.constants.signals.SIGTERM||typeof a=="string"&&a.toUpperCase()==="SIGTERM","isSigterm"),GPr=t(({forceKillAfterTimeout:a=!0})=>{if(a===!0)return qPr;if(!Number.isFinite(a)||a<0)throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${a}\` (${typeof a})`);return a},"getForceKillAfterTimeout"),cxt=t((a,s)=>{a.kill()&&(s.isCanceled=!0)},"spawnedCancel"),KPr=t((a,s,l)=>{a.kill(s),l(Object.assign(new Error("Timed out"),{timedOut:!0,signal:s}))},"timeoutKill"),lxt=t((a,{timeout:s,killSignal:l="SIGTERM"},_)=>{if(s===0||s===void 0)return _;let h,b=new Promise((N,M)=>{h=setTimeout(()=>{KPr(a,l,M)},s)}),D=_.finally(()=>{clearTimeout(h)});return Promise.race([b,D])},"setupTimeout"),uxt=t(({timeout:a})=>{if(a!==void 0&&(!Number.isFinite(a)||a<0))throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${a}\` (${typeof a})`)},"validateTimeout"),fxt=t(async(a,{cleanup:s,detached:l},_)=>{if(!s||l)return _;let h=(0,axt.default)(()=>{a.kill()});return _.finally(()=>{h()})},"setExitHandler");function _xt(a){return a!==null&&typeof a=="object"&&typeof a.pipe=="function"}t(_xt,"isStream");var G9e=x_(mxt(),1),yxt=x_(gxt(),1);var vxt=t((a,s)=>{s===void 0||a.stdin===void 0||(_xt(s)?s.pipe(a.stdin):a.stdin.end(s))},"handleInput"),bxt=t((a,{all:s})=>{if(!s||!a.stdout&&!a.stderr)return;let l=(0,yxt.default)();return a.stdout&&l.add(a.stdout),a.stderr&&l.add(a.stderr),l},"makeAllStream"),W9e=t(async(a,s)=>{if(a){a.destroy();try{return await s}catch(l){return l.bufferedData}}},"getBufferedData"),H9e=t((a,{encoding:s,buffer:l,maxBuffer:_})=>{if(!(!a||!l))return s?(0,G9e.default)(a,{encoding:s,maxBuffer:_}):G9e.default.buffer(a,{maxBuffer:_})},"getStreamPromise"),Sxt=t(async({stdout:a,stderr:s,all:l},{encoding:_,buffer:h,maxBuffer:b},D)=>{let N=H9e(a,{encoding:_,buffer:h,maxBuffer:b}),M=H9e(s,{encoding:_,buffer:h,maxBuffer:b}),z=H9e(l,{encoding:_,buffer:h,maxBuffer:b*2});try{return await Promise.all([D,N,M,z])}catch(re){return Promise.all([{error:re,signal:re.signal,timedOut:re.timedOut},W9e(a,N),W9e(s,M),W9e(l,z)])}},"getSpawnedResult");var nAr=(async()=>{})().constructor.prototype,iAr=["then","catch","finally"].map(a=>[a,Reflect.getOwnPropertyDescriptor(nAr,a)]),K9e=t((a,s)=>{for(let[l,_]of iAr){let h=typeof s=="function"?(...b)=>Reflect.apply(_.value,s(),b):_.value.bind(s);Reflect.defineProperty(a,l,{..._,value:h})}return a},"mergePromise"),Txt=t(a=>new Promise((s,l)=>{a.on("exit",(_,h)=>{s({exitCode:_,signal:h})}),a.on("error",_=>{l(_)}),a.stdin&&a.stdin.on("error",_=>{l(_)})}),"getSpawnedPromise");var xxt=t((a,s=[])=>Array.isArray(s)?[a,...s]:[a],"normalizeArgs"),sAr=/^[\w.-]+$/,aAr=/"/g,oAr=t(a=>typeof a!="string"||sAr.test(a)?a:`"${a.replace(aAr,'\\"')}"`,"escapeArg"),Cxt=t((a,s)=>xxt(a,s).join(" "),"joinCommand"),Ext=t((a,s)=>xxt(a,s).map(l=>oAr(l)).join(" "),"getEscapedCommand");var uAr=1e3*1e3*100,fAr=t(({env:a,extendEnv:s,preferLocal:l,localDir:_,execPath:h})=>{let b=s?{...yde.env,...a}:a;return l?WTt({env:b,cwd:_,execPath:h}):b},"getEnv"),_Ar=t((a,s,l={})=>{let _=kxt.default._parse(a,s,l);return a=_.command,s=_.args,l=_.options,l={maxBuffer:uAr,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:l.cwd||yde.cwd(),execPath:yde.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,...l},l.env=fAr(l),l.stdio=ZTt(l),yde.platform==="win32"&&lAr.basename(a,".exe")==="cmd"&&s.unshift("/q"),{file:a,args:s,options:l,parsed:_}},"handleArguments"),Y9e=t((a,s,l)=>typeof s!="string"&&!cAr.isBuffer(s)?l===void 0?void 0:"":a.stripFinalNewline?j9e(s):s,"handleOutput");function wxt(a,s,l){let _=_Ar(a,s,l),h=Cxt(a,s),b=Ext(a,s);uxt(_.options);let D;try{D=Dxt.spawn(_.file,_.args,_.options)}catch(Re){let Ne=new Dxt.ChildProcess,we=Promise.reject(z9e({error:Re,stdout:"",stderr:"",all:"",command:h,escapedCommand:b,parsed:_,timedOut:!1,isCanceled:!1,killed:!1}));return K9e(Ne,we)}let N=Txt(D),M=lxt(D,_.options,N),z=fxt(D,_.options,M),re={isCanceled:!1};D.kill=oxt.bind(null,D.kill.bind(D)),D.cancel=cxt.bind(null,D,re);let Q=GTt(t(async()=>{let[{error:Re,exitCode:Ne,signal:we,timedOut:wt},xt,Tr,fn]=await Sxt(D,_.options,z),tn=Y9e(_.options,xt),cn=Y9e(_.options,Tr),Cr=Y9e(_.options,fn);if(Re||Ne!==0||we!==null){let vr=z9e({error:Re,exitCode:Ne,signal:we,stdout:tn,stderr:cn,all:Cr,command:h,escapedCommand:b,parsed:_,timedOut:wt,isCanceled:re.isCanceled||(_.options.signal?_.options.signal.aborted:!1),killed:D.killed});if(!_.options.reject)return vr;throw vr}return{command:h,escapedCommand:b,exitCode:0,stdout:tn,stderr:cn,all:Cr,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}},"handlePromise"));return vxt(D,_.options.input),D.all=bxt(D,_.options),K9e(D,Q)}t(wxt,"execa");async function bde(a,s){if(a.__ZUPLO_LOG_LEVEL=process.env.__ZUPLO_LOG_LEVEL??process.env.LOG_LEVEL,a.__ZUPLO_LOG_FORMAT=process.env.__ZUPLO_LOG_FORMAT??process.env.LOG_FORMAT,a.LOG_LEVEL=process.env.LOG_LEVEL??process.env.LOG_LEVEL,a.LOG_FORMAT=process.env.LOG_FORMAT??process.env.LOG_FORMAT,a.GIT_SHA=process.env.GIT_SHA??await pAr(s),process.env.__ZUPLO_CONFIG&&(a.__ZUPLO_CONFIG=process.env.__ZUPLO_CONFIG),Pxt(vde.join(s,".env.zuplo"))){let l=Axt(vde.join(s,".env.zuplo"),"utf8"),_=X9e.default.parse(l);for(let h of Object.keys(_))if(a[h]=_[h],h==="ZUPLO_SYSTEM_CONFIGURATIONS"){let b=Buffer.from(pue.decode(_[h])).toString(),D=JSON.parse(b);for(let N of Object.keys(D))a[N]=D[N]}}if(Pxt(vde.join(s,".env"))){let l=Axt(vde.join(s,".env"),"utf8"),_=X9e.default.parse(l);for(let h of Object.keys(_))a[h]=_[h]}for(let l of Object.keys(a))a[l]===void 0&&delete a[l];return a}t(bde,"setEnvironment");async function pAr(a){let s="unknown";try{let{stdout:l}=await wxt("git",["rev-parse","HEAD"],{cwd:a});l.trim().length===40&&(s=l.trim())}catch{}return s}t(pAr,"getGitSha");async function gAr({buildId:a,output:s,sourceDirectory:l,bundledDir:_,port:h,binaryName:b,publicZuploEnvironmentVariables:D,logger:N,handleRuntimeStdio:M}){if(_){let re=wY.join(l,_,"modules.json");if(!dAr(re))throw new Error("The bundled-dir does not contain a modules.json file.");let ie=await hAr(re,"utf-8").then(JSON.parse),Q=await cB(l);return Q.status===vA?new Promise((Re,Ne)=>{z(Q.config.compatibilityDate,wY.join(l,_),ie,Re,M)().catch(we=>{N.error(we),Ne(we)})}):(N.warn("Failed to get Zuplo config. Using default compatibility date."),new Promise((Re,Ne)=>{z(void 0,l,ie,Re,M)().catch(we=>{N.error(we),Ne(we)})}))}else{let re=new VA({buildId:a,output:s,sourceDirectory:l,command:"dev",logger:N,publicZuploEnvironmentVariables:D??{ZUPLO_ENVIRONMENT_TYPE:"LOCAL_DEVELOPMENT"},urls:void 0});try{await re.start()}catch{N.info("Ran into irrecoverable error while building. Fix the error and rerun the command."),process.exit(1)}return new Promise((ie,Q)=>{re.onReload((Re,Ne)=>{(Ne||Re&&Re.errors&&Re.errors.length>0)&&Q(Ne??Re?.errors),z(Re?.compatibilityDate,wY.join(l,"dist"),Uj(l,Re?.metafile),ie,M)().catch(we=>{N.error(we),Q(we)})})})}function z(re,ie,Q,Re,Ne){return async()=>{let we={};await bde(we,l);let wt=new Nxt.ZuploWorkerd({compatibilityDate:re,scriptDirectory:ie,modules:Q,port:h??Om.DEV_SERVER_PORT,bindings:we,handleRuntimeStdio:Ne}),xt=b??"compiled-zup",Tr=wY.join(l,"dist");await mAr(Tr,{recursive:!0}),await wt.compileBinary({binaryPath:wY.join(l,"dist",xt)}),await wt.dispose(),Re(void 0)}}t(z,"compile")}t(gAr,"compileWorkerdServer");var Ixt=x_(w9e(),1);import vAr from"node:path";import yAr from"node:net";function PY(a,s){return new Promise(l=>{let _=new yAr.Socket;_.connect(s,a),_.on("connect",()=>{_.destroy(),l(!1)}),_.on("error",()=>{_.destroy(),l(!0)})})}t(PY,"isPortAvailable");var Sde=class{static{t(this,"WorkerdServer")}sourceDirectory;port;debugPort;buildWatcher;workerd;logger;output;handleRuntimeStdio;onReload;constructor(s){this.sourceDirectory=s.sourceDirectory,this.port=s.port??Om.DEV_SERVER_PORT,this.debugPort=s.debugPort,this.logger=s.logger,this.output=s.output,this.handleRuntimeStdio=s.handleRuntimeStdio,this.onReload=s.onReload,s.zupTestMode||(this.buildWatcher=new VA({...s,logger:this.logger,publicZuploEnvironmentVariables:s.publicZuploEnvironmentVariables??{ZUPLO_ENVIRONMENT_TYPE:"LOCAL_DEVELOPMENT"},urls:void 0}),this.buildWatcher.watchEnvFiles())}async start(){if(!await PY("localhost",this.port))throw new Error(`Port ${this.port} is currently in use. Please use a different port.`);if(this.buildWatcher)try{await this.buildWatcher.start()}catch(l){this.output.child("api").error(l.toString());let _="Ran into irrecoverable error while starting watcher. Fix the error and restart the server.";this.output.child("api").error(_),this.logger?.info(_),process.exit(1)}await this.startOrReload(),this.buildWatcher?.onReload((l,_)=>{_||l&&l.errors&&l.errors.length>0||(this.onReload(l,_),this.startOrReload(l).catch(h=>{this.output.child("api").error(h.toString()),this.logger?.error(h)}))})}async startOrReload(s){try{let l={};await bde(l,this.sourceDirectory),await this.workerd?.dispose(),this.workerd=new Ixt.ZuploWorkerd({compatibilityDate:s?.compatibilityDate,scriptDirectory:vAr.join(this.sourceDirectory,"dist"),modules:Uj(this.sourceDirectory,s?.metafile),port:this.port,inspectorPort:this.debugPort??void 0,bindings:l,handleRuntimeStdio:this.handleRuntimeStdio}),await this.workerd.serve()}catch(l){this.logger?.debug(l)}}async stop(){await this.buildWatcher?.close(),await this.workerd?.dispose()}};import{fileURLToPath as Mxt}from"node:url";import{Readable as Fxt}from"node:stream";import Oxt from"node:assert";import bAr from"node:child_process";import SAr from"node:fs";import Tde from"node:os";import TAr from"node:path";function Lxt(a,s){let l=import.meta.resolve(a),_=new URL(".",l),h=new URL(s,_);if(SAr.existsSync(h))return Mxt(h)}t(Lxt,"getValidExecutablePath");function xAr(){let a=Tde.platform()==="win32"?"deno.exe":"deno",s=Lxt("deno/package.json",a);if(s)return s;let l=CAr(),_=Lxt(`@deno/${l}/package.json`,a);if(_)return _;throw new Error("Failed to locate the managed-dedicated server executable.")}t(xAr,"locateDenoExecutable");function CAr(){let a=Tde.platform();return a==="linux"?a+"-"+Rxt()+"-glibc":a+"-"+Rxt()}t(CAr,"getTarget");function Rxt(){let a=Tde.arch();if(a!=="arm64"&&a!=="x64")throw new Error("Unsupported architecture "+Tde.arch()+". Only x64 and aarch64 binaries are available.");return a}t(Rxt,"getArch");var xde=class{static{t(this,"ZenoServer")}serverProcess;debugPort;processExitPromise;logger;output;buildWatcher;onReload;handleRuntimeStdio;denoExecutablePath;constructor(s){this.debugPort=s.debugPort,this.logger=s.logger,this.output=s.output,this.onReload=s.onReload,this.handleRuntimeStdio=s.handleRuntimeStdio,s.zupTestMode||(this.buildWatcher=new VA({sourceDirectory:s.sourceDirectory,command:"dev",logger:s.logger,publicZuploEnvironmentVariables:s.publicZuploEnvironmentVariables??{ZUPLO_ENVIRONMENT_TYPE:"LOCAL_DEVELOPMENT"},buildId:"dev",output:s.output,urls:void 0}),this.buildWatcher.watchEnvFiles()),this.denoExecutablePath=xAr()}getServeArgs(){let s=`${TAr.dirname(Mxt(import.meta.url))}/zeno.js`,l=["run","--allow-read","--allow-net","--allow-env","--allow-write"];return this.debugPort&&l.push(`--inspect=127.0.0.1:${this.debugPort}`),l.push(s),l}async getUnavailablePorts(){let s=[];return this.debugPort&&!await PY("127.0.0.1",this.debugPort)&&s.push(this.debugPort),await PY("127.0.0.1",9e3)||s.push(9e3),s}async start(){let s=await this.getUnavailablePorts();if(s.length>0)throw new Error("The following ports are not available: "+s.join(", "));if(this.buildWatcher)try{await this.buildWatcher.start()}catch(l){this.output.child("api").error(l.toString());let _="Ran into irrecoverable error while starting watcher. Fix the error and restart the server.";this.output.child("api").error(_),this.logger?.info(_),process.exit(1)}await this.startOrReload(),this.buildWatcher?.onReload((l,_)=>{_||l&&l.errors&&l.errors.length>0||(this.onReload(l,_),this.startOrReload().catch(h=>{this.output.child("api").error(h.toString()),this.logger?.error(h)}))})}async startOrReload(){try{await this.dispose(),this.logger?.info("Starting managed-dedicated local server");let s=this.getServeArgs();this.serverProcess=bAr.spawn(this.denoExecutablePath,s,{stdio:["pipe","pipe","pipe"],env:{...process.env,FORCE_COLOR:"1"}}),Oxt(this.serverProcess.stdout instanceof Fxt),Oxt(this.serverProcess.stderr instanceof Fxt),this.processExitPromise=this.waitForExit(),this.handleRuntimeStdio(this.serverProcess.stdout,this.serverProcess.stderr)}catch(s){this.logger?.debug(s)}}waitForExit(){return new Promise(s=>{this.serverProcess?.once("exit",s)})}dispose(){return this.serverProcess?.kill("SIGKILL"),this.processExitPromise}async stop(){await this.dispose(),await this.buildWatcher?.close()}};async function EAr(a){let s=await cB(a),l=!1;return s.status===vA&&(l=s.config.flags?.managedDedicatedFlags?.useZeno??!1),l||process.env.ZUPLO_DEV_RUNTIME==="zeno"}t(EAr,"useZeno");async function DAr({sourceDirectory:a,port:s,debugPort:l,publicZuploEnvironmentVariables:_,logger:h,output:b,buildId:D,onReload:N,handleRuntimeStdio:M}){process.env.ZUPLO_IS_LOCAL_DEVELOPMENT="true";let z;await EAr(a)?(h.debug("Starting managed-dedicated local dev server."),z=new xde({sourceDirectory:a,debugPort:l,logger:h,output:b,publicZuploEnvironmentVariables:_,onReload:N,handleRuntimeStdio:M})):(h.debug("Starting edge local dev server."),z=new Sde({sourceDirectory:a,command:"dev",port:s,debugPort:l,publicZuploEnvironmentVariables:_,logger:h,output:b,buildId:D,onReload:N,handleRuntimeStdio:M})),await z.start();async function re(){await z.stop()}t(re,"handle"),process.on("SIGTERM",re),process.on("SIGINT",re)}t(DAr,"startDevServer");var fCt=x_(Uxt(),1),_Ct=x_(lCt(),1);import{readFile as o6r}from"node:fs/promises";import LY from"node:path";var s6r=new RegExp("^((https|http)://)?[a-zA-Z0-9]{3}\\.[a-zA-Z0-9][a-zA-Z0-9]{0,61}?[a-zA-Z0-9]\\.(com|net|cn|cc)(:[0-9]{1,4})?/$"),a6r={concat(a,s){return LY.join(a,s)},resolve(a){return this.isAbsolute(a)?this.normalize(a):this.normalize(this.concat(process.cwd(),a))},normalize(a){let s=LY.normalize(a),l=LY.sep,_=[],h=0;return s.split(l).reverse().filter(D=>D!==".").forEach(D=>{D===".."?h++:h===0?_.push(D):h--}),_.reverse().join(l)},isData(a){return a.startsWith("data:")},isURL(a){return s6r.test(a)},isAbsolute(a){return LY.isAbsolute(a)},relativeToFile(a,s){if(this.isData(a)||this.isAbsolute(s))return this.normalize(s);{let l=LY.dirname(a);return this.normalize(this.concat(l,s))}}},Fde=a6r;var uCt=t(a=>{let s=t(l=>l in s.cache?s.cache[l]:s.cache[l]=a(l),"m");return s.forgetEverything=()=>{s.cache=Object.create(null)},s.cache=Object.create(null),s},"memoize");function lLe(a){let s=uCt(async D=>await l(D,await a(D)));async function l(D,N){if(N===void 0)return s(Fde.resolve(D));let M,z,re=t(async Q=>(z=z||await _(ie))(Q),"_resolve"),ie={path:D,text:N,get lines(){return M=M||N.split(`
661
661
  `)},async resolve(Q){try{return await re(Q)}catch(Re){return Object.assign({},Q,{error:Re})}},_resolve:re};return ie}t(l,"SourceFile");async function _(D){let N=/\u0023 sourceMappingURL=(.+)\n?/g,M;for(;;){let ie=N.exec(D.text);if(ie)M=ie;else break}let z=M&&M[1],re=t(async ie=>Object.assign({},ie,{sourceFile:D,sourceLine:D.lines[ie.line-1]||""}),"defaultResolver");return z?await h(D.path,z,re):re}t(_,"SourceMapResolverFromFetchedFile");async function h(D,N,M){let z=N.startsWith("data:")?await l(D,(0,fCt.dataUriToBuffer)(N).toString()):await l(Fde.relativeToFile(D,N)),re=await new _Ct.SourceMapConsumer(JSON.parse(z.text)),ie=uCt(async Q=>{let Re=Fde.relativeToFile(z.path,Q),Ne=re.sourceContentFor(Q,!0)||void 0;return await l(Re,Ne)});return async Q=>{try{let Re=re.originalPositionFor(Q);return Re.source?await(await ie(Re.source))._resolve(Object.assign({},Q,{line:Re.line,column:(Re.column??0)+1,name:Re.name})):M(Q)}catch(Re){return Object.assign(M(Q),{sourceMapError:Re})}}}t(h,"SourceMapResolver");let b=t(async function(N){try{return await l(N)}catch(M){let z={path:N,text:"",lines:[],error:M,async resolve(re){return Object.assign({},re,{error:M,sourceLine:"",sourceFile:z})},_resolve(re){return this.resolve(re)}};return z}},"getSource");return b.resetCache=()=>s.forgetEverything(),b.getCache=()=>s.cache,b}t(lLe,"buildGetSourceFunction");var c6r=t(async a=>o6r(a,{encoding:"utf8"}),"fetchFile"),pCt=lLe(c6r);import l6r from"node:path";import u6r from"node:util";var dCt=t(a=>a[a.length-1],"lastOf"),RY=t(a=>a.replace(/\\/g,"/"),"nixSlashes"),f6r=t((a,s)=>{let l=a||[],_=[],h={label:void 0,items:[l[0]]};return l.forEach(b=>{let D=s(b);h.label!==D&&h.items.length?_.push(h={label:D,items:[b]}):h.items.push(b)}),_},"partition"),MY=class a{static{t(this,"StackTracey")}items;getSource;pathRoot;constructor(s,{offset:l,getSource:_}){this.getSource=_,this.pathRoot=`${RY(process.cwd())}/`;let h=s,b=s instanceof SyntaxError;if(l=l||0,s instanceof Error&&(s=s.stack||""),typeof s=="string"&&(s=this.rawParse(s).slice(l).map(D=>this.extractEntryMetadata(D))),Array.isArray(s)){if(b){let D=u6r.inspect(h).split(`
662
662
  `),N=D[0].split(":"),M=N.pop(),z=N.join(":");z&&s.unshift({file:RY(z),line:parseInt(M||"0",10),column:(D[2]||"").indexOf("^")+1,sourceLine:D[1],callee:"(syntax error)",syntaxError:!0,beforeParse:"",index:!1,native:!1,calleeShort:"",fileRelative:"",fileShort:"",fileName:"",thirdParty:!1})}this.items=s}else this.items=[]}extractEntryMetadata(s){let l=this.decomposePath(s.file||""),_=l[0],h=l[1];return Object.assign(s,{calleeShort:s.calleeShort||dCt((s.callee||"").split(".")),fileRelative:_,fileShort:this.shortenPath(_),fileName:dCt((s.file||"").split("/")),thirdParty:this.isThirdParty(_,h)&&!s.index,externalDomain:h})}shortenPath(s){return s.replace(/^node_modules\//,"").replace(/^webpack\/bootstrap\//,"").replace(/^__parcel_source_root\//,"")}decomposePath(s){let l=s,_=l.match(/^(http|https):\/\/([^\/]+)\/(.*)/),h=_?_[2]:void 0;return l=_?_[3]:l,l=l6r.relative(this.pathRoot,l),[RY(l).replace(/^.*:\/\/?\/?/,""),h]}isThirdParty(s,l){return!!l||s[0]==="~"||s[0]==="/"||s.indexOf("node_modules")===0||s.indexOf("webpack/bootstrap")===0}rawParse(s){return(s||"").split(`
663
663
  `).map(h=>{h=h.trim();let b,D=[],N,M,z;if((M=h.match(/at (.+) \(eval at .+ \((.+)\), .+\)/))||(M=h.match(/at (.+) \((.+)\)/))||h.slice(0,3)!=="at "&&(M=h.match(/(.*)@(.*)/)))b=M[1],N=M[2]==="native",D=(M[2].match(/(.*):(\d+):(\d+)/)||M[2].match(/(.*):(\d+)/)||[]).slice(1);else if(z=h.match(/^(at\s+)*(.+):(\d+):(\d+)/))D=z.slice(2);else return;return b&&!D[0]&&b.split(".")[0]==="Array"&&(N=!0),{beforeParse:h,callee:b||"",index:D[0]==="/",native:N||!1,file:RY(D[0]||""),line:parseInt(D[1]||"",10)||void 0,column:parseInt(D[2]||"",10)||void 0,calleeShort:"",fileRelative:"",fileShort:"",fileName:"",thirdParty:!1}}).filter(h=>h!==void 0)}async withSourceAsyncAt(s){return this.items[s]&&this.withSourceAsync(this.items[s])}async withSourceAsync(s){if(this.shouldSkipResolving(s))return s;{let l=(s.file||"").replace("file://","");try{let h=await(await this.getSource(l)).resolve(s);return this.withSourceResolved(s,h)}catch(_){return this.withSourceResolved(s,{error:_,sourceLine:""})}}}shouldSkipResolving(s){return!!s.sourceFile||!!s.error||!!s.file&&s.file.indexOf("<")>=0}withSourceResolved(s,l){return l.sourceFile&&!l.sourceFile.error&&(l.file=RY(l.sourceFile.path),l=this.extractEntryMetadata(l)),l.sourceLine?.includes("// @hide")&&(l.sourceLine=l.sourceLine.replace("// @hide",""),l.hide=!0),(l.sourceLine?.includes("__webpack_require__")||l.sourceLine?.includes("/******/ ({"))&&(l.thirdParty=!0),Object.assign({sourceLine:""},s,l)}async withSourcesAsync(){let s=await Promise.all(this.items.map(l=>this.withSourceAsync(l)));return new a(s,{getSource:this.getSource})}mergeRepeatedLines(){return new a(f6r(this.items,s=>s.file+s.line).map(s=>s.items.slice(1).reduce((l,_)=>(l.callee=(l.callee||"<anonymous>")+" \u2192 "+(_.callee||"<anonymous>"),l.calleeShort=(l.calleeShort||"<anonymous>")+" \u2192 "+(_.calleeShort||"<anonymous>"),l),Object.assign({},s.items[0]))),{getSource:this.getSource})}async cleanAsync(){let s=await this.withSourcesAsync();return s.mergeRepeatedLines().filter((l,_)=>s.isClean(l,_))}isClean(s,l){return l===0||!(s.thirdParty||s.hide||s.native)}at(s){return Object.assign({beforeParse:"",callee:"<???>",index:!1,native:!1,file:"<???>",line:0,column:0},this.items[s])}map(s,l){return new a(this.items.map(s,l),{getSource:this.getSource})}filter(s,l){return new a(this.items.filter(s,l),{getSource:this.getSource})}slice(s,l){return new a(this.items.slice(s,l),{getSource:this.getSource})}concat(...s){return new a(this.items.concat(...s),{getSource:this.getSource})}maxColumnWidths(){return{callee:30,file:60,sourceLine:80}}static locationsEqual(s,l){return s.file===l.file&&s.line===l.line&&s.column===l.column}};import{relative as g6r}from"node:path";import{fileURLToPath as y6r}from"node:url";import{inspect as v6r}from"node:util";function uLe({onlyFirst:a=!1}={}){let l=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(l,a?void 0:"g")}t(uLe,"ansiRegex");var _6r=uLe();function fLe(a){if(typeof a!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof a}\``);return a.replace(_6r,"")}t(fLe,"stripAnsi");function mCt(a){return a===161||a===164||a===167||a===168||a===170||a===173||a===174||a>=176&&a<=180||a>=182&&a<=186||a>=188&&a<=191||a===198||a===208||a===215||a===216||a>=222&&a<=225||a===230||a>=232&&a<=234||a===236||a===237||a===240||a===242||a===243||a>=247&&a<=250||a===252||a===254||a===257||a===273||a===275||a===283||a===294||a===295||a===299||a>=305&&a<=307||a===312||a>=319&&a<=322||a===324||a>=328&&a<=331||a===333||a===338||a===339||a===358||a===359||a===363||a===462||a===464||a===466||a===468||a===470||a===472||a===474||a===476||a===593||a===609||a===708||a===711||a>=713&&a<=715||a===717||a===720||a>=728&&a<=731||a===733||a===735||a>=768&&a<=879||a>=913&&a<=929||a>=931&&a<=937||a>=945&&a<=961||a>=963&&a<=969||a===1025||a>=1040&&a<=1103||a===1105||a===8208||a>=8211&&a<=8214||a===8216||a===8217||a===8220||a===8221||a>=8224&&a<=8226||a>=8228&&a<=8231||a===8240||a===8242||a===8243||a===8245||a===8251||a===8254||a===8308||a===8319||a>=8321&&a<=8324||a===8364||a===8451||a===8453||a===8457||a===8467||a===8470||a===8481||a===8482||a===8486||a===8491||a===8531||a===8532||a>=8539&&a<=8542||a>=8544&&a<=8555||a>=8560&&a<=8569||a===8585||a>=8592&&a<=8601||a===8632||a===8633||a===8658||a===8660||a===8679||a===8704||a===8706||a===8707||a===8711||a===8712||a===8715||a===8719||a===8721||a===8725||a===8730||a>=8733&&a<=8736||a===8739||a===8741||a>=8743&&a<=8748||a===8750||a>=8756&&a<=8759||a===8764||a===8765||a===8776||a===8780||a===8786||a===8800||a===8801||a>=8804&&a<=8807||a===8810||a===8811||a===8814||a===8815||a===8834||a===8835||a===8838||a===8839||a===8853||a===8857||a===8869||a===8895||a===8978||a>=9312&&a<=9449||a>=9451&&a<=9547||a>=9552&&a<=9587||a>=9600&&a<=9615||a>=9618&&a<=9621||a===9632||a===9633||a>=9635&&a<=9641||a===9650||a===9651||a===9654||a===9655||a===9660||a===9661||a===9664||a===9665||a>=9670&&a<=9672||a===9675||a>=9678&&a<=9681||a>=9698&&a<=9701||a===9711||a===9733||a===9734||a===9737||a===9742||a===9743||a===9756||a===9758||a===9792||a===9794||a===9824||a===9825||a>=9827&&a<=9829||a>=9831&&a<=9834||a===9836||a===9837||a===9839||a===9886||a===9887||a===9919||a>=9926&&a<=9933||a>=9935&&a<=9939||a>=9941&&a<=9953||a===9955||a===9960||a===9961||a>=9963&&a<=9969||a===9972||a>=9974&&a<=9977||a===9979||a===9980||a===9982||a===9983||a===10045||a>=10102&&a<=10111||a>=11094&&a<=11097||a>=12872&&a<=12879||a>=57344&&a<=63743||a>=65024&&a<=65039||a===65533||a>=127232&&a<=127242||a>=127248&&a<=127277||a>=127280&&a<=127337||a>=127344&&a<=127373||a===127375||a===127376||a>=127387&&a<=127404||a>=917760&&a<=917999||a>=983040&&a<=1048573||a>=1048576&&a<=1114109}t(mCt,"isAmbiguous");function hCt(a){return a===12288||a>=65281&&a<=65376||a>=65504&&a<=65510}t(hCt,"isFullWidth");function gCt(a){return a>=4352&&a<=4447||a===8986||a===8987||a===9001||a===9002||a>=9193&&a<=9196||a===9200||a===9203||a===9725||a===9726||a===9748||a===9749||a>=9800&&a<=9811||a===9855||a===9875||a===9889||a===9898||a===9899||a===9917||a===9918||a===9924||a===9925||a===9934||a===9940||a===9962||a===9970||a===9971||a===9973||a===9978||a===9981||a===9989||a===9994||a===9995||a===10024||a===10060||a===10062||a>=10067&&a<=10069||a===10071||a>=10133&&a<=10135||a===10160||a===10175||a===11035||a===11036||a===11088||a===11093||a>=11904&&a<=11929||a>=11931&&a<=12019||a>=12032&&a<=12245||a>=12272&&a<=12287||a>=12289&&a<=12350||a>=12353&&a<=12438||a>=12441&&a<=12543||a>=12549&&a<=12591||a>=12593&&a<=12686||a>=12688&&a<=12771||a>=12783&&a<=12830||a>=12832&&a<=12871||a>=12880&&a<=19903||a>=19968&&a<=42124||a>=42128&&a<=42182||a>=43360&&a<=43388||a>=44032&&a<=55203||a>=63744&&a<=64255||a>=65040&&a<=65049||a>=65072&&a<=65106||a>=65108&&a<=65126||a>=65128&&a<=65131||a>=94176&&a<=94180||a===94192||a===94193||a>=94208&&a<=100343||a>=100352&&a<=101589||a>=101632&&a<=101640||a>=110576&&a<=110579||a>=110581&&a<=110587||a===110589||a===110590||a>=110592&&a<=110882||a===110898||a>=110928&&a<=110930||a===110933||a>=110948&&a<=110951||a>=110960&&a<=111355||a===126980||a===127183||a===127374||a>=127377&&a<=127386||a>=127488&&a<=127490||a>=127504&&a<=127547||a>=127552&&a<=127560||a===127568||a===127569||a>=127584&&a<=127589||a>=127744&&a<=127776||a>=127789&&a<=127797||a>=127799&&a<=127868||a>=127870&&a<=127891||a>=127904&&a<=127946||a>=127951&&a<=127955||a>=127968&&a<=127984||a===127988||a>=127992&&a<=128062||a===128064||a>=128066&&a<=128252||a>=128255&&a<=128317||a>=128331&&a<=128334||a>=128336&&a<=128359||a===128378||a===128405||a===128406||a===128420||a>=128507&&a<=128591||a>=128640&&a<=128709||a===128716||a>=128720&&a<=128722||a>=128725&&a<=128727||a>=128732&&a<=128735||a===128747||a===128748||a>=128756&&a<=128764||a>=128992&&a<=129003||a===129008||a>=129292&&a<=129338||a>=129340&&a<=129349||a>=129351&&a<=129535||a>=129648&&a<=129660||a>=129664&&a<=129672||a>=129680&&a<=129725||a>=129727&&a<=129733||a>=129742&&a<=129755||a>=129760&&a<=129768||a>=129776&&a<=129784||a>=131072&&a<=196605||a>=196608&&a<=262141}t(gCt,"isWide");function p6r(a){if(!Number.isSafeInteger(a))throw new TypeError(`Expected a code point, got \`${typeof a}\`.`)}t(p6r,"validate");function yCt(a,{ambiguousAsWide:s=!1}={}){return p6r(a),hCt(a)||gCt(a)||s&&mCt(a)?2:1}t(yCt,"eastAsianWidth");var SCt=x_(bCt(),1);var d6r=new Intl.Segmenter,m6r=/^\p{Default_Ignorable_Code_Point}$/u;function Ode(a,s={}){if(typeof a!="string"||a.length===0)return 0;let{ambiguousIsNarrow:l=!0,countAnsiEscapeCodes:_=!1}=s;if(_||(a=fLe(a)),a.length===0)return 0;let h=0,b={ambiguousAsWide:!l};for(let{segment:D}of d6r.segment(a)){let N=D.codePointAt(0);if(!(N<=31||N>=127&&N<=159)&&!(N>=8203&&N<=8207||N===65279)&&!(N>=768&&N<=879||N>=6832&&N<=6911||N>=7616&&N<=7679||N>=8400&&N<=8447||N>=65056&&N<=65071)&&!(N>=55296&&N<=57343)&&!(N>=65024&&N<=65039)&&!m6r.test(D)){if((0,SCt.default)().test(D)){h+=2;continue}h+=yCt(N,b)}}return h}t(Ode,"stringWidth");var dLe=x_(xCt(),1);var{platform:CCt,cwd:h6r}=process,{red:tU,yellow:ECt,green:Rde,cyan:jY,dim:_Le}=Jf,DCt=process.stdout.columns,b6r=CCt==="win32"&&!process.env.WT_SESSION?">":"\u276F",S6r=(CCt==="win32"&&!process.env.WT_SESSION,"\u2043"),T6r=h6r();function kCt(a){return a=a.replace("async file:","file:"),g6r(T6r,a.startsWith("file:")?y6r(a):a)}t(kCt,"getRelativePath");function x6r(a){return a.find(s=>s.isApp)||null}t(x6r,"mainFrame");function C6r(a,s){return a.filter(l=>(l.isApp||l.isModule)&&(!s||l.file!==s.file||l.line!==s.line))}t(C6r,"filterNativeFrames");function wCt(a){return a.callee||"anonymous"}t(wCt,"frameMethod");function PCt(a,s){let l="",_=a.length-s.length;for(let h=0;h<=_;h++)l+=" ";return l}t(PCt,"whiteSpace");function pLe(a,s,l,_,h){let b=PCt(String(l),String(s));return _?`${h}${tU(b6r)}${b}${tU(s)}${tU("|")}${b} ${tU(a)}`:`${h} ${b}${_Le(s)}${_Le("|")}${b} ${_Le(a)}`}t(pLe,"codeLine");function E6r(a,s,l){let _,h=(0,dLe.default)(Ode(s)+2,DCt);return l?_=`${s} ${tU(h(`${a.message}`).trim())}`:_=`${s} ${tU(h(`${a.name}: ${a.message}`).trim())}`,[_,s]}t(E6r,"getMessage");function D6r(a,s){let l=a.help;if(!l)return[];let _=(0,dLe.default)(Ode(s)+4,DCt);return Array.isArray(l)?l.map(h=>`${s} ${jY(_(`- ${h}`).trim())}`).concat([s]):[`${s} ${jY(l)}`,s]}t(D6r,"getHelpText");function k6r(a,s,l){if(!a)return[];let _=l?kCt(a.filePath):a.filePath;return[`${s} at ${ECt(`${wCt(a)}`)} ${Rde(_)}:${Rde(a.line)}`]}t(k6r,"getMainFrameLocation");function w6r(a,s){if(!a||!a.context||!a.context.line)return[];let l=a.context.start-1,_=a.context.pre.split(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zuplo/core",
3
- "version": "6.52.5",
3
+ "version": "6.52.6",
4
4
  "repository": "https://github.com/zuplo/zuplo",
5
5
  "author": "Zuplo, Inc.",
6
6
  "type": "module",
@@ -41,9 +41,9 @@
41
41
  "prettier": "^3.5.3"
42
42
  },
43
43
  "peerDependencies": {
44
- "@zuplo/graphql": "6.52.5",
45
- "@zuplo/otel": "6.52.5",
46
- "@zuplo/runtime": "6.52.5",
44
+ "@zuplo/graphql": "6.52.6",
45
+ "@zuplo/otel": "6.52.6",
46
+ "@zuplo/runtime": "6.52.6",
47
47
  "deno": "2.3.1"
48
48
  }
49
49
  }