balda-js 0.0.62 → 0.0.63

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
- 'use strict';var glob=require('glob'),ot=require('pino'),Qe=require('path'),zod=require('zod'),child_process=require('child_process'),Te=require('fs'),http=require('http'),http2=require('http2'),https=require('https'),zlib=require('zlib');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ot__default=/*#__PURE__*/_interopDefault(ot);var Qe__default=/*#__PURE__*/_interopDefault(Qe);var Te__default=/*#__PURE__*/_interopDefault(Te);var tr=Object.defineProperty;var x=(s,e,t,r)=>{for(var o=void 0,n=s.length-1,i;n>=0;n--)(i=s[n])&&(o=(i(e,t,o))||o);return o&&tr(e,t,o),o};var O=class extends Error{constructor(e){super(e);}};var sr=()=>ot__default.default({level:"info",formatters:{level:e=>({level:e})}});exports.logger=sr();var Xr=s=>{exports.logger=ot__default.default(s);};var Be=class{type;constructor(){this.type=this.getRunTime();}getRunTime(){if(typeof Bun<"u")return "bun";if(typeof Deno<"u")return "deno";if(typeof process<"u")return "node";throw new Error("No environment detected")}},g=new Be;var Le=class{getCwd(){switch(g.type){case "node":case "bun":return process.cwd();case "deno":return Deno.cwd();default:throw new Error("Unsupported runtime")}}},$=new Le;var j=class{static scheduledJobs=[];static register(e,...t){t[2]={name:e,...t[2]},this.scheduledJobs.push({name:e,args:t});}static async run(){let e=(await import('node-cron').catch(()=>{throw new O("node-cron not installed as a dependency, it is required in order to run cron jobs with the @cron decorator")})).default;if(exports.logger.info("Scheduling cron jobs"),!this.scheduledJobs.length){exports.logger.info("No cron jobs to schedule");return}for(let{name:t,args:r}of this.scheduledJobs)exports.logger.info(`Scheduling cron job: ${t}`),e.schedule(...r).on("execution:failed",n=>this.globalErrorHandler(n));exports.logger.info("Cron jobs scheduled");}static globalErrorHandler(e){exports.logger.error(e.execution?.error);}static async massiveImportCronJobs(e){let t=[];for(let r of e){let o=await glob.glob(r,{absolute:true,cwd:$.getCwd()});t.push(...o);}await Promise.all(t.map(async r=>{await import(r).catch(o=>{exports.logger.error(`Error importing cron job: ${r}`),exports.logger.error(o);});}));}},ps=s=>{j.globalErrorHandler=s.bind(j);};var us=(s,e)=>function(t,r,o){let n=o.value,i=async(...p)=>{let d=new t.constructor;return await n.apply(d,p)};return j.register(`${t.constructor.name}.${r}`,s,i,e),o};var Ue=class{getCliArgs(){switch(g.type){case "bun":return this.getBunArgs();case "node":return this.getNodeArgs();case "deno":return Deno.args;default:throw new Error("Unsupported runtime")}}getBunArgs(){let e=Bun.argv,t=this.findScriptIndex(e);return e.slice(t+1)}getNodeArgs(){let e=process.argv,t=this.findScriptIndex(e);return e.slice(t+1)}findScriptIndex(e){if(e.length>=3&&e[1].includes(".bin/"))return 1;for(let t=0;t<e.length;t++){let r=e[t],o=r.split("/").pop()||r;if(!r.startsWith("-")){if(o==="yarn"&&t+1<e.length&&e[t+1]==="run"||o==="npx"&&t+1<e.length)return t+1;if(o==="yarn"||o==="pnpm")return t;if(o==="npm"&&t+1<e.length&&e[t+1]==="run"||o==="bun"&&t+1<e.length&&e[t+1]==="run")return t+1;if(/\.(js|ts|mjs|cjs)$/.test(r))return t;if(/^(tsx|ts-node|node|bun)$/.test(o)){for(let n=t+1;n<e.length;n++)if(!e[n].startsWith("-")&&/\.(js|ts|mjs|cjs)$/.test(e[n]))return n;return t}}}for(let t=e.length-1;t>=0;t--)if(!e[t].startsWith("-"))return t;return 1}},Ie=new Ue;var nt=s=>s.toLowerCase().replace(/[-_.]/g,"_").replace(/([A-Z])/g,"_$1").replace(/^_+/,"").replace(/_+$/,"").toLowerCase(),pe=(s,e)=>{if(!s||typeof s!="string")return e;let t=s.toLowerCase().trim(),r=t.match(/^(\d+(?:\.\d+)?)kb$/),o=t.match(/^(\d+(?:\.\d+)?)mb$/);if(r){let n=Number.parseFloat(r[1]);return Number.isNaN(n)||n<0?e:Math.floor(n*1024)}if(o){let n=Number.parseFloat(o[1]);return Number.isNaN(n)||n<0?e:Math.floor(n*1024*1024)}return e};var nr=s=>{if(!s||s==="-"||s==="--")return null;let e=s.indexOf("=");if(e>0){let t=s.substring(0,e),r=s.substring(e+1);return {name:t,value:it(r)}}return {name:s,value:true}},it=s=>{if(s.toLowerCase()==="true")return true;if(s.toLowerCase()==="false")return false;let e=Number(s);return !Number.isNaN(e)&&Number.isFinite(e)?e:s},J=()=>{let s=Ie.getCliArgs(),e=[],t={};if(!s||!s.length)return {args:e,flags:t};for(let r=0;r<s.length;r++){let o=s[r];if(!(!o||typeof o!="string")){if(o.startsWith("-")){let n=nr(o);if(n){if(n.value===true&&r+1<s.length){let i=s[r+1];i&&typeof i=="string"&&!i.startsWith("-")&&(n.value=it(i),r++);}t[n.name]=n.value;}continue}e.push(o);}}return {args:e,flags:t}};var be=()=>Ie.getCliArgs()[0]||null;var h=class{static metadata=new WeakMap;static set(e,t,r){this.metadata.has(e)||this.metadata.set(e,new Map),this.metadata.get(e).set(t,r);}static get(e,t){return this.metadata.get(e)?.get(t)}static getAll(e){return this.metadata.get(e)||new Map}static delete(e,t){this.metadata.get(e)?.delete(t.toString());}static clear(e){this.metadata.delete(e);}};var W="VALIDATION_ERROR",Rs="ARG",at=J().args.slice(1),L=s=>(e,t)=>{let r=be();if(!r||r!==e.commandName)return;let o=t;h.set(e,t,{type:"arg",name:o,description:s.description});let n=at.length?at.shift():s.defaultValue;if(s.required&&!n){let i=h.get(e,W);h.set(e,W,[...i||[],{type:"arg",name:o,message:"Required argument not provided"}]);return}s.parse&&n&&(n=s.parse(n)),Object.defineProperty(e,t,{value:n,enumerable:true,configurable:true,writable:true});};var Y=s=>(e,t)=>{let r=be();if(!r||r!==e.commandName)return;let o=s.name||t,n=J().flags,i=s.aliases||[],p=[o,...i],d=s.defaultValue;for(let a of p){let c=[a,`-${a}`,`--${a}`];for(let u of c)if(u in n){d=n[u],s.type==="boolean"?d=!!d:s.type==="number"&&(d=Number(d)),s.parse&&(d=s.parse(d));break}if(d!==s.defaultValue)break}if(h.set(e,t,{type:"flag",name:o,aliases:i||[],description:s.description}),s.required&&!d){let a=h.get(e,W);h.set(e,W,[...a||[],{type:"flag",name:o,message:"Required flag not provided"}]);return}Object.defineProperty(e,t,{value:d,enumerable:true,configurable:true,writable:true});};Y.boolean=s=>Y({...s,type:"boolean"});Y.string=s=>Y({...s,type:"string"});Y.number=s=>Y({...s,type:"number"});var T=Y;var ze=class{join(...e){switch(g.type){case "node":case "bun":case "deno":return Qe__default.default.join(...e);default:throw new Error("Unsupported runtime")}}extName(e){switch(g.type){case "bun":case "node":case "deno":return Qe__default.default.extname(e);default:throw new Error("Unsupported runtime")}}resolve(...e){switch(g.type){case "bun":case "node":case "deno":return Qe__default.default.resolve(...e);default:throw new Error("Unsupported runtime")}}},y=new ze;var de=class{staticChildren;paramChild;wildcardChild;middleware;handler;constructor(){this.staticChildren=new Map,this.paramChild=null,this.wildcardChild=null,this.middleware=null,this.handler=null;}},Ge=class s{trees;routes;middlewares;basePath;constructor(e="",t=[]){this.trees=new Map,this.routes=[],this.middlewares=t,this.basePath=this.normalizeBasePath(e);}getRoutes(){return this.routes.slice()}addOrUpdate(e,t,r,o,n){e=e.toUpperCase();let i=this.trees.get(e);i||(i=new de,this.trees.set(e,i));let d=t.split("?")[0].replace(/^\/+|\/+$/g,""),a=d.length===0?[]:d.split("/"),c=i;for(let f of a){if(f==="*"){c.wildcardChild||(c.wildcardChild=new de),c=c.wildcardChild;break}if(f.startsWith(":")){let l=f.slice(1);c.paramChild||(c.paramChild={node:new de,name:l}),c=c.paramChild.node;continue}c.staticChildren.has(f)||c.staticChildren.set(f,new de),c=c.staticChildren.get(f);}c.middleware=r,c.handler=o;let u=this.routes.findIndex(f=>f.method===e&&f.path===t);if(u!==-1){this.routes[u].middleware=r,this.routes[u].handler=o;return}this.routes.push({method:e,path:t,middleware:r,handler:o,swaggerOptions:n});}find(e,t){e=e.toUpperCase();let r=this.trees.get(e);if(!r)return null;let n=t.split("?")[0].replace(/^\/+|\/+$/g,""),i=n.length===0?[]:n.split("/"),p={},d=r;for(let a=0;a<i.length;a++){let c=i[a];if(d.staticChildren.has(c)){d=d.staticChildren.get(c);continue}if(d.paramChild){p[d.paramChild.name]=c,d=d.paramChild.node;continue}if(d.wildcardChild){p["*"]=i.slice(a).join("/"),d=d.wildcardChild;break}return null}return !d.handler||!d.middleware?null:{middleware:d.middleware,handler:d.handler,params:p}}get(e,t,r,o){let n=this.joinPath(e),i=typeof t=="function"&&t.length!==3,p=i?t:r,d=i?[]:Array.isArray(t)?t:[t],a=[...this.middlewares,...d],c=i?r:o;this.addOrUpdate("GET",n,a,p,c);}post(e,t,r,o){let n=this.joinPath(e),i=typeof t=="function"&&t.length!==3,p=i?t:r,d=i?[]:Array.isArray(t)?t:[t],a=[...this.middlewares,...d],c=i?r:o;this.addOrUpdate("POST",n,a,p,c);}patch(e,t,r,o){let n=this.joinPath(e),i=typeof t=="function"&&t.length!==3,p=i?t:r,d=i?[]:Array.isArray(t)?t:[t],a=[...this.middlewares,...d],c=i?r:o;this.addOrUpdate("PATCH",n,a,p,c);}put(e,t,r,o){let n=this.joinPath(e),i=typeof t=="function"&&t.length!==3,p=i?t:r,d=i?[]:Array.isArray(t)?t:[t],a=[...this.middlewares,...d],c=i?r:o;this.addOrUpdate("PUT",n,a,p,c);}delete(e,t,r,o){let n=this.joinPath(e),i=typeof t=="function"&&t.length!==3,p=i?t:r,d=i?[]:Array.isArray(t)?t:[t],a=[...this.middlewares,...d],c=i?r:o;this.addOrUpdate("DELETE",n,a,p,c);}options(e,t,r,o){let n=this.joinPath(e),i=typeof t=="function"&&t.length!==3,p=i?t:r,d=i?[]:Array.isArray(t)?t:[t],a=[...this.middlewares,...d],c=i?r:o;this.addOrUpdate("OPTIONS",n,a,p,c);}head(e,t,r,o){let n=this.joinPath(e),i=typeof t=="function"&&t.length!==3,p=i?t:r,d=i?[]:Array.isArray(t)?t:[t],a=[...this.middlewares,...d],c=i?r:o;this.addOrUpdate("HEAD",n,a,p,c);}group(e,t,r){let o=Array.isArray(t)?t:typeof t=="function"?[]:t?[t]:[],n=Array.isArray(t)?r:typeof t=="function"?t:void 0,i=this.joinPath(e),p=new s(i,[...this.middlewares,...o]);n?.(p);for(let d of p.getRoutes())this.addOrUpdate(d.method,d.path,d.middleware,d.handler,d.swaggerOptions);}applyGlobalMiddlewaresToAllRoutes(e){for(let t of this.routes)this.addOrUpdate(t.method,t.path,[...e,...t.middleware||[]],t.handler);}normalizeBasePath(e){if(!e)return "";let t=e.replace(/\s+/g,"");return t=t.replace(/\/+/g,"/"),t.startsWith("/")||(t="/"+t),t.length>1&&(t=t.replace(/\/+$/g,"")),t}joinPath(e){let r=[this.basePath,e].filter(o=>typeof o=="string"&&o.length>0).join("/");return r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r.length>1&&(r=r.replace(/\/+$/g,"")),r}},w=new Ge;var ir=s=>async(e,t,r)=>{for(let o of s)if(!await o.manager.canAccess(o.scope,o.handler,e))return t.unauthorized({error:"Unauthorized"});return r()},Fs=(s,e)=>t=>{let r=h.get(t.prototype,"__class__"),o=r?.middlewares||[],n=r?.policies||[],i=h.getAll(t.prototype),p=new t;for(let[d,a]of i.entries()){if(!a.route)continue;let c=t.prototype[d].bind(p),u=s?y.join(s,a.route.path):a.route.path,f=[...n,...a.policies||[]],l=f.length>0?[ir(f)]:[],m=[...o,...l,...a.middlewares||[]];w.addOrUpdate(a.route.method,u,m,c,{service:t.name.replace(/Controller$/,""),...e,...a.documentation});}h.clear(t.prototype);};var Ds=(s,e)=>(t,r,o)=>{let n=h.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"DELETE"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"DELETE"},h.set(t,r,n),o};var Us=(s,e)=>(t,r,o)=>{let n=h.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"GET"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"GET"},h.set(t,r,n),o};var zs=(s,e)=>(t,r,o)=>{let n=h.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"PATCH"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"PATCH"},h.set(t,r,n),o};var Vs=(s,e)=>(t,r,o)=>{let n=h.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"POST"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"POST"},h.set(t,r,n),o};var Ws=(s,e)=>(t,r,o)=>{let n=h.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"PUT"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"PUT"},h.set(t,r,n),o};var eo=s=>(e,t,r)=>{if(typeof t>"u"){let n=h.get(e.prototype,"__class__");if(n||(n={middlewares:[]}),n.middlewares||(n.middlewares=[]),!s)throw new Error(`Middleware ${String(s)} not found, are you sure you defined it before using it?`);return Array.isArray(s)||(s=[s]),n.middlewares.push(...s),h.set(e.prototype,"__class__",n),e}let o=h.get(e,t);return o||(o={middlewares:[]}),o.middlewares||(o.middlewares=[]),Array.isArray(s)||(s=[s]),o.middlewares.push(...s),h.set(e,t,o),r};var D=(s,e,t=false)=>{let{success:r,data:o,error:n}=s.safeParse(e);if(!r){if(t)return o;throw n}return o};var pt=Symbol("serializeWrapped"),ce=Symbol("serializeMetadata"),io=(s,e)=>(t,r,o)=>{let n=h.get(t,r)||{middlewares:[],route:{}};n.documentation||(n.documentation={}),n.documentation.responses||(n.documentation.responses={}),n.serializeOptions||(n.serializeOptions={});let i=Number(e?.status??200);if(n.documentation.responses[i]=s,n.serializeOptions[i]=e?.safe??true,h.set(t,r,n),o.value[ce]||(o.value[ce]={}),o.value[ce][i]={name:r,schema:s,safe:e?.safe??true},!o.value[pt]){let p=o.value,d=async function(...a){let c=a[1];await p.apply(this,a);let u=c.responseStatus,f=d[ce],l=f?.[u]?.schema,m=f?.[u]?.safe??true;if(l&&!m){let v=c.getBody();try{c.send(D(l,v,m));}catch(P){if(P instanceof zod.ZodError){c.internalServerError({received:v,schema:l,error:P});return}throw P}}};d[pt]=true,d[ce]=p[ce],o.value=d;}};var X=s=>(e,t,r)=>{let o=r.value,n=h.get(e,t);return n||(n={middlewares:[],route:{}}),n.documentation||(n.documentation={}),s.body&&(n.documentation.requestBody=s.body),s.query&&(n.documentation.query=s.query),h.set(e,t,n),r.value=async function(...i){let p=i[0],d=i[1];try{let a,c,u;s.body&&(a=p.validate(s.body,s.safe)),s.query&&(c=p.validateQuery(s.query,s.safe)),s.all&&(u=p.validateAll(s.all,s.safe));let f=[...i];return a!==void 0&&f.push(a),c!==void 0&&f.push(c),u!==void 0&&f.push(u),o.apply(this,f)}catch(a){if(!(a instanceof zod.ZodError))throw a;return s.customError?d.status(s.customError.status||400).json({received:p.body,schema:s.body,error:a}):d.badRequest(a)}},r};X.query=(s,e)=>X({query:s,customError:e});X.body=(s,e)=>X({body:s,customError:e});X.all=(s,e)=>X({all:s,customError:e});var uo=X;var ee=class{static options={connection:{}}},dt=s=>{ee.options=s??{connection:{}};};var F=class extends O{constructor(...e){super(`Library not installed: ${e.join(", ")}, try run npm install ${e.join(" ")}`);}};var Ke=class{randomUUID(){return crypto.randomUUID()}},U=new Ke;var xe=class{queues=new Map;workers=new Map;async publish(e,t,r){let o=await this.getQueue(e),n=U.randomUUID();return await o.add(e,t,{jobId:n,...ee.options?.defaultJobOptions,...r}),{id:n}}async subscribe(e,t){if(this.workers.has(e))throw new Error(`[BullMQ] Already subscribed to topic "${e}"`);let{errorHandler:r,...o}=ee.options??{},n=await this.getBullMQClient(),i=new n.Worker(e,async p=>{try{await t(p.data);}catch(d){await r?.(p,d)??Promise.reject(d);}},{...o});this.workers.set(e,i);}async getQueue(e){if(!this.queues.has(e)){let t=await import('bullmq').catch(()=>{throw new F("bullmq","ioredis")}),r=new t.Queue(e,{...ee.options||{connection:{}}});this.queues.set(e,r);}return this.queues.get(e)}async getBullMQClient(){return this.bullmqClient||(this.bullmqClient=await import('bullmq').catch(()=>{throw new F("bullmq","ioredis")})),this.bullmqClient}};var I=class{static options={}},ct=s=>{I.options=s??{};};var Re=class{createdQueues=new Set;async publish(e,t,r){let o=await this.getBoss();await this.ensureQueue(String(e));let n=r||{},i=await o.send(String(e),t,n);return {id:String(i??"")}}async subscribe(e,t){let r=await this.getBoss();await this.ensureQueue(String(e));let o=I.options;o.errorHandler&&r.on("error",o.errorHandler),await r.work(String(e),async n=>{let i=Array.isArray(n)?n:[n];for(let p of i)await t(p.data);});}async getBoss(){if(this.boss)return this.boss;let e=await import('pg-boss').catch(()=>{throw new F("pg-boss","pg")}),r=e.default??e,{connectionString:o,boss:n}=I.options,i=o??n,p=new r(i);return I.options?.errorHandler&&p.on("error",I.options.errorHandler),await p.start(),this.boss=p,this.boss}async ensureQueue(e){if(this.createdQueues.has(e))return;let t=await this.getBoss();typeof t.createQueue=="function"&&await t.createQueue(e),this.createdQueues.add(e);}};var te=class{static options={}},ut=s=>{te.options=s??{};};var Oe=class{consumers=new Map;client;async publish(e,t,r){let{...o}=r??{},n=await this.getClient(),{SendMessageCommand:i}=await this.getSqsLib(),p=await this.resolveQueueUrl(String(e));if(!p)throw new Error(`[SQS] Queue url not configured for topic "${String(e)}"`);let d=new i({MessageBody:JSON.stringify(t),MessageAttributes:{topic:{DataType:"String",StringValue:String(e)}},...o,QueueUrl:p});return {id:(await n.send(d)).MessageId??""}}async subscribe(e,t){if(this.consumers.has(String(e)))throw new Error(`[SQS] Already subscribed to topic "${String(e)}"`);let r=te.options,o=await this.getSqsConsumerLib(),n={...r.consumer||{},sqs:await this.getClient(),queueUrl:await this.resolveQueueUrl(String(e)),handleMessage:async d=>{let a=JSON.parse(d.Body||"{}");await t(a);}},i=o.Consumer.create(n),p=r.errorHandler;p&&(i.on("error",p),i.on("processing_error",p)),i.start(),this.consumers.set(String(e),i);}async getClient(){if(this.client)return this.client;let{SQSClient:e}=await this.getSqsLib(),t=te.options.client;return this.client=new e(t??{}),this.client}async getSqsLib(){return this.sqsLib||(this.sqsLib=await import('@aws-sdk/client-sqs').catch(()=>{throw new F("@aws-sdk/client-sqs","sqs-consumer")})),this.sqsLib}async getSqsConsumerLib(){return this.sqsConsumerLib||(this.sqsConsumerLib=await import('sqs-consumer').catch(()=>{throw new F("sqs-consumer")})),this.sqsConsumerLib}async resolveQueueUrl(e){let r=te.options.consumer?.queueUrlMap?.[e];if(!r)throw new Error(`[SQS] Queue url not configured for topic "${e}"`);return r}};var Q=class{static map=new Map;static{this.map.set("bullmq",new xe),this.map.set("sqs",new Oe),this.map.set("pgboss",new Re);}static getProvider(e){if(!this.map.has(e))throw new Error(`[QueueSubscriber] Provider ${e} not found`);return this.map.get(e)}static setProvider(e,t){this.map.set(e,t);}};var re=class{static scheduledSubscribers=[];static register(e,t,r,o){this.scheduledSubscribers.push({name:e,topic:t,handler:r,provider:o?.provider??"bullmq"});}static async run(){if(exports.logger.info("Subscribing queue handlers"),!this.scheduledSubscribers.length){exports.logger.info("No queue handlers to subscribe");return}for(let{topic:e,handler:t,provider:r}of this.scheduledSubscribers)exports.logger.info(`Subscribing to queue: ${String(e)}`),await Q.getProvider(r).subscribe(e,t);exports.logger.info("Queue handlers subscribed");}static async massiveImportQueues(e){let t=[];for(let r of e){let o=await glob.glob(r,{absolute:true,cwd:$.getCwd()});t.push(...o);}await Promise.all(t.map(async r=>{await import(r).catch(o=>{exports.logger.error(`Error importing queue handler: ${r}`),exports.logger.error(o);});}));}};var ue=(s,e)=>function(t,r,o){let n=o.value,i=async p=>{let d=new t.constructor;return n.apply(d,[p])};return re.register(`${t.constructor.name}.${r}`,e,i,{provider:s}),o};ue.bullmq=s=>ue("bullmq",s);ue.sqs=s=>ue("sqs",s);ue.pgboss=s=>ue("pgboss",s);var se=async(s,e,t,r)=>Q.getProvider(s).publish(e,t,r??{});se.bullmq=async(s,e,t)=>se("bullmq",s,e,t);se.sqs=async(s,e,t)=>se("sqs",s,e,t);se.pgboss=async(s,e,t)=>se("pgboss",s,e,t);var Lo=se;var Ko=s=>{let e=["bullmq","pgboss","sqs"];s.bullmq&&dt(s.bullmq),s.pgboss&&ct(s.pgboss),s.sqs&&ut(s.sqs);for(let t of Object.keys(s)){let r=t;e.includes(r)||Q.setProvider(r,s[r]);}};var Ve=class{exit(e){switch(g.type){case "bun":case "node":process.exit(e);case "deno":Deno.exit(e);default:throw new Error("Unsupported runtime")}}},Ze=new Ve;var E=class{static commandName=this.name;static description="";static help=[];static options={keepAlive:false};static args=J().args.slice(1);static flags=J().flags;static logger=exports.logger;static handle(){throw new Error(`Handle method not implemented in command class ${this.name}`)}static handleHelpFlag(e){let t=["-h","--help"];if(!Object.keys(e).some(a=>t.includes(a)))return;let o=this.commandName,n=this.description||"No description available",i=this.help||[],p=this.options,d=this.generateHelpOutput({name:o,description:n,helpText:i,options:p,args:this.args,flags:this.flags},this);console.log(d),Ze.exit(0);}static generateHelpOutput=(e,t)=>{let{name:r,description:o,helpText:n,options:i,args:p,flags:d}=e,a={title:"\x1B[1;36m",subtitle:"\x1B[1;33m",description:"\x1B[0;37m",code:"\x1B[0;32m",flag:"\x1B[0;35m",reset:"\x1B[0m",error:"\x1B[0;31m",success:"\x1B[0;32m",info:"\x1B[0;34m"},c=[`${a.title}${r}${a.reset}`,`${a.description}${o}${a.reset}`,"",`${a.subtitle}Usage:${a.reset}`,` ${a.code}${r}${a.reset} [options] [arguments]`,"",`${a.subtitle}Options:${a.reset}`,` ${a.flag}-h, --help${a.reset} Show this help message`,"",`${a.subtitle}Command Options:${a.reset}`,` ${a.flag}keepAlive${a.reset} ${i?.keepAlive??false?a.success+"Enabled"+a.reset:a.error+"Disabled"+a.reset}`,""];if(n){let m=Array.isArray(n)?n:[n];c.push(`${a.subtitle}Help:${a.reset}`),m.forEach(v=>{c.push(` ${a.description}${v}${a.reset}`);}),c.push("");}let u=h.getAll(t),f=Array.from(u.values()).filter(m=>m.type==="arg"),l=Array.from(u.values()).filter(m=>m.type==="flag");return f.length&&(c.push(`${a.subtitle}Available Arguments:${a.reset}`),f.forEach(m=>{let v=m.required?` ${a.error}(required)${a.reset}`:"",P=m.description?` ${a.description}${m.description}${a.reset}`:"";c.push(` ${a.code}${m.name}${a.reset}${v}${P}`);}),c.push("")),l.length&&(c.push(`${a.subtitle}Available Flags:${a.reset}`),l.forEach(m=>{m.aliases&&!Array.isArray(m.aliases)&&(m.aliases=[m.aliases]);let v=m.aliases.length?` ${a.flag}(${m.aliases.join(", ")})${a.reset}`:"",P=m.required?` ${a.error}(required)${a.reset}`:"",C=m.description?` ${a.description}${m.description}${a.reset}`:"";c.push(` ${a.flag}--${m.name}${v}${a.reset}${P}${C}`);}),c.push("")),((p?.length??0)>0||d&&Object.keys(d).length>0)&&(c.push(`${a.subtitle}Current Context:${a.reset}`),p?.length&&c.push(` ${a.info}Provided Arguments:${a.reset} ${a.code}${p.join(" ")}${a.reset}`),d&&Object.keys(d).length>0&&(c.push(` ${a.info}Provided Flags:${a.reset}`),Object.keys(d).forEach(m=>{let v=d[m],P=v!=null?` = ${a.code}${v}${a.reset}`:"";c.push(` ${a.flag}${m}${a.reset}${P}`);})),c.push("")),n&&(Array.isArray(n)?n.some(m=>m.includes("example")):n.includes("example"))&&(c.push(`${a.subtitle}Examples:${a.reset}`),(Array.isArray(n)?n.filter(v=>v.includes("example")):[n.split("example")[1].trim()]).forEach(v=>{c.push(` ${a.code}${v}${a.reset}`);}),c.push("")),c.join(`
2
- `)};static validateContext=e=>{let t=Array.from(h.get(e,W)||[]);if(t.length){let r={error:"\x1B[0;31m",title:"\x1B[1;31m",reset:"\x1B[0m",info:"\x1B[0;34m",code:"\x1B[0;32m"};console.error(`${r.title}\u274C Validation Errors:${r.reset}`),console.error(""),t.forEach((o,n)=>{let i=`${r.info}${n+1}.${r.reset}`,p=`${r.error}${o.type.toUpperCase()}${r.reset}`,d=`${r.code}${o.name}${r.reset}`;console.error(` ${i} ${p} ${d}: ${r.error}${o.message}${r.reset}`);}),console.error(""),console.error(`${r.info}\u{1F4A1} Tip: Use --help for usage information${r.reset}`),Ze.exit(1);}}};var Je=class{async mkdir(e,t){switch(g.type){case "bun":case "node":await(await import('fs/promises')).mkdir(e,{recursive:t?.recursive??false,mode:t?.mode});break;case "deno":typeof t?.mode=="string"&&(t.mode=Number.parseInt(t.mode)),await Deno.mkdir(e,{recursive:t?.recursive??false,mode:t?.mode});break}}async exists(e){switch(g.type){case "node":return (await import('fs')).existsSync(e);case "bun":return Bun.file(e).exists();case "deno":return Deno.stat(e).then(()=>true).catch(()=>false);default:throw new Error("Unsupported runtime")}}async readFile(e){switch(g.type){case "node":let r=await(await import('fs/promises')).readFile(e);return new Uint8Array(r);case "bun":let o=await Bun.file(e).arrayBuffer();return new Uint8Array(o);case "deno":return new Uint8Array(await Deno.readFile(e))}}async writeFile(e,t){switch(g.type){case "node":await(await import('fs/promises')).writeFile(e,t);break;case "bun":await Bun.write(e,t);break;case "deno":await Deno.writeFile(e,t);break}}async stat(e){switch(g.type){case "node":let r=await(await import('fs/promises')).stat(e);return {isDirectory:r.isDirectory(),isFile:r.isFile(),isSymbolicLink:r.isSymbolicLink(),size:r.size};case "bun":let o=await Bun.file(e).stat();return {isDirectory:o.isDirectory(),isFile:o.isFile(),isSymbolicLink:o.isSymbolicLink(),size:o.size};case "deno":let n=await Deno.stat(e);return {isDirectory:n.isDirectory,isFile:n.isFile,isSymbolicLink:false,size:n.size}}}async unlink(e){switch(g.type){case "node":await(await import('fs/promises')).unlink(e);break;case "bun":await Bun.file(e).delete();break;case "deno":await Deno.remove(e);break;default:throw new Error("Unsupported runtime")}}},S=new Je;var le=class extends E{static commandName="generate-command";static description="Generate a new command in the specified path";static help=["Generate a new cli command in the specified path","Example: npx balda generate-command my-command -p src/commands"];static path="src/commands";static name;static async handle(){let e=this.getCommandTemplate();this.path=y.join(this.path,`${this.name}.ts`),await S.exists(y.join(process.cwd(),this.path))||await S.mkdir(y.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await S.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Command ${this.name} created successfully at ${this.path}`);}static getCommandTemplate(){return `import { Command, CommandOptions } from "balda-js";
1
+ 'use strict';var glob=require('glob'),it=require('pino'),ze=require('path'),zod=require('zod'),child_process=require('child_process'),Ce=require('fs'),zlib=require('zlib'),http=require('http'),http2=require('http2'),https=require('https');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var it__default=/*#__PURE__*/_interopDefault(it);var ze__default=/*#__PURE__*/_interopDefault(ze);var Ce__default=/*#__PURE__*/_interopDefault(Ce);var sr=Object.defineProperty;var R=(s,e,t,r)=>{for(var o=void 0,n=s.length-1,i;n>=0;n--)(i=s[n])&&(o=(i(e,t,o))||o);return o&&sr(e,t,o),o};var O=class extends Error{constructor(e){super(e);}};var nr=()=>it__default.default({level:"info",formatters:{level:e=>({level:e})}});exports.logger=nr();var ts=s=>{exports.logger=it__default.default(s);};var Qe=class{type;constructor(){this.type=this.getRunTime();}getRunTime(){if(typeof Bun<"u")return "bun";if(typeof Deno<"u")return "deno";if(typeof process<"u")return "node";throw new Error("No environment detected")}},g=new Qe;var Ie=class{getCwd(){switch(g.type){case "node":case "bun":return process.cwd();case "deno":return Deno.cwd();default:throw new Error("Unsupported runtime")}}},q=new Ie;var j=class{static scheduledJobs=[];static register(e,...t){t[2]={name:e,...t[2]},this.scheduledJobs.push({name:e,args:t});}static async run(){let e=(await import('node-cron').catch(()=>{throw new O("node-cron not installed as a dependency, it is required in order to run cron jobs with the @cron decorator")})).default;if(exports.logger.info("Scheduling cron jobs"),!this.scheduledJobs.length){exports.logger.info("No cron jobs to schedule");return}for(let{name:t,args:r}of this.scheduledJobs)exports.logger.info(`Scheduling cron job: ${t}`),e.schedule(...r).on("execution:failed",n=>this.globalErrorHandler(n));exports.logger.info("Cron jobs scheduled");}static globalErrorHandler(e){exports.logger.error(e.execution?.error);}static async massiveImportCronJobs(e){let t=[];for(let r of e){let o=await glob.glob(r,{absolute:true,cwd:q.getCwd()});t.push(...o);}await Promise.all(t.map(async r=>{await import(r).catch(o=>{exports.logger.error(`Error importing cron job: ${r}`),exports.logger.error(o);});}));}},cs=s=>{j.globalErrorHandler=s.bind(j);};var ms=(s,e)=>function(t,r,o){let n=o.value,i=async(...p)=>{let d=new t.constructor;return await n.apply(d,p)};return j.register(`${t.constructor.name}.${r}`,s,i,e),o};var Ue=class{getCliArgs(){switch(g.type){case "bun":return this.getBunArgs();case "node":return this.getNodeArgs();case "deno":return Deno.args;default:throw new Error("Unsupported runtime")}}getBunArgs(){let e=Bun.argv,t=this.findScriptIndex(e);return e.slice(t+1)}getNodeArgs(){let e=process.argv,t=this.findScriptIndex(e);return e.slice(t+1)}findScriptIndex(e){if(e.length>=3&&e[1].includes(".bin/"))return 1;for(let t=0;t<e.length;t++){let r=e[t],o=r.split("/").pop()||r;if(!r.startsWith("-")){if(o==="yarn"&&t+1<e.length&&e[t+1]==="run"||o==="npx"&&t+1<e.length)return t+1;if(o==="yarn"||o==="pnpm")return t;if(o==="npm"&&t+1<e.length&&e[t+1]==="run"||o==="bun"&&t+1<e.length&&e[t+1]==="run")return t+1;if(/\.(js|ts|mjs|cjs)$/.test(r))return t;if(/^(tsx|ts-node|node|bun)$/.test(o)){for(let n=t+1;n<e.length;n++)if(!e[n].startsWith("-")&&/\.(js|ts|mjs|cjs)$/.test(e[n]))return n;return t}}}for(let t=e.length-1;t>=0;t--)if(!e[t].startsWith("-"))return t;return 1}},Ge=new Ue;var at=s=>s.toLowerCase().replace(/[-_.]/g,"_").replace(/([A-Z])/g,"_$1").replace(/^_+/,"").replace(/_+$/,"").toLowerCase(),de=(s,e)=>{if(!s||typeof s!="string")return e;let t=s.toLowerCase().trim(),r=t.match(/^(\d+(?:\.\d+)?)kb$/),o=t.match(/^(\d+(?:\.\d+)?)mb$/);if(r){let n=Number.parseFloat(r[1]);return Number.isNaN(n)||n<0?e:Math.floor(n*1024)}if(o){let n=Number.parseFloat(o[1]);return Number.isNaN(n)||n<0?e:Math.floor(n*1024*1024)}return e};var ar=s=>{if(!s||s==="-"||s==="--")return null;let e=s.indexOf("=");if(e>0){let t=s.substring(0,e),r=s.substring(e+1);return {name:t,value:pt(r)}}return {name:s,value:true}},pt=s=>{if(s.toLowerCase()==="true")return true;if(s.toLowerCase()==="false")return false;let e=Number(s);return !Number.isNaN(e)&&Number.isFinite(e)?e:s},J=()=>{let s=Ge.getCliArgs(),e=[],t={};if(!s||!s.length)return {args:e,flags:t};for(let r=0;r<s.length;r++){let o=s[r];if(!(!o||typeof o!="string")){if(o.startsWith("-")){let n=ar(o);if(n){if(n.value===true&&r+1<s.length){let i=s[r+1];i&&typeof i=="string"&&!i.startsWith("-")&&(n.value=pt(i),r++);}t[n.name]=n.value;}continue}e.push(o);}}return {args:e,flags:t}};var xe=()=>Ge.getCliArgs()[0]||null;var f=class{static metadata=new WeakMap;static set(e,t,r){this.metadata.has(e)||this.metadata.set(e,new Map),this.metadata.get(e).set(t,r);}static get(e,t){return this.metadata.get(e)?.get(t)}static getAll(e){return this.metadata.get(e)||new Map}static delete(e,t){this.metadata.get(e)?.delete(t.toString());}static clear(e){this.metadata.delete(e);}};var Y="VALIDATION_ERROR",Ts="ARG",dt=J().args.slice(1),Q=s=>(e,t)=>{let r=xe();if(!r||r!==e.commandName)return;let o=t;f.set(e,t,{type:"arg",name:o,description:s.description});let n=dt.length?dt.shift():s.defaultValue;if(s.required&&!n){let i=f.get(e,Y);f.set(e,Y,[...i||[],{type:"arg",name:o,message:"Required argument not provided"}]);return}s.parse&&n&&(n=s.parse(n)),Object.defineProperty(e,t,{value:n,enumerable:true,configurable:true,writable:true});};var X=s=>(e,t)=>{let r=xe();if(!r||r!==e.commandName)return;let o=s.name||t,n=J().flags,i=s.aliases||[],p=[o,...i],d=s.defaultValue;for(let a of p){let c=[a,`-${a}`,`--${a}`];for(let u of c)if(u in n){d=n[u],s.type==="boolean"?d=!!d:s.type==="number"&&(d=Number(d)),s.parse&&(d=s.parse(d));break}if(d!==s.defaultValue)break}if(f.set(e,t,{type:"flag",name:o,aliases:i||[],description:s.description}),s.required&&!d){let a=f.get(e,Y);f.set(e,Y,[...a||[],{type:"flag",name:o,message:"Required flag not provided"}]);return}Object.defineProperty(e,t,{value:d,enumerable:true,configurable:true,writable:true});};X.boolean=s=>X({...s,type:"boolean"});X.string=s=>X({...s,type:"string"});X.number=s=>X({...s,type:"number"});var T=X;var Ke=class{join(...e){switch(g.type){case "node":case "bun":case "deno":return ze__default.default.join(...e);default:throw new Error("Unsupported runtime")}}extName(e){switch(g.type){case "bun":case "node":case "deno":return ze__default.default.extname(e);default:throw new Error("Unsupported runtime")}}resolve(...e){switch(g.type){case "bun":case "node":case "deno":return ze__default.default.resolve(...e);default:throw new Error("Unsupported runtime")}}},y=new Ke;var ce=class{staticChildren;paramChild;wildcardChild;middleware;handler;constructor(){this.staticChildren=new Map,this.paramChild=null,this.wildcardChild=null,this.middleware=null,this.handler=null;}},Ve=class s{trees;routes;middlewares;basePath;constructor(e="",t=[]){this.trees=new Map,this.routes=[],this.middlewares=t,this.basePath=this.normalizeBasePath(e);}getRoutes(){return this.routes.slice()}addOrUpdate(e,t,r,o,n){e=e.toUpperCase();let i=this.trees.get(e);i||(i=new ce,this.trees.set(e,i));let d=t.split("?")[0].replace(/^\/+|\/+$/g,""),a=d.length===0?[]:d.split("/"),c=i;for(let h of a){if(h==="*"){c.wildcardChild||(c.wildcardChild=new ce),c=c.wildcardChild;break}if(h.startsWith(":")){let l=h.slice(1);c.paramChild||(c.paramChild={node:new ce,name:l}),c=c.paramChild.node;continue}c.staticChildren.has(h)||c.staticChildren.set(h,new ce),c=c.staticChildren.get(h);}c.middleware=r,c.handler=o;let u=this.routes.findIndex(h=>h.method===e&&h.path===t);if(u!==-1){this.routes[u].middleware=r,this.routes[u].handler=o;return}this.routes.push({method:e,path:t,middleware:r,handler:o,swaggerOptions:n});}find(e,t){e=e.toUpperCase();let r=this.trees.get(e);if(!r)return null;let n=t.split("?")[0].replace(/^\/+|\/+$/g,""),i=n.length===0?[]:n.split("/"),p={},d=r;for(let a=0;a<i.length;a++){let c=i[a];if(d.staticChildren.has(c)){d=d.staticChildren.get(c);continue}if(d.paramChild){p[d.paramChild.name]=c,d=d.paramChild.node;continue}if(d.wildcardChild){p["*"]=i.slice(a).join("/"),d=d.wildcardChild;break}return null}return !d.handler||!d.middleware?null:{middleware:d.middleware,handler:d.handler,params:p}}get(e,t,r,o){let n=this.joinPath(e),i=typeof t=="function"&&t.length!==3,p=i?t:r,d=i?[]:Array.isArray(t)?t:[t],a=[...this.middlewares,...d],c=i?r:o;this.addOrUpdate("GET",n,a,p,c);}post(e,t,r,o){let n=this.joinPath(e),i=typeof t=="function"&&t.length!==3,p=i?t:r,d=i?[]:Array.isArray(t)?t:[t],a=[...this.middlewares,...d],c=i?r:o;this.addOrUpdate("POST",n,a,p,c);}patch(e,t,r,o){let n=this.joinPath(e),i=typeof t=="function"&&t.length!==3,p=i?t:r,d=i?[]:Array.isArray(t)?t:[t],a=[...this.middlewares,...d],c=i?r:o;this.addOrUpdate("PATCH",n,a,p,c);}put(e,t,r,o){let n=this.joinPath(e),i=typeof t=="function"&&t.length!==3,p=i?t:r,d=i?[]:Array.isArray(t)?t:[t],a=[...this.middlewares,...d],c=i?r:o;this.addOrUpdate("PUT",n,a,p,c);}delete(e,t,r,o){let n=this.joinPath(e),i=typeof t=="function"&&t.length!==3,p=i?t:r,d=i?[]:Array.isArray(t)?t:[t],a=[...this.middlewares,...d],c=i?r:o;this.addOrUpdate("DELETE",n,a,p,c);}options(e,t,r,o){let n=this.joinPath(e),i=typeof t=="function"&&t.length!==3,p=i?t:r,d=i?[]:Array.isArray(t)?t:[t],a=[...this.middlewares,...d],c=i?r:o;this.addOrUpdate("OPTIONS",n,a,p,c);}head(e,t,r,o){let n=this.joinPath(e),i=typeof t=="function"&&t.length!==3,p=i?t:r,d=i?[]:Array.isArray(t)?t:[t],a=[...this.middlewares,...d],c=i?r:o;this.addOrUpdate("HEAD",n,a,p,c);}group(e,t,r){let o=Array.isArray(t)?t:typeof t=="function"?[]:t?[t]:[],n=Array.isArray(t)?r:typeof t=="function"?t:void 0,i=this.joinPath(e),p=new s(i,[...this.middlewares,...o]);n?.(p);for(let d of p.getRoutes())this.addOrUpdate(d.method,d.path,d.middleware,d.handler,d.swaggerOptions);}applyGlobalMiddlewaresToAllRoutes(e){for(let t of this.routes)this.addOrUpdate(t.method,t.path,[...e,...t.middleware||[]],t.handler);}normalizeBasePath(e){if(!e)return "";let t=e.replace(/\s+/g,"");return t=t.replace(/\/+/g,"/"),t.startsWith("/")||(t="/"+t),t.length>1&&(t=t.replace(/\/+$/g,"")),t}joinPath(e){let r=[this.basePath,e].filter(o=>typeof o=="string"&&o.length>0).join("/");return r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r.length>1&&(r=r.replace(/\/+$/g,"")),r}},w=new Ve;var pr=s=>async(e,t,r)=>{for(let o of s)if(!await o.manager.canAccess(o.scope,o.handler,e))return t.unauthorized({error:"Unauthorized"});return r()},_s=(s,e)=>t=>{let r=f.get(t.prototype,"__class__"),o=r?.middlewares||[],n=r?.policies||[],i=f.getAll(t.prototype),p=new t;for(let[d,a]of i.entries()){if(!a.route)continue;let c=t.prototype[d].bind(p),u=s?y.join(s,a.route.path):a.route.path,h=[...n,...a.policies||[]],l=h.length>0?[pr(h)]:[],m=[...o,...l,...a.middlewares||[]];w.addOrUpdate(a.route.method,u,m,c,{service:t.name.replace(/Controller$/,""),...e,...a.documentation});}f.clear(t.prototype);};var Bs=(s,e)=>(t,r,o)=>{let n=f.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"DELETE"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"DELETE"},f.set(t,r,n),o};var Us=(s,e)=>(t,r,o)=>{let n=f.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"GET"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"GET"},f.set(t,r,n),o};var Ks=(s,e)=>(t,r,o)=>{let n=f.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"PATCH"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"PATCH"},f.set(t,r,n),o};var Ws=(s,e)=>(t,r,o)=>{let n=f.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"POST"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"POST"},f.set(t,r,n),o};var Xs=(s,e)=>(t,r,o)=>{let n=f.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"PUT"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"PUT"},f.set(t,r,n),o};var ro=s=>(e,t,r)=>{if(typeof t>"u"){let n=f.get(e.prototype,"__class__");if(n||(n={middlewares:[]}),n.middlewares||(n.middlewares=[]),!s)throw new Error(`Middleware ${String(s)} not found, are you sure you defined it before using it?`);return Array.isArray(s)||(s=[s]),n.middlewares.push(...s),f.set(e.prototype,"__class__",n),e}let o=f.get(e,t);return o||(o={middlewares:[]}),o.middlewares||(o.middlewares=[]),Array.isArray(s)||(s=[s]),o.middlewares.push(...s),f.set(e,t,o),r};var D=(s,e,t=false)=>{let{success:r,data:o,error:n}=s.safeParse(e);if(!r){if(t)return o;throw n}return o};var ct=Symbol("serializeWrapped"),ue=Symbol("serializeMetadata"),po=(s,e)=>(t,r,o)=>{let n=f.get(t,r)||{middlewares:[],route:{}};n.documentation||(n.documentation={}),n.documentation.responses||(n.documentation.responses={}),n.serializeOptions||(n.serializeOptions={});let i=Number(e?.status??200);if(n.documentation.responses[i]=s,n.serializeOptions[i]=e?.safe??true,f.set(t,r,n),o.value[ue]||(o.value[ue]={}),o.value[ue][i]={name:r,schema:s,safe:e?.safe??true},!o.value[ct]){let p=o.value,d=async function(...a){let c=a[1];await p.apply(this,a);let u=c.responseStatus,h=d[ue],l=h?.[u]?.schema,m=h?.[u]?.safe??true;if(l&&!m){let v=c.getBody();try{c.send(D(l,v,m));}catch(P){if(P instanceof zod.ZodError){c.internalServerError({received:v,schema:l,error:P});return}throw P}}};d[ct]=true,d[ue]=p[ue],o.value=d;}};var ee=s=>(e,t,r)=>{let o=r.value,n=f.get(e,t);return n||(n={middlewares:[],route:{}}),n.documentation||(n.documentation={}),s.body&&(n.documentation.requestBody=s.body),s.query&&(n.documentation.query=s.query),f.set(e,t,n),r.value=async function(...i){let p=i[0],d=i[1];try{let a,c,u;s.body&&(a=p.validate(s.body,s.safe)),s.query&&(c=p.validateQuery(s.query,s.safe)),s.all&&(u=p.validateAll(s.all,s.safe));let h=[...i];return a!==void 0&&h.push(a),c!==void 0&&h.push(c),u!==void 0&&h.push(u),o.apply(this,h)}catch(a){if(!(a instanceof zod.ZodError))throw a;return s.customError?d.status(s.customError.status||400).json({received:p.body,schema:s.body,error:a}):d.badRequest(a)}},r};ee.query=(s,e)=>ee({query:s,customError:e});ee.body=(s,e)=>ee({body:s,customError:e});ee.all=(s,e)=>ee({all:s,customError:e});var mo=ee;var te=class{static options={connection:{}}},ut=s=>{te.options=s??{connection:{}};};var L=class extends O{constructor(...e){super(`Library not installed: ${e.join(", ")}, try run npm install ${e.join(" ")}`);}};var Ze=class{randomUUID(){return crypto.randomUUID()}},I=new Ze;var Oe=class{queues=new Map;workers=new Map;async publish(e,t,r){let o=await this.getQueue(e),n=I.randomUUID();return await o.add(e,t,{jobId:n,...te.options?.defaultJobOptions,...r}),{id:n}}async subscribe(e,t){if(this.workers.has(e))throw new Error(`[BullMQ] Already subscribed to topic "${e}"`);let{errorHandler:r,...o}=te.options??{},n=await this.getBullMQClient(),i=new n.Worker(e,async p=>{try{await t(p.data);}catch(d){await r?.(p,d)??Promise.reject(d);}},{...o});this.workers.set(e,i);}async getQueue(e){if(!this.queues.has(e)){let t=await import('bullmq').catch(()=>{throw new L("bullmq","ioredis")}),r=new t.Queue(e,{...te.options||{connection:{}}});this.queues.set(e,r);}return this.queues.get(e)}async getBullMQClient(){return this.bullmqClient||(this.bullmqClient=await import('bullmq').catch(()=>{throw new L("bullmq","ioredis")})),this.bullmqClient}};var U=class{static options={}},lt=s=>{U.options=s??{};};var Te=class{createdQueues=new Set;async publish(e,t,r){let o=await this.getBoss();await this.ensureQueue(String(e));let n=r||{},i=await o.send(String(e),t,n);return {id:String(i??"")}}async subscribe(e,t){let r=await this.getBoss();await this.ensureQueue(String(e));let o=U.options;o.errorHandler&&r.on("error",o.errorHandler),await r.work(String(e),async n=>{let i=Array.isArray(n)?n:[n];for(let p of i)await t(p.data);});}async getBoss(){if(this.boss)return this.boss;let e=await import('pg-boss').catch(()=>{throw new L("pg-boss","pg")}),r=e.default??e,{connectionString:o,boss:n}=U.options,i=o??n,p=new r(i);return U.options?.errorHandler&&p.on("error",U.options.errorHandler),await p.start(),this.boss=p,this.boss}async ensureQueue(e){if(this.createdQueues.has(e))return;let t=await this.getBoss();typeof t.createQueue=="function"&&await t.createQueue(e),this.createdQueues.add(e);}};var re=class{static options={}},mt=s=>{re.options=s??{};};var Pe=class{consumers=new Map;client;async publish(e,t,r){let{...o}=r??{},n=await this.getClient(),{SendMessageCommand:i}=await this.getSqsLib(),p=await this.resolveQueueUrl(String(e));if(!p)throw new Error(`[SQS] Queue url not configured for topic "${String(e)}"`);let d=new i({MessageBody:JSON.stringify(t),MessageAttributes:{topic:{DataType:"String",StringValue:String(e)}},...o,QueueUrl:p});return {id:(await n.send(d)).MessageId??""}}async subscribe(e,t){if(this.consumers.has(String(e)))throw new Error(`[SQS] Already subscribed to topic "${String(e)}"`);let r=re.options,o=await this.getSqsConsumerLib(),n={...r.consumer||{},sqs:await this.getClient(),queueUrl:await this.resolveQueueUrl(String(e)),handleMessage:async d=>{let a=JSON.parse(d.Body||"{}");await t(a);}},i=o.Consumer.create(n),p=r.errorHandler;p&&(i.on("error",p),i.on("processing_error",p)),i.start(),this.consumers.set(String(e),i);}async getClient(){if(this.client)return this.client;let{SQSClient:e}=await this.getSqsLib(),t=re.options.client;return this.client=new e(t??{}),this.client}async getSqsLib(){return this.sqsLib||(this.sqsLib=await import('@aws-sdk/client-sqs').catch(()=>{throw new L("@aws-sdk/client-sqs","sqs-consumer")})),this.sqsLib}async getSqsConsumerLib(){return this.sqsConsumerLib||(this.sqsConsumerLib=await import('sqs-consumer').catch(()=>{throw new L("sqs-consumer")})),this.sqsConsumerLib}async resolveQueueUrl(e){let r=re.options.consumer?.queueUrlMap?.[e];if(!r)throw new Error(`[SQS] Queue url not configured for topic "${e}"`);return r}};var G=class{static map=new Map;static{this.map.set("bullmq",new Oe),this.map.set("sqs",new Pe),this.map.set("pgboss",new Te);}static getProvider(e){if(!this.map.has(e))throw new Error(`[QueueSubscriber] Provider ${e} not found`);return this.map.get(e)}static setProvider(e,t){this.map.set(e,t);}};var se=class{static scheduledSubscribers=[];static register(e,t,r,o){this.scheduledSubscribers.push({name:e,topic:t,handler:r,provider:o?.provider??"bullmq"});}static async run(){if(exports.logger.info("Subscribing queue handlers"),!this.scheduledSubscribers.length){exports.logger.info("No queue handlers to subscribe");return}for(let{topic:e,handler:t,provider:r}of this.scheduledSubscribers)exports.logger.info(`Subscribing to queue: ${String(e)}`),await G.getProvider(r).subscribe(e,t);exports.logger.info("Queue handlers subscribed");}static async massiveImportQueues(e){let t=[];for(let r of e){let o=await glob.glob(r,{absolute:true,cwd:q.getCwd()});t.push(...o);}await Promise.all(t.map(async r=>{await import(r).catch(o=>{exports.logger.error(`Error importing queue handler: ${r}`),exports.logger.error(o);});}));}};var le=(s,e)=>function(t,r,o){let n=o.value,i=async p=>{let d=new t.constructor;return n.apply(d,[p])};return se.register(`${t.constructor.name}.${r}`,e,i,{provider:s}),o};le.bullmq=s=>le("bullmq",s);le.sqs=s=>le("sqs",s);le.pgboss=s=>le("pgboss",s);var oe=async(s,e,t,r)=>G.getProvider(s).publish(e,t,r??{});oe.bullmq=async(s,e,t)=>oe("bullmq",s,e,t);oe.sqs=async(s,e,t)=>oe("sqs",s,e,t);oe.pgboss=async(s,e,t)=>oe("pgboss",s,e,t);var Io=oe;var Zo=s=>{let e=["bullmq","pgboss","sqs"];s.bullmq&&ut(s.bullmq),s.pgboss&&lt(s.pgboss),s.sqs&&mt(s.sqs);for(let t of Object.keys(s)){let r=t;e.includes(r)||G.setProvider(r,s[r]);}};var We=class{exit(e){switch(g.type){case "bun":case "node":process.exit(e);case "deno":Deno.exit(e);default:throw new Error("Unsupported runtime")}}},Je=new We;var E=class{static commandName=this.name;static description="";static help=[];static options={keepAlive:false};static args=J().args.slice(1);static flags=J().flags;static logger=exports.logger;static handle(){throw new Error(`Handle method not implemented in command class ${this.name}`)}static handleHelpFlag(e){let t=["-h","--help"];if(!Object.keys(e).some(a=>t.includes(a)))return;let o=this.commandName,n=this.description||"No description available",i=this.help||[],p=this.options,d=this.generateHelpOutput({name:o,description:n,helpText:i,options:p,args:this.args,flags:this.flags},this);console.log(d),Je.exit(0);}static generateHelpOutput=(e,t)=>{let{name:r,description:o,helpText:n,options:i,args:p,flags:d}=e,a={title:"\x1B[1;36m",subtitle:"\x1B[1;33m",description:"\x1B[0;37m",code:"\x1B[0;32m",flag:"\x1B[0;35m",reset:"\x1B[0m",error:"\x1B[0;31m",success:"\x1B[0;32m",info:"\x1B[0;34m"},c=[`${a.title}${r}${a.reset}`,`${a.description}${o}${a.reset}`,"",`${a.subtitle}Usage:${a.reset}`,` ${a.code}${r}${a.reset} [options] [arguments]`,"",`${a.subtitle}Options:${a.reset}`,` ${a.flag}-h, --help${a.reset} Show this help message`,"",`${a.subtitle}Command Options:${a.reset}`,` ${a.flag}keepAlive${a.reset} ${i?.keepAlive??false?a.success+"Enabled"+a.reset:a.error+"Disabled"+a.reset}`,""];if(n){let m=Array.isArray(n)?n:[n];c.push(`${a.subtitle}Help:${a.reset}`),m.forEach(v=>{c.push(` ${a.description}${v}${a.reset}`);}),c.push("");}let u=f.getAll(t),h=Array.from(u.values()).filter(m=>m.type==="arg"),l=Array.from(u.values()).filter(m=>m.type==="flag");return h.length&&(c.push(`${a.subtitle}Available Arguments:${a.reset}`),h.forEach(m=>{let v=m.required?` ${a.error}(required)${a.reset}`:"",P=m.description?` ${a.description}${m.description}${a.reset}`:"";c.push(` ${a.code}${m.name}${a.reset}${v}${P}`);}),c.push("")),l.length&&(c.push(`${a.subtitle}Available Flags:${a.reset}`),l.forEach(m=>{m.aliases&&!Array.isArray(m.aliases)&&(m.aliases=[m.aliases]);let v=m.aliases.length?` ${a.flag}(${m.aliases.join(", ")})${a.reset}`:"",P=m.required?` ${a.error}(required)${a.reset}`:"",C=m.description?` ${a.description}${m.description}${a.reset}`:"";c.push(` ${a.flag}--${m.name}${v}${a.reset}${P}${C}`);}),c.push("")),((p?.length??0)>0||d&&Object.keys(d).length>0)&&(c.push(`${a.subtitle}Current Context:${a.reset}`),p?.length&&c.push(` ${a.info}Provided Arguments:${a.reset} ${a.code}${p.join(" ")}${a.reset}`),d&&Object.keys(d).length>0&&(c.push(` ${a.info}Provided Flags:${a.reset}`),Object.keys(d).forEach(m=>{let v=d[m],P=v!=null?` = ${a.code}${v}${a.reset}`:"";c.push(` ${a.flag}${m}${a.reset}${P}`);})),c.push("")),n&&(Array.isArray(n)?n.some(m=>m.includes("example")):n.includes("example"))&&(c.push(`${a.subtitle}Examples:${a.reset}`),(Array.isArray(n)?n.filter(v=>v.includes("example")):[n.split("example")[1].trim()]).forEach(v=>{c.push(` ${a.code}${v}${a.reset}`);}),c.push("")),c.join(`
2
+ `)};static validateContext=e=>{let t=Array.from(f.get(e,Y)||[]);if(t.length){let r={error:"\x1B[0;31m",title:"\x1B[1;31m",reset:"\x1B[0m",info:"\x1B[0;34m",code:"\x1B[0;32m"};console.error(`${r.title}\u274C Validation Errors:${r.reset}`),console.error(""),t.forEach((o,n)=>{let i=`${r.info}${n+1}.${r.reset}`,p=`${r.error}${o.type.toUpperCase()}${r.reset}`,d=`${r.code}${o.name}${r.reset}`;console.error(` ${i} ${p} ${d}: ${r.error}${o.message}${r.reset}`);}),console.error(""),console.error(`${r.info}\u{1F4A1} Tip: Use --help for usage information${r.reset}`),Je.exit(1);}}};var Ye=class{async mkdir(e,t){switch(g.type){case "bun":case "node":await(await import('fs/promises')).mkdir(e,{recursive:t?.recursive??false,mode:t?.mode});break;case "deno":typeof t?.mode=="string"&&(t.mode=Number.parseInt(t.mode)),await Deno.mkdir(e,{recursive:t?.recursive??false,mode:t?.mode});break}}async exists(e){switch(g.type){case "node":return (await import('fs')).existsSync(e);case "bun":return Bun.file(e).exists();case "deno":return Deno.stat(e).then(()=>true).catch(()=>false);default:throw new Error("Unsupported runtime")}}async readFile(e){switch(g.type){case "node":let r=await(await import('fs/promises')).readFile(e);return new Uint8Array(r);case "bun":let o=await Bun.file(e).arrayBuffer();return new Uint8Array(o);case "deno":return new Uint8Array(await Deno.readFile(e))}}async writeFile(e,t){switch(g.type){case "node":await(await import('fs/promises')).writeFile(e,t);break;case "bun":await Bun.write(e,t);break;case "deno":await Deno.writeFile(e,t);break}}async stat(e){switch(g.type){case "node":let r=await(await import('fs/promises')).stat(e);return {isDirectory:r.isDirectory(),isFile:r.isFile(),isSymbolicLink:r.isSymbolicLink(),size:r.size};case "bun":let o=await Bun.file(e).stat();return {isDirectory:o.isDirectory(),isFile:o.isFile(),isSymbolicLink:o.isSymbolicLink(),size:o.size};case "deno":let n=await Deno.stat(e);return {isDirectory:n.isDirectory,isFile:n.isFile,isSymbolicLink:false,size:n.size}}}async unlink(e){switch(g.type){case "node":await(await import('fs/promises')).unlink(e);break;case "bun":await Bun.file(e).delete();break;case "deno":await Deno.remove(e);break;default:throw new Error("Unsupported runtime")}}},S=new Ye;var me=class extends E{static commandName="generate-command";static description="Generate a new command in the specified path";static help=["Generate a new cli command in the specified path","Example: npx balda generate-command my-command -p src/commands"];static path="src/commands";static name;static async handle(){let e=this.getCommandTemplate();this.path=y.join(this.path,`${this.name}.ts`),await S.exists(y.join(process.cwd(),this.path))||await S.mkdir(y.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await S.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Command ${this.name} created successfully at ${this.path}`);}static getCommandTemplate(){return `import { Command, CommandOptions } from "balda-js";
3
3
 
4
4
  export default class extends Command {
5
5
  static commandName = "${this.name}";
@@ -13,7 +13,7 @@ export default class extends Command {
13
13
  static async handle(): Promise<void> {
14
14
  // Implement your command logic here
15
15
  }
16
- }`}};x([L({description:"The name of the command to generate",required:true})],le,"name");var oe=class extends E{static commandName="generate-plugin";static description="Generate a new plugin in the specified path";static help=["Generate a new plugin in the specified path","Example: npx balda generate-plugin my-plugin -p src/plugins"];static pluginName;static pluginPath;static async handle(){let e=this.getPluginTemplate();this.pluginPath=y.join(this.pluginPath,`${this.pluginName}.ts`),await S.exists(y.join(process.cwd(),this.pluginPath))||await S.mkdir(y.join(process.cwd(),this.pluginPath.split("/").slice(0,-1).join("/")),{recursive:true}),await S.writeFile(this.pluginPath,new TextEncoder().encode(e)),this.logger.info(`Plugin ${this.name} created successfully at ${this.pluginPath}`);}static getPluginTemplate(){return `import { BasePlugin, Request, Response, NextFunction, ServerRouteMiddleware } from "balda-js";
16
+ }`}};R([Q({description:"The name of the command to generate",required:true})],me,"name");var ne=class extends E{static commandName="generate-plugin";static description="Generate a new plugin in the specified path";static help=["Generate a new plugin in the specified path","Example: npx balda generate-plugin my-plugin -p src/plugins"];static pluginName;static pluginPath;static async handle(){let e=this.getPluginTemplate();this.pluginPath=y.join(this.pluginPath,`${this.pluginName}.ts`),await S.exists(y.join(process.cwd(),this.pluginPath))||await S.mkdir(y.join(process.cwd(),this.pluginPath.split("/").slice(0,-1).join("/")),{recursive:true}),await S.writeFile(this.pluginPath,new TextEncoder().encode(e)),this.logger.info(`Plugin ${this.name} created successfully at ${this.pluginPath}`);}static getPluginTemplate(){return `import { BasePlugin, Request, Response, NextFunction, ServerRouteMiddleware } from "balda-js";
17
17
 
18
18
  export default class extends BasePlugin {
19
19
  async handle(): Promise<ServerRouteMiddleware> {
@@ -22,14 +22,14 @@ export default class extends BasePlugin {
22
22
  await next();
23
23
  };
24
24
  }
25
- }`}};x([L({description:"The name of the plugin to generate",required:true})],oe,"pluginName"),x([T({description:"The path to the plugin to generate, default is src/plugins",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/plugins"})],oe,"pluginPath");var ne=class extends E{static commandName="generate-cron";static description="Generate a new cron job in the specified path";static help=["Generate a new cron job in the specified path","Example: npx balda generate-cron my-cron -p src/cron"];static fileName;static path;static async handle(){let e=this.getCronTemplate();this.path=y.join(this.path,`${this.fileName}.ts`),await S.exists(y.join(process.cwd(),this.path))||await S.mkdir(y.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await S.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Cron job ${this.fileName} created successfully at ${this.path}`);}static getCronTemplate(){return `import { cron } from "balda-js";
25
+ }`}};R([Q({description:"The name of the plugin to generate",required:true})],ne,"pluginName"),R([T({description:"The path to the plugin to generate, default is src/plugins",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/plugins"})],ne,"pluginPath");var ie=class extends E{static commandName="generate-cron";static description="Generate a new cron job in the specified path";static help=["Generate a new cron job in the specified path","Example: npx balda generate-cron my-cron -p src/cron"];static fileName;static path;static async handle(){let e=this.getCronTemplate();this.path=y.join(this.path,`${this.fileName}.ts`),await S.exists(y.join(process.cwd(),this.path))||await S.mkdir(y.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await S.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Cron job ${this.fileName} created successfully at ${this.path}`);}static getCronTemplate(){return `import { cron } from "balda-js";
26
26
 
27
27
  export default class {
28
28
  @cron("* * * * *")
29
29
  handle() {
30
30
  // Implement your cron job logic here
31
31
  }
32
- }`}};x([L({description:"The name of the cron job file to generate",required:true})],ne,"fileName"),x([T({description:"The path to the cron job to generate, default is src/cron",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/cron"})],ne,"path");var lt=async()=>await S.exists(y.join(process.cwd(),"yarn.lock"))?["yarn","add","-D"]:await S.exists(y.join(process.cwd(),"pnpm-lock.yaml"))?["pnpm","add","-D"]:await S.exists(y.join(process.cwd(),"package-lock.json"))?["npm","install","-D"]:await S.exists(y.join(process.cwd(),"bun.lockb"))?["bun","add","-D"]:await S.exists(y.join(process.cwd(),"deno.lock"))?["deno","add","-D"]:["npm","install","-D"];var ie=class extends E{static commandName="init";static description="Initialize a new balda project in the current directory";static help=["Initialize a new balda project, it is given for granted that balda-js is installed in the project as a dependency","All the files are created in the /src directory (created if not exists)","It adds a server.ts for the file instance and a index.ts for the entry point with a dummy hello world route","Example: npx balda init -p ./src -t true"];static srcPath;static typescript;static devDependencies=["esbuild","esbuild-plugin-copy","tsx","typescript"];static async handle(){this.logger.info("Initializing project...");let[e,t,r]=await lt();["npm","yarn","pnpm"].includes(e)&&(this.logger.info(`Installing dev dependencies with ${e}...`),child_process.execSync(`${e} ${t} ${this.devDependencies.join(" ")} -${r}`,{stdio:"inherit"}));let o=this.typescript?"ts":"js",n=this.getServerTemplate(),i=this.getIndexTemplate();S.exists(this.srcPath)||await S.mkdir(this.srcPath,{recursive:true}),this.logger.info(`Creating server.${o} file...`),await S.writeFile(`${this.srcPath}/server.${o}`,new TextEncoder().encode(n)),this.logger.info(`Creating index.${o} file...`),await S.writeFile(`${this.srcPath}/index.${o}`,new TextEncoder().encode(i)),this.logger.info("Project initialized successfully!");}static getServerTemplate(){return `import { Server } from "balda-js";
32
+ }`}};R([Q({description:"The name of the cron job file to generate",required:true})],ie,"fileName"),R([T({description:"The path to the cron job to generate, default is src/cron",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/cron"})],ie,"path");var ht=async()=>await S.exists(y.join(process.cwd(),"yarn.lock"))?["yarn","add","-D"]:await S.exists(y.join(process.cwd(),"pnpm-lock.yaml"))?["pnpm","add","-D"]:await S.exists(y.join(process.cwd(),"package-lock.json"))?["npm","install","-D"]:await S.exists(y.join(process.cwd(),"bun.lockb"))?["bun","add","-D"]:await S.exists(y.join(process.cwd(),"deno.lock"))?["deno","add","-D"]:["npm","install","-D"];var ae=class extends E{static commandName="init";static description="Initialize a new balda project in the current directory";static help=["Initialize a new balda project, it is given for granted that balda-js is installed in the project as a dependency","All the files are created in the /src directory (created if not exists)","It adds a server.ts for the file instance and a index.ts for the entry point with a dummy hello world route","Example: npx balda init -p ./src -t true"];static srcPath;static typescript;static devDependencies=["esbuild","esbuild-plugin-copy","tsx","typescript"];static async handle(){this.logger.info("Initializing project...");let[e,t,r]=await ht();["npm","yarn","pnpm"].includes(e)&&(this.logger.info(`Installing dev dependencies with ${e}...`),child_process.execSync(`${e} ${t} ${this.devDependencies.join(" ")} -${r}`,{stdio:"inherit"}));let o=this.typescript?"ts":"js",n=this.getServerTemplate(),i=this.getIndexTemplate();S.exists(this.srcPath)||await S.mkdir(this.srcPath,{recursive:true}),this.logger.info(`Creating server.${o} file...`),await S.writeFile(`${this.srcPath}/server.${o}`,new TextEncoder().encode(n)),this.logger.info(`Creating index.${o} file...`),await S.writeFile(`${this.srcPath}/index.${o}`,new TextEncoder().encode(i)),this.logger.info("Project initialized successfully!");}static getServerTemplate(){return `import { Server } from "balda-js";
33
33
 
34
34
  const serverInstance = new Server({
35
35
  port: 80,
@@ -47,11 +47,11 @@ export { serverInstance as server };
47
47
  server.listen(({ url }) => {
48
48
  console.log(\`Server is running on \${url}\`);
49
49
  });
50
- `}};x([T.string({description:"The path to the project, default is the current directory /src",aliases:"p",name:"path",required:false,defaultValue:"./src"})],ie,"srcPath"),x([T.boolean({description:"Whether to use typescript, default is true",aliases:"t",name:"typescript",required:false,defaultValue:true})],ie,"typescript");var ve=class extends E{static commandName="list";static description="List all available commands";static help=["Display all registered Balda CLI commands with their descriptions","Example: npx balda list"];static async handle(){let e=mt.getCommands();console.log(`
50
+ `}};R([T.string({description:"The path to the project, default is the current directory /src",aliases:"p",name:"path",required:false,defaultValue:"./src"})],ae,"srcPath"),R([T.boolean({description:"Whether to use typescript, default is true",aliases:"t",name:"typescript",required:false,defaultValue:true})],ae,"typescript");var Se=class extends E{static commandName="list";static description="List all available commands";static help=["Display all registered Balda CLI commands with their descriptions","Example: npx balda list"];static async handle(){let e=ft.getCommands();console.log(`
51
51
  \u2728 Available Balda Commands:
52
52
  `);let t=Math.max(...e.map(r=>r.commandName.length));for(let r of e){let o=r.commandName.padEnd(t+2),n=r.description||"No description available";console.log(` \x1B[36m${o}\x1B[0m ${n}`);}console.log(`
53
53
  \x1B[90mRun 'npx balda <command> -h' for more information on a specific command.\x1B[0m
54
- `);}};var z=class extends E{static commandName="generate-queue";static description="Generate a new queue in the specified path";static help=["Generate a new queue in the specified path","Example: npx balda generate-queue my-queue -p src/queues --provider bullmq"];static queueName;static path;static provider;static async handle(){let e=this.queueName.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/),t=this.getQueueTemplate(!!e);this.path=y.join(this.path,`${nt(this.queueName)}.ts`),await S.exists(y.join(process.cwd(),this.path))||await S.mkdir(y.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await S.writeFile(this.path,new TextEncoder().encode(t)),this.logger.info(`Queue ${this.queueName} created successfully at ${this.path}`);}static getQueueTemplate(e){return `import { queue, logger } from "balda-js";
54
+ `);}};var z=class extends E{static commandName="generate-queue";static description="Generate a new queue in the specified path";static help=["Generate a new queue in the specified path","Example: npx balda generate-queue my-queue -p src/queues --provider bullmq"];static queueName;static path;static provider;static async handle(){let e=this.queueName.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/),t=this.getQueueTemplate(!!e);this.path=y.join(this.path,`${at(this.queueName)}.ts`),await S.exists(y.join(process.cwd(),this.path))||await S.mkdir(y.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await S.writeFile(this.path,new TextEncoder().encode(t)),this.logger.info(`Queue ${this.queueName} created successfully at ${this.path}`);}static getQueueTemplate(e){return `import { queue, logger } from "balda-js";
55
55
 
56
56
  export type Payload = {
57
57
  // Add your payload here
@@ -72,23 +72,23 @@ export default class {
72
72
  this.logger.info({ payload }, 'Payload received');
73
73
  return Promise.resolve();
74
74
  }
75
- }`}};x([L({description:"The name of the queue to generate",required:true})],z,"queueName"),x([T({description:"The path to the queue to generate, default is src/queues",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/queues"})],z,"path"),x([T({description:"The provider of the queue to generate, default is bullmq",type:"string",aliases:["pr"],name:"provider",required:false,defaultValue:"bullmq"})],z,"provider");var A=class extends E{static commandName="build";static description="Build the project for production, node.js only";static help=["Build the project for production, node.js only","It will create a production build of the project in the dist directory","Must have a tsconfig.json file in the root of the project","Must have esbuild installed as a dependency while running the command","Must have esbuild-plugin-copy installed as a dependency while running the command if you want to copy assets to the output directory","Example: npx balda build -t ./tsconfig.json -a ./assets"];static clearDist;static entry;static output;static tsconfig;static assets;static format;static packages;static sourcemap;static async handle(){typeof process===void 0&&(this.logger.error("Build command is only supported in node.js"),process.exit(1)),["esm","cjs"].includes(this.format)||(this.logger.error("Invalid format, must be 'esm' or 'cjs'"),process.exit(1)),["bundle","external"].includes(this.packages)||(this.logger.error("Invalid packages, must be 'bundle' or 'external'"),process.exit(1));let e=await import('esbuild').catch(i=>{throw this.logger.error("esbuild is not installed, please install it with `npm install -D esbuild` to use the build command"),new Error("esbuild is not installed")}),t=Qe__default.default.join(this.output,"assets"),r=[];if(this.assets){let{copy:i}=await import('esbuild-plugin-copy').catch(p=>{throw this.logger.error("esbuild-plugin-copy is not installed, please install it with `npm install -D esbuild-plugin-copy` to use the build command"),new Error("esbuild-plugin-copy is not installed")});Te__default.default.existsSync(t)||Te__default.default.mkdirSync(t,{recursive:true}),r.push(i({assets:{from:this.assets,to:t}}));}this.clearDist&&Te__default.default.existsSync(this.output)&&(this.logger.info("Clearing dist directory..."),Te__default.default.rmSync(this.output,{recursive:true})),this.logger.info("Building project...");let o=Qe__default.default.join(this.output,"server.js"),n=await e.build({tsconfig:this.tsconfig,entryPoints:[this.entry],bundle:true,platform:"node",outfile:o,minify:true,sourcemap:this.sourcemap,plugins:r,format:this.format,packages:this.packages});n.errors.length&&(this.logger.error(JSON.stringify({message:"Failed to build the project",errors:n.errors},null,2)),process.exit(1)),n.warnings.length&&this.logger.warn(JSON.stringify({message:"Failed to build the project",warnings:n.warnings},null,2)),this.logger.info(JSON.stringify({message:`Project built successfully in ${o}`,output:o,assets:!!this.assets},null,2)),process.exit(0);}};x([T({type:"boolean",aliases:["c"],name:"clear-dist",required:false,defaultValue:false,description:"Whether to clear the dist directory before building the project"})],A,"clearDist"),x([T({type:"string",aliases:["e"],name:"entry",required:false,defaultValue:"./src/index.ts",description:"The entry point of the project, default is ./src/index.ts"})],A,"entry"),x([T({type:"string",aliases:["o"],name:"output",required:false,defaultValue:"./dist",description:"The path to the output directory, default is ./dist"})],A,"output"),x([T({type:"string",aliases:["t"],name:"tsconfig",required:false,defaultValue:"./tsconfig.json",description:"The path to the tsconfig.json file, default is ./tsconfig.json"})],A,"tsconfig"),x([T({type:"string",aliases:["a"],name:"assets",required:false,description:"The path to the assets directory that will be loaded in the production build"})],A,"assets"),x([T({type:"string",aliases:["f"],name:"format",required:false,defaultValue:"esm",description:"The format to build the project, default is esm, can be 'esm' or 'cjs'"})],A,"format"),x([T({type:"string",aliases:["p"],name:"packages",required:false,defaultValue:"external",description:"Weather to bundle node_modules or not, default is external, can be 'bundle' or 'external'"})],A,"packages"),x([T({type:"boolean",aliases:["s"],name:"sourcemap",required:false,defaultValue:true,description:"Whether to generate sourcemaps or not, default is true"})],A,"sourcemap");var We=class s{commands;static commandsPattern="src/commands/**/*.{ts,js}";static logger=exports.logger;constructor(){this.commands=new Map;}static getInstance(){return new s}static setCommandsPattern(e){this.commandsPattern=e;}getCommand(e){return this.commands.get(e)??null}getCommands(){return Array.from(this.commands.values())}async loadCommands(e){s.logger.info(`Loading commands from ${e}`);let t=await glob.glob(e,{absolute:true,cwd:$.getCwd()});if(t.some(o=>o.endsWith(".ts")))try{let{register:o}=await import('module');o("ts-node/esm",(typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));}catch{s.logger.error("Failed to register ts-node/esm, you need to install it in your project in order to use typescript in the cli\ntry running: `npm install -D ts-node`"),process.exit(1);}for(let o of t){let n=await import(o).then(i=>i.default?i.default:i).catch(i=>(s.logger.error(`Error loading command ${o}: ${i}`),null));n&&this.commands.set(n.commandName,n);}let r=[oe,le,ne,z,ie,ve,A];for(let o of r)this.commands.set(o.commandName,o);}},mt=We.getInstance();var Pe=class extends Request{};var _=class s extends Pe{static fromRequest(e){return new s(e.url,{method:e.method,body:e.body,headers:e.headers})}static enrichRequest(e){return e.validate=(t,r=false)=>(typeof t=="function"&&(t=t(zod.z)),D(t,e.body||{},r)),e.validateQuery=(t,r=false)=>(typeof t=="function"&&(t=t(zod.z)),D(t,e.query||{},r)),e.validateAll=(t,r=false)=>(typeof t=="function"&&(t=t(zod.z)),D(t,{...e.body?{body:e.body}:{},...e.query?{query:e.query}:{}},r)),e.file=t=>e.files.find(r=>r.formName===t)??null,e.files=[],e.saveSession=async()=>{},e.destroySession=async()=>{},e.session={},e.cookies={},e.cookie=t=>e.cookies[t],e}file=e=>this.files.find(t=>t.formName===e)??null;cookies={};cookie=e=>this.cookies[e];timeout;session=void 0;saveSession=async()=>{};destroySession=async()=>{};ip;files=[];params={};query={};get id(){return this._id||(this._id=U.randomUUID()),this._id}body;validate(e,t=false){return typeof e=="function"&&(e=e(zod.z)),D(e,this.body||{},t)}validateQuery(e,t=false){return typeof e=="function"&&(e=e(zod.z)),D(e,this.query||{},t)}validateAll(e,t=false){return typeof e=="function"&&(e=e(zod.z)),D(e,{...this.body?{body:this.body}:{},...this.query?{query:this.query}:{}},t)}};var fe=class{get(e){switch(g.type){case "node":case "bun":case "deno":return process.env[e]??"";default:throw new Error(`Unsupported runtime: ${g.type}`)}}getEnvironment(){switch(g.type){case "node":case "deno":case "bun":return Object.fromEntries(Object.entries(process.env).filter(([e,t])=>t!==void 0))}}};var lr=new fe,R=s=>{let e=lr.get("NODE_ENV")!=="production";return {code:s.name||"INTERNAL_ERROR",message:s.message,...e&&{stack:s.stack,cause:s.cause}}};var he=class extends O{constructor(e,t){super(`METHOD_NOT_ALLOWED: Cannot ${t} ${e}`);}};var M=class extends O{constructor(e,t){super(`ROUTE_NOT_FOUND: Cannot ${t} ${e}`);}};var Ye=class{file(e,t){switch(g.type){case "bun":case "node":return Te__default.default.readFileSync(e,t);case "deno":return Deno.readFileSync(e);default:throw new Error("Unsupported runtime")}}},Ce=new Ye;var ht=new Map([[".html","text/html"],[".htm","text/html"],[".css","text/css"],[".js","application/javascript"],[".mjs","application/javascript"],[".cjs","application/javascript"],[".ts","application/typescript"],[".jsx","text/jsx"],[".tsx","text/tsx"],[".json","application/json"],[".xml","application/xml"],[".yaml","application/yaml"],[".yml","application/yaml"],[".csv","text/csv"],[".txt","text/plain"],[".md","text/markdown"],[".markdown","text/markdown"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".gif","image/gif"],[".svg","image/svg+xml"],[".ico","image/x-icon"],[".webp","image/webp"],[".avif","image/avif"],[".bmp","image/bmp"],[".tiff","image/tiff"],[".tif","image/tiff"],[".heic","image/heic"],[".heif","image/heif"],[".mp4","video/mp4"],[".webm","video/webm"],[".avi","video/x-msvideo"],[".mov","video/quicktime"],[".mkv","video/x-matroska"],[".wmv","video/x-ms-wmv"],[".flv","video/x-flv"],[".m4v","video/x-m4v"],[".mpeg","video/mpeg"],[".mpg","video/mpeg"],[".3gp","video/3gpp"],[".mp3","audio/mpeg"],[".wav","audio/wav"],[".ogg","audio/ogg"],[".flac","audio/flac"],[".aac","audio/aac"],[".m4a","audio/mp4"],[".wma","audio/x-ms-wma"],[".opus","audio/opus"],[".mid","audio/midi"],[".midi","audio/midi"],[".woff","font/woff"],[".woff2","font/woff2"],[".ttf","font/ttf"],[".otf","font/otf"],[".eot","application/vnd.ms-fontobject"],[".pdf","application/pdf"],[".doc","application/msword"],[".docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"],[".xls","application/vnd.ms-excel"],[".xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],[".ppt","application/vnd.ms-powerpoint"],[".pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation"],[".odt","application/vnd.oasis.opendocument.text"],[".ods","application/vnd.oasis.opendocument.spreadsheet"],[".odp","application/vnd.oasis.opendocument.presentation"],[".rtf","application/rtf"],[".epub","application/epub+zip"],[".zip","application/zip"],[".tar","application/x-tar"],[".gz","application/gzip"],[".gzip","application/gzip"],[".bz2","application/x-bzip2"],[".xz","application/x-xz"],[".rar","application/vnd.rar"],[".7z","application/x-7z-compressed"],[".wasm","application/wasm"],[".map","application/json"],[".webmanifest","application/manifest+json"],[".ics","text/calendar"],[".vcf","text/vcard"],[".sql","application/sql"],[".sh","application/x-sh"],[".bat","application/x-msdos-program"],[".exe","application/x-msdownload"],[".dll","application/x-msdownload"],[".bin","application/octet-stream"],[".iso","application/x-iso9660-image"],[".dmg","application/x-apple-diskimage"],[".apk","application/vnd.android.package-archive"],[".jar","application/java-archive"],[".swf","application/x-shockwave-flash"]]);var gt=(s,e)=>{let{source:t,path:r}=s,o=r;return o.startsWith("/")||(o="/"+o),o!=="/"&&o.endsWith("/")&&(o=o.slice(0,-1)),w.addOrUpdate("GET",`${o}/*`,[],async(n,i)=>fr(n,i,t),{service:"StaticFiles",...e}),async(n,i,p)=>p()};async function fr(s,e,t){if(s.method!=="GET"&&s.method!=="HEAD")return e.status(405).json({...R(new he(s.url,s.method))});let r=s.params["*"]||"",o=y.join(t,r),n=y.resolve($.getCwd(),o),i=y.resolve($.getCwd(),t);if(!n.startsWith(i))return e.notFound({...R(new M(s.url,s.method))});try{if(!(await S.stat(n)).isFile)return e.notFound({...R(new M(s.url,s.method))})}catch(a){if(a.code==="ENOENT")return e.notFound({...R(new M(s.url,s.method))});throw a}let p=Xe(y.extName(n));e.setHeader("Content-Type",p);let d=Ce.file(n);e.raw(d);}function Xe(s){return ht.get(s)||"application/octet-stream"}var B=class{responseStatus;headers;body;constructor(e=200){this.responseStatus=e,this.headers={};}setHeader(e,t){return this.headers[e]=t,this}status(e){return this.responseStatus=e,this}send(e){if(e==null)return this.text("");if(typeof e=="string")return this.text(e);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return this.raw(e);if(typeof Buffer<"u"&&e instanceof Buffer)return this.download(new Uint8Array(e));if(e instanceof ArrayBuffer||e instanceof Uint8Array)return this.download(new Uint8Array(e));if(typeof e=="object"&&e!==null)try{return this.json(e)}catch{return this.text(String(e))}if(typeof e=="symbol")return this.text(e.toString());this.body=e;}raw(e){this.body=e;}text(e){this.body=e,this.headers={...this.headers,"Content-Type":"text/plain"};}json(e){this.body=e,this.headers={...this.headers,"Content-Type":"application/json"};}html(e){this.body=e,this.headers={...this.headers,"Content-Type":"text/html"};}xml(e){this.body=e,this.headers={...this.headers,"Content-Type":"application/xml"};}download(e){this.body=e,this.headers={...this.headers,"Content-Type":"application/octet-stream"};}file(e,t){let r=y.extName(e),o=Xe(r);this.body=Ce.file(e,t),this.headers={...this.headers,"Content-Type":o};}ok(e){this.status(200).send(e);}created(e){this.status(201).send(e);}accepted(e){this.status(202).send(e);}noContent(){this.status(204).send("");}partialContent(e){this.status(206).send(e);}multipleChoices(e){this.status(300).setHeader("Location",e);}redirect(e){this.status(302).setHeader("Location",e);}movedPermanently(e){this.status(301).setHeader("Location",e);}found(e){this.status(302).setHeader("Location",e);}seeOther(e){this.status(303).setHeader("Location",e);}notModified(){this.status(304).send("");}temporaryRedirect(e){this.status(307).setHeader("Location",e);}permanentRedirect(e){this.status(308).setHeader("Location",e);}badRequest(e){this.status(400).send(e);}unauthorized(e){this.status(401).send(e);}forbidden(e){this.status(403).send(e);}notFound(e){this.status(404).send(e);}methodNotAllowed(e){this.status(405).send(e);}notAcceptable(e){this.status(406).send(e);}conflict(e){this.status(409).send(e);}gone(e){this.status(410).send(e);}payloadTooLarge(e){this.status(413).send(e);}unsupportedMediaType(e){this.status(415).send(e);}unprocessableEntity(e){this.status(422).send(e);}tooManyRequests(e){this.status(429).send(e);}internalServerError(e){this.status(500).send(e);}notImplemented(e){this.status(501).send(e);}badGateway(e){this.status(502).send(e);}serviceUnavailable(e){this.status(503).send(e);}gatewayTimeout(e){this.status(504).send(e);}httpVersionNotSupported(e){this.status(505).send(e);}stream(e,t){if(this.headers={...this.headers,"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive",...t?.customHeaders},e instanceof ReadableStream){this.body=e;return}this.body=new ReadableStream({async start(r){for await(let o of e)r.enqueue(new TextEncoder().encode(o));r.close();}});}getBody(){return this.body}};var ge=class{constructor(e){this.response=e;}body(){return this.response.getBody()}statusCode(){return this.response.responseStatus}headers(){return this.response.headers}assertStatus(e){if(this.response.responseStatus!==e)throw new Error(`Expected status ${e}, but got ${this.response.responseStatus}`);return this}assertHeader(e,t){if(this.response.headers[e]!==t)throw new Error(`Expected header ${e} to be ${t}, but got ${this.response.headers[e]}`);return this}assertHeaderExists(e){if(!(e in this.response.headers))throw new Error(`Expected header ${e} to exist, but it was not found`);return this}assertHeaderNotExists(e){if(e in this.response.headers)throw new Error(`Expected header ${e} to not exist, but it was found with value: ${this.response.headers[e]}`);return this}assertBodySubset(e){return this.assertSubset(this.body(),e,"body"),this}assertBodyDeepEqual(e){return this.assertDeepEqual(this.body(),e,"body"),this}assertBodyNotSubset(e){return this.assertNotSubset(this.body(),e,"body"),this}assertBodyNotDeepEqual(e){return this.assertNotDeepEqual(this.body(),e,"body"),this}assertCustom(e){return e(this.response),this}assertSubset(e,t,r){for(let o in t){let n=r===""?o:`${r}.${o}`,i=e[o],p=t[o];if(!(o in e))throw new Error(`Expected ${r} to have key ${o}, but it was not found`);if(this.isObject(p)&&this.isObject(i))this.assertSubset(i,p,n);else if(Array.isArray(p)&&Array.isArray(i))this.assertArraySubset(i,p,n);else if(i!==p)throw new Error(`Expected ${n} to be ${p}, but got ${i}`)}}assertDeepEqual(e,t,r){if(this.isObject(e)&&this.isObject(t)){let o=Object.keys(e),n=Object.keys(t);if(o.length!==n.length)throw new Error(`Expected ${r} to have ${n.length} keys, but got ${o.length}`);for(let i of n){let p=r==="body"?i:`${r}.${i}`;this.assertDeepEqual(e[i],t[i],p);}}else if(Array.isArray(e)&&Array.isArray(t))this.assertArrayDeepEqual(e,t,r);else if(e!==t)throw new Error(`Expected ${r} to be ${t}, but got ${e}`)}assertNotSubset(e,t,r){try{throw this.assertSubset(e,t,r),new Error(`Expected ${r} to NOT contain the subset, but it does`)}catch(o){if(o instanceof Error&&o.message.includes("Expected"))return;throw o}}assertNotDeepEqual(e,t,r){try{throw this.assertDeepEqual(e,t,r),new Error(`Expected ${r} to NOT be deeply equal, but it is`)}catch(o){if(o instanceof Error&&o.message.includes("Expected"))return;throw o}}assertArraySubset(e,t,r){if(t.length>e.length)throw new Error(`Expected ${r} to have at least ${t.length} elements, but got ${e.length}`);for(let o=0;o<t.length;o++){let n=`${r}[${o}]`,i=e[o],p=t[o];if(this.isObject(p)&&this.isObject(i))this.assertSubset(i,p,n);else if(Array.isArray(p)&&Array.isArray(i))this.assertArraySubset(i,p,n);else if(i!==p)throw new Error(`Expected ${n} to be ${p}, but got ${i}`)}}assertArrayDeepEqual(e,t,r){if(e.length!==t.length)throw new Error(`Expected ${r} to have ${t.length} elements, but got ${e.length}`);for(let o=0;o<t.length;o++){let n=`${r}[${o}]`;this.assertDeepEqual(e[o],t[o],n);}}isObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}};var G=async(s,e,t,r=new B)=>{let o=0;if(!s.length)return await e(t,r),r;let n=async()=>{if(o++,o>=s.length){await e(t,r);return}let p=s[o];await p(t,r,n);},i=s[0];return await i(t,r,n),r},K=s=>s?["post","put","patch","delete"].includes(s.toLowerCase()):true;var Ee=class{server;constructor(e){this.server=e;}async request(e,t,r={}){let{headers:o={},query:n={},cookies:i={},ip:p}=r;this.validateOptions(r);let d=w.find(e.toUpperCase(),t);if(!d){let l=new B(404);return l.json({caller:"MockServer",error:"Route not found",path:t,method:e}),new ge(l)}let a=r.body,c="application/json";if(a&&typeof a=="object"&&!(a instanceof Uint8Array)&&!(a instanceof ArrayBuffer)&&(a=JSON.stringify(a)),r.formData){let l=`----WebKitFormBoundary${Math.random().toString(36).substring(2)}`;c=`multipart/form-data; boundary=${l}`,a=await this.formDataToMultipart(r.formData,l);}r.urlencoded&&(c="application/x-www-form-urlencoded",a=new URLSearchParams(r.urlencoded).toString());let u=new URL(`http://${this.server.host}:${this.server.port}${t}`);u.search=new URLSearchParams(n).toString();let f=new _(u.toString(),{method:e.toUpperCase(),body:K(e)?a:void 0,headers:{"content-type":c,...o}});f.query={...Object.fromEntries(u.searchParams.entries()),...n},f.params=d.params,f.cookies=i,f.ip=p;try{let l=await G(d.middleware,d.handler,f);return new ge(l)}catch(l){exports.logger.error({error:l},`Error processing mock request ${e} ${t}:`);let m=new B(500);return m.json({error:"Internal server error",message:l instanceof Error?l.message:String(l)}),new ge(m)}}async get(e,t){return this.request("GET",e,t)}async post(e,t){return this.request("POST",e,t)}async put(e,t){return this.request("PUT",e,t)}async patch(e,t){return this.request("PATCH",e,t)}async delete(e,t){return this.request("DELETE",e,t)}async formDataToMultipart(e,t){let r=new TextEncoder,o=[];for(let[d,a]of e.entries()){o.push(r.encode(`--${t}\r
75
+ }`}};R([Q({description:"The name of the queue to generate",required:true})],z,"queueName"),R([T({description:"The path to the queue to generate, default is src/queues",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/queues"})],z,"path"),R([T({description:"The provider of the queue to generate, default is bullmq",type:"string",aliases:["pr"],name:"provider",required:false,defaultValue:"bullmq"})],z,"provider");var A=class extends E{static commandName="build";static description="Build the project for production, node.js only";static help=["Build the project for production, node.js only","It will create a production build of the project in the dist directory","Must have a tsconfig.json file in the root of the project","Must have esbuild installed as a dependency while running the command","Must have esbuild-plugin-copy installed as a dependency while running the command if you want to copy assets to the output directory","Example: npx balda build -t ./tsconfig.json -a ./assets"];static clearDist;static entry;static output;static tsconfig;static assets;static format;static packages;static sourcemap;static async handle(){typeof process===void 0&&(this.logger.error("Build command is only supported in node.js"),process.exit(1)),["esm","cjs"].includes(this.format)||(this.logger.error("Invalid format, must be 'esm' or 'cjs'"),process.exit(1)),["bundle","external"].includes(this.packages)||(this.logger.error("Invalid packages, must be 'bundle' or 'external'"),process.exit(1));let e=await import('esbuild').catch(i=>{throw this.logger.error("esbuild is not installed, please install it with `npm install -D esbuild` to use the build command"),new Error("esbuild is not installed")}),t=ze__default.default.join(this.output,"assets"),r=[];if(this.assets){let{copy:i}=await import('esbuild-plugin-copy').catch(p=>{throw this.logger.error("esbuild-plugin-copy is not installed, please install it with `npm install -D esbuild-plugin-copy` to use the build command"),new Error("esbuild-plugin-copy is not installed")});Ce__default.default.existsSync(t)||Ce__default.default.mkdirSync(t,{recursive:true}),r.push(i({assets:{from:this.assets,to:t}}));}this.clearDist&&Ce__default.default.existsSync(this.output)&&(this.logger.info("Clearing dist directory..."),Ce__default.default.rmSync(this.output,{recursive:true})),this.logger.info("Building project...");let o=ze__default.default.join(this.output,"server.js"),n=await e.build({tsconfig:this.tsconfig,entryPoints:[this.entry],bundle:true,platform:"node",outfile:o,minify:true,sourcemap:this.sourcemap,plugins:r,format:this.format,packages:this.packages});n.errors.length&&(this.logger.error(JSON.stringify({message:"Failed to build the project",errors:n.errors},null,2)),process.exit(1)),n.warnings.length&&this.logger.warn(JSON.stringify({message:"Failed to build the project",warnings:n.warnings},null,2)),this.logger.info(JSON.stringify({message:`Project built successfully in ${o}`,output:o,assets:!!this.assets},null,2)),process.exit(0);}};R([T({type:"boolean",aliases:["c"],name:"clear-dist",required:false,defaultValue:false,description:"Whether to clear the dist directory before building the project"})],A,"clearDist"),R([T({type:"string",aliases:["e"],name:"entry",required:false,defaultValue:"./src/index.ts",description:"The entry point of the project, default is ./src/index.ts"})],A,"entry"),R([T({type:"string",aliases:["o"],name:"output",required:false,defaultValue:"./dist",description:"The path to the output directory, default is ./dist"})],A,"output"),R([T({type:"string",aliases:["t"],name:"tsconfig",required:false,defaultValue:"./tsconfig.json",description:"The path to the tsconfig.json file, default is ./tsconfig.json"})],A,"tsconfig"),R([T({type:"string",aliases:["a"],name:"assets",required:false,description:"The path to the assets directory that will be loaded in the production build"})],A,"assets"),R([T({type:"string",aliases:["f"],name:"format",required:false,defaultValue:"esm",description:"The format to build the project, default is esm, can be 'esm' or 'cjs'"})],A,"format"),R([T({type:"string",aliases:["p"],name:"packages",required:false,defaultValue:"external",description:"Weather to bundle node_modules or not, default is external, can be 'bundle' or 'external'"})],A,"packages"),R([T({type:"boolean",aliases:["s"],name:"sourcemap",required:false,defaultValue:true,description:"Whether to generate sourcemaps or not, default is true"})],A,"sourcemap");var Xe=class s{commands;static commandsPattern="src/commands/**/*.{ts,js}";static logger=exports.logger;constructor(){this.commands=new Map;}static getInstance(){return new s}static setCommandsPattern(e){this.commandsPattern=e;}getCommand(e){return this.commands.get(e)??null}getCommands(){return Array.from(this.commands.values())}async loadCommands(e){s.logger.info(`Loading commands from ${e}`);let t=await glob.glob(e,{absolute:true,cwd:q.getCwd()});if(t.some(o=>o.endsWith(".ts")))try{let{register:o}=await import('module');o("ts-node/esm",(typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));}catch{s.logger.error("Failed to register ts-node/esm, you need to install it in your project in order to use typescript in the cli\ntry running: `npm install -D ts-node`"),process.exit(1);}for(let o of t){let n=await import(o).then(i=>i.default?i.default:i).catch(i=>(s.logger.error(`Error loading command ${o}: ${i}`),null));n&&this.commands.set(n.commandName,n);}let r=[ne,me,ie,z,ae,Se,A];for(let o of r)this.commands.set(o.commandName,o);}},ft=Xe.getInstance();var Ee=class extends Request{};var F=class s extends Ee{static fromRequest(e){return new s(e.url,{method:e.method,body:e.body,headers:e.headers})}static enrichRequest(e){return e.validate=(t,r=false)=>(typeof t=="function"&&(t=t(zod.z)),D(t,e.body||{},r)),e.validateQuery=(t,r=false)=>(typeof t=="function"&&(t=t(zod.z)),D(t,e.query||{},r)),e.validateAll=(t,r=false)=>(typeof t=="function"&&(t=t(zod.z)),D(t,{...e.body?{body:e.body}:{},...e.query?{query:e.query}:{}},r)),e.file=t=>e.files.find(r=>r.formName===t)??null,e.files=[],e.saveSession=async()=>{},e.destroySession=async()=>{},e.session={},e.cookies={},e.cookie=t=>e.cookies[t],e}file=e=>this.files.find(t=>t.formName===e)??null;cookies={};cookie=e=>this.cookies[e];timeout;session=void 0;saveSession=async()=>{};destroySession=async()=>{};ip;files=[];params={};query={};get id(){return this._id||(this._id=I.randomUUID()),this._id}body;validate(e,t=false){return typeof e=="function"&&(e=e(zod.z)),D(e,this.body||{},t)}validateQuery(e,t=false){return typeof e=="function"&&(e=e(zod.z)),D(e,this.query||{},t)}validateAll(e,t=false){return typeof e=="function"&&(e=e(zod.z)),D(e,{...this.body?{body:this.body}:{},...this.query?{query:this.query}:{}},t)}};var fe=class{get(e){switch(g.type){case "node":case "bun":case "deno":return process.env[e]??"";default:throw new Error(`Unsupported runtime: ${g.type}`)}}getEnvironment(){switch(g.type){case "node":case "deno":case "bun":return Object.fromEntries(Object.entries(process.env).filter(([e,t])=>t!==void 0))}}};var hr=new fe,x=s=>{let e=hr.get("NODE_ENV")!=="production";return {code:s.name||"INTERNAL_ERROR",message:s.message,...e&&{stack:s.stack,cause:s.cause}}};var ge=class extends O{constructor(e,t){super(`METHOD_NOT_ALLOWED: Cannot ${t} ${e}`);}};var M=class extends O{constructor(e,t){super(`ROUTE_NOT_FOUND: Cannot ${t} ${e}`);}};var et=class{file(e,t){switch(g.type){case "bun":case "node":return Ce__default.default.readFileSync(e,t);case "deno":return Deno.readFileSync(e);default:throw new Error("Unsupported runtime")}}},Me=new et;var yt=new Map([[".html","text/html"],[".htm","text/html"],[".css","text/css"],[".js","application/javascript"],[".mjs","application/javascript"],[".cjs","application/javascript"],[".ts","application/typescript"],[".jsx","text/jsx"],[".tsx","text/tsx"],[".json","application/json"],[".xml","application/xml"],[".yaml","application/yaml"],[".yml","application/yaml"],[".csv","text/csv"],[".txt","text/plain"],[".md","text/markdown"],[".markdown","text/markdown"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".gif","image/gif"],[".svg","image/svg+xml"],[".ico","image/x-icon"],[".webp","image/webp"],[".avif","image/avif"],[".bmp","image/bmp"],[".tiff","image/tiff"],[".tif","image/tiff"],[".heic","image/heic"],[".heif","image/heif"],[".mp4","video/mp4"],[".webm","video/webm"],[".avi","video/x-msvideo"],[".mov","video/quicktime"],[".mkv","video/x-matroska"],[".wmv","video/x-ms-wmv"],[".flv","video/x-flv"],[".m4v","video/x-m4v"],[".mpeg","video/mpeg"],[".mpg","video/mpeg"],[".3gp","video/3gpp"],[".mp3","audio/mpeg"],[".wav","audio/wav"],[".ogg","audio/ogg"],[".flac","audio/flac"],[".aac","audio/aac"],[".m4a","audio/mp4"],[".wma","audio/x-ms-wma"],[".opus","audio/opus"],[".mid","audio/midi"],[".midi","audio/midi"],[".woff","font/woff"],[".woff2","font/woff2"],[".ttf","font/ttf"],[".otf","font/otf"],[".eot","application/vnd.ms-fontobject"],[".pdf","application/pdf"],[".doc","application/msword"],[".docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"],[".xls","application/vnd.ms-excel"],[".xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],[".ppt","application/vnd.ms-powerpoint"],[".pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation"],[".odt","application/vnd.oasis.opendocument.text"],[".ods","application/vnd.oasis.opendocument.spreadsheet"],[".odp","application/vnd.oasis.opendocument.presentation"],[".rtf","application/rtf"],[".epub","application/epub+zip"],[".zip","application/zip"],[".tar","application/x-tar"],[".gz","application/gzip"],[".gzip","application/gzip"],[".bz2","application/x-bzip2"],[".xz","application/x-xz"],[".rar","application/vnd.rar"],[".7z","application/x-7z-compressed"],[".wasm","application/wasm"],[".map","application/json"],[".webmanifest","application/manifest+json"],[".ics","text/calendar"],[".vcf","text/vcard"],[".sql","application/sql"],[".sh","application/x-sh"],[".bat","application/x-msdos-program"],[".exe","application/x-msdownload"],[".dll","application/x-msdownload"],[".bin","application/octet-stream"],[".iso","application/x-iso9660-image"],[".dmg","application/x-apple-diskimage"],[".apk","application/vnd.android.package-archive"],[".jar","application/java-archive"],[".swf","application/x-shockwave-flash"]]);var vt=(s,e)=>{let{source:t,path:r}=s,o=r;return o.startsWith("/")||(o="/"+o),o!=="/"&&o.endsWith("/")&&(o=o.slice(0,-1)),w.addOrUpdate("GET",`${o}/*`,[],async(n,i)=>gr(n,i,t),{service:"StaticFiles",...e}),async(n,i,p)=>p()};async function gr(s,e,t){if(s.method!=="GET"&&s.method!=="HEAD")return e.status(405).json({...x(new ge(s.url,s.method))});let r=s.params["*"]||"",o=y.join(t,r),n=y.resolve(q.getCwd(),o),i=y.resolve(q.getCwd(),t);if(!n.startsWith(i))return e.notFound({...x(new M(s.url,s.method))});try{if(!(await S.stat(n)).isFile)return e.notFound({...x(new M(s.url,s.method))})}catch(a){if(a.code==="ENOENT")return e.notFound({...x(new M(s.url,s.method))});throw a}let p=tt(y.extName(n));e.setHeader("Content-Type",p);let d=Me.file(n);e.raw(d);}function tt(s){return yt.get(s)||"application/octet-stream"}var B=class{responseStatus;headers;body;constructor(e=200){this.responseStatus=e,this.headers={};}setHeader(e,t){return this.headers[e]=t,this}status(e){return this.responseStatus=e,this}send(e){if(e==null)return this.text("");if(typeof e=="string")return this.text(e);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return this.raw(e);if(typeof Buffer<"u"&&e instanceof Buffer)return this.download(new Uint8Array(e));if(e instanceof ArrayBuffer||e instanceof Uint8Array)return this.download(new Uint8Array(e));if(typeof e=="object"&&e!==null)try{return this.json(e)}catch{return this.text(String(e))}if(typeof e=="symbol")return this.text(e.toString());this.body=e;}raw(e){this.body=e;}text(e){this.body=e,this.headers={...this.headers,"Content-Type":"text/plain"};}json(e){this.body=e,this.headers={...this.headers,"Content-Type":"application/json"};}html(e){this.body=e,this.headers={...this.headers,"Content-Type":"text/html"};}xml(e){this.body=e,this.headers={...this.headers,"Content-Type":"application/xml"};}download(e){this.body=e,this.headers={...this.headers,"Content-Type":"application/octet-stream"};}file(e,t){let r=y.extName(e),o=tt(r);this.body=Me.file(e,t),this.headers={...this.headers,"Content-Type":o};}ok(e){this.status(200).send(e);}created(e){this.status(201).send(e);}accepted(e){this.status(202).send(e);}noContent(){this.status(204).send("");}partialContent(e){this.status(206).send(e);}multipleChoices(e){this.status(300).setHeader("Location",e);}redirect(e){this.status(302).setHeader("Location",e);}movedPermanently(e){this.status(301).setHeader("Location",e);}found(e){this.status(302).setHeader("Location",e);}seeOther(e){this.status(303).setHeader("Location",e);}notModified(){this.status(304).send("");}temporaryRedirect(e){this.status(307).setHeader("Location",e);}permanentRedirect(e){this.status(308).setHeader("Location",e);}badRequest(e){this.status(400).send(e);}unauthorized(e){this.status(401).send(e);}forbidden(e){this.status(403).send(e);}notFound(e){this.status(404).send(e);}methodNotAllowed(e){this.status(405).send(e);}notAcceptable(e){this.status(406).send(e);}conflict(e){this.status(409).send(e);}gone(e){this.status(410).send(e);}payloadTooLarge(e){this.status(413).send(e);}unsupportedMediaType(e){this.status(415).send(e);}unprocessableEntity(e){this.status(422).send(e);}tooManyRequests(e){this.status(429).send(e);}internalServerError(e){this.status(500).send(e);}notImplemented(e){this.status(501).send(e);}badGateway(e){this.status(502).send(e);}serviceUnavailable(e){this.status(503).send(e);}gatewayTimeout(e){this.status(504).send(e);}httpVersionNotSupported(e){this.status(505).send(e);}stream(e,t){if(this.headers={...this.headers,"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive",...t?.customHeaders},e instanceof ReadableStream){this.body=e;return}this.body=new ReadableStream({async start(r){for await(let o of e)r.enqueue(new TextEncoder().encode(o));r.close();}});}getBody(){return this.body}};var _=class{schemaOptions;yogaOptions;isEnabled;constructor(e){let t=this.initializeConfiguration(e);this.schemaOptions=t.schemaOptions,this.yogaOptions=t.yogaOptions,this.isEnabled=t.isEnabled;}getSchema(e){return e(this.schemaOptions)}getYogaOptions(){return this.yogaOptions}addTypeDef(e){if(typeof e=="function"){this.addTypeDef(e());return}if(Array.isArray(e)){this.addTypeDefArray(e);return}this.ensureTypeDefsArray(),this.schemaOptions.typeDefs.push(e);}addResolver(e,t){if(typeof e=="string"&&t){this.addResolverByType(e,t);return}this.addFullResolver(e);}initializeConfiguration(e){return e?this.createEnabledConfiguration(e):this.createDisabledConfiguration()}createDisabledConfiguration(){return {schemaOptions:{typeDefs:"",resolvers:{}},yogaOptions:{},isEnabled:false}}createEnabledConfiguration(e){return {schemaOptions:this.resolveSchemaOptions(e.schema),yogaOptions:this.resolveYogaOptions(e.yogaOptions),isEnabled:true}}resolveSchemaOptions(e){return e!==void 0?e:{typeDefs:"",resolvers:{}}}resolveYogaOptions(e){return e!==void 0?e:{}}addResolverByType(e,t){if(this.ensureResolversInitialized(),Array.isArray(this.schemaOptions.resolvers)){this.schemaOptions.resolvers.push({[e]:t});return}this.mergeResolverIntoObject(e,t);}ensureResolversInitialized(){!this.schemaOptions.resolvers&&(this.schemaOptions.resolvers={});}mergeResolverIntoObject(e,t){let r=this.schemaOptions.resolvers,o=r[e];if(o&&typeof o=="object"){r[e]={...o,...t};return}r[e]=t;}addFullResolver(e){if(this.ensureResolversInitialized(),Array.isArray(e)){this.addResolverArray(e);return}if(typeof e=="object"&&e!==null){this.addResolverObject(e);return}this.schemaOptions.resolvers=e;}addResolverArray(e){if(Array.isArray(this.schemaOptions.resolvers)){this.schemaOptions.resolvers=[...this.schemaOptions.resolvers,...e];return}this.schemaOptions.resolvers=[this.schemaOptions.resolvers,...e];}addResolverObject(e){if(Array.isArray(this.schemaOptions.resolvers)){this.schemaOptions.resolvers=[...this.schemaOptions.resolvers,e];return}this.schemaOptions.resolvers={...this.schemaOptions.resolvers,...e};}addTypeDefArray(e){for(let t of e)this.addTypeDef(t);}ensureTypeDefsArray(){if(Array.isArray(this.schemaOptions.typeDefs))return;if(this.schemaOptions.typeDefs!==void 0){this.schemaOptions.typeDefs=[this.schemaOptions.typeDefs];return}this.schemaOptions.typeDefs=[];}};var ye=class{constructor(e){this.response=e;}body(){return this.response.getBody()}statusCode(){return this.response.responseStatus}headers(){return this.response.headers}assertStatus(e){if(this.response.responseStatus!==e)throw new Error(`Expected status ${e}, but got ${this.response.responseStatus}`);return this}assertHeader(e,t){if(this.response.headers[e]!==t)throw new Error(`Expected header ${e} to be ${t}, but got ${this.response.headers[e]}`);return this}assertHeaderExists(e){if(!(e in this.response.headers))throw new Error(`Expected header ${e} to exist, but it was not found`);return this}assertHeaderNotExists(e){if(e in this.response.headers)throw new Error(`Expected header ${e} to not exist, but it was found with value: ${this.response.headers[e]}`);return this}assertBodySubset(e){return this.assertSubset(this.body(),e,"body"),this}assertBodyDeepEqual(e){return this.assertDeepEqual(this.body(),e,"body"),this}assertBodyNotSubset(e){return this.assertNotSubset(this.body(),e,"body"),this}assertBodyNotDeepEqual(e){return this.assertNotDeepEqual(this.body(),e,"body"),this}assertCustom(e){return e(this.response),this}assertSubset(e,t,r){for(let o in t){let n=r===""?o:`${r}.${o}`,i=e[o],p=t[o];if(!(o in e))throw new Error(`Expected ${r} to have key ${o}, but it was not found`);if(this.isObject(p)&&this.isObject(i))this.assertSubset(i,p,n);else if(Array.isArray(p)&&Array.isArray(i))this.assertArraySubset(i,p,n);else if(i!==p)throw new Error(`Expected ${n} to be ${p}, but got ${i}`)}}assertDeepEqual(e,t,r){if(this.isObject(e)&&this.isObject(t)){let o=Object.keys(e),n=Object.keys(t);if(o.length!==n.length)throw new Error(`Expected ${r} to have ${n.length} keys, but got ${o.length}`);for(let i of n){let p=r==="body"?i:`${r}.${i}`;this.assertDeepEqual(e[i],t[i],p);}}else if(Array.isArray(e)&&Array.isArray(t))this.assertArrayDeepEqual(e,t,r);else if(e!==t)throw new Error(`Expected ${r} to be ${t}, but got ${e}`)}assertNotSubset(e,t,r){try{throw this.assertSubset(e,t,r),new Error(`Expected ${r} to NOT contain the subset, but it does`)}catch(o){if(o instanceof Error&&o.message.includes("Expected"))return;throw o}}assertNotDeepEqual(e,t,r){try{throw this.assertDeepEqual(e,t,r),new Error(`Expected ${r} to NOT be deeply equal, but it is`)}catch(o){if(o instanceof Error&&o.message.includes("Expected"))return;throw o}}assertArraySubset(e,t,r){if(t.length>e.length)throw new Error(`Expected ${r} to have at least ${t.length} elements, but got ${e.length}`);for(let o=0;o<t.length;o++){let n=`${r}[${o}]`,i=e[o],p=t[o];if(this.isObject(p)&&this.isObject(i))this.assertSubset(i,p,n);else if(Array.isArray(p)&&Array.isArray(i))this.assertArraySubset(i,p,n);else if(i!==p)throw new Error(`Expected ${n} to be ${p}, but got ${i}`)}}assertArrayDeepEqual(e,t,r){if(e.length!==t.length)throw new Error(`Expected ${r} to have ${t.length} elements, but got ${e.length}`);for(let o=0;o<t.length;o++){let n=`${r}[${o}]`;this.assertDeepEqual(e[o],t[o],n);}}isObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}};var K=async(s,e,t,r=new B)=>{let o=0;if(!s.length)return await e(t,r),r;let n=async()=>{if(o++,o>=s.length){await e(t,r);return}let p=s[o];await p(t,r,n);},i=s[0];return await i(t,r,n),r},V=s=>s?["post","put","patch","delete"].includes(s.toLowerCase()):true,ve=s=>{let e=null,t=false,r=async()=>{for(;t;)await new Promise(n=>setTimeout(n,10));},o=async()=>{try{let{createYoga:n,createSchema:i}=await import('graphql-yoga'),p=s.getSchema(i),d=s.getYogaOptions();return n({graphqlEndpoint:"/graphql",...d,schema:p})}catch(n){throw n instanceof Error&&(n.message.includes("Cannot find module")||n.message.includes("Cannot find package"))?new Error("GraphQL is enabled but 'graphql-yoga' is not installed. Install it with: npm install graphql graphql-yoga"):n}};return async()=>{if(!s.isEnabled)return null;if(e!==null)return e;if(t)return await r(),e;t=true;try{return e=o(),await e}catch(d){throw e=null,d}finally{t=false;}}};var Ae=class{server;constructor(e){this.server=e;}async request(e,t,r={}){let{headers:o={},query:n={},cookies:i={},ip:p}=r;this.validateOptions(r);let d=w.find(e.toUpperCase(),t);if(!d){let l=new B(404);return l.json({caller:"MockServer",error:"Route not found",path:t,method:e}),new ye(l)}let a=r.body,c="application/json";if(a&&typeof a=="object"&&!(a instanceof Uint8Array)&&!(a instanceof ArrayBuffer)&&(a=JSON.stringify(a)),r.formData){let l=`----WebKitFormBoundary${Math.random().toString(36).substring(2)}`;c=`multipart/form-data; boundary=${l}`,a=await this.formDataToMultipart(r.formData,l);}r.urlencoded&&(c="application/x-www-form-urlencoded",a=new URLSearchParams(r.urlencoded).toString());let u=new URL(`http://${this.server.host}:${this.server.port}${t}`);u.search=new URLSearchParams(n).toString();let h=new F(u.toString(),{method:e.toUpperCase(),body:V(e)?a:void 0,headers:{"content-type":c,...o}});h.query={...Object.fromEntries(u.searchParams.entries()),...n},h.params=d.params,h.cookies=i,h.ip=p;try{let l=await K(d.middleware,d.handler,h);return new ye(l)}catch(l){exports.logger.error({error:l},`Error processing mock request ${e} ${t}:`);let m=new B(500);return m.json({error:"Internal server error",message:l instanceof Error?l.message:String(l)}),new ye(m)}}async get(e,t){return this.request("GET",e,t)}async post(e,t){return this.request("POST",e,t)}async put(e,t){return this.request("PUT",e,t)}async patch(e,t){return this.request("PATCH",e,t)}async delete(e,t){return this.request("DELETE",e,t)}async formDataToMultipart(e,t){let r=new TextEncoder,o=[];for(let[d,a]of e.entries()){o.push(r.encode(`--${t}\r
76
76
  `));let c=`Content-Disposition: form-data; name="${d}"`,u="";if(a instanceof File&&(c+=`; filename="${a.name}"`,u=`Content-Type: ${a.type||"application/octet-stream"}\r
77
77
  `),o.push(r.encode(`${c}\r
78
78
  ${u}\r
79
- `)),a instanceof File){let f=await a.arrayBuffer();o.push(new Uint8Array(f)),o.push(r.encode(`\r
79
+ `)),a instanceof File){let h=await a.arrayBuffer();o.push(new Uint8Array(h)),o.push(r.encode(`\r
80
80
  `));}else o.push(r.encode(`${String(a)}\r
81
81
  `));}o.push(r.encode(`--${t}--\r
82
- `));let n=o.reduce((d,a)=>d+a.byteLength,0),i=new Uint8Array(n),p=0;for(let d of o)i.set(d,p),p+=d.byteLength;return i}validateOptions(e){let{body:t,formData:r,urlencoded:o}=e;if(t&&(r||o))throw new Error("Only one of body, formData, urlencoded can be provided");if(r&&(o||t))throw new Error("Only one of formData, urlencoded can be provided");if(o&&(t||r))throw new Error("Only one of urlencoded, body can be provided")}};var yt=s=>{let e={secret:s?.secret??"",defaults:{path:"/",httpOnly:true,secure:true,sameSite:"Lax",...s?.defaults},parse:s?.parse??true,sign:s?.sign??false};return async(t,r,o)=>{if(e.parse){let n=hr(t.headers.get("cookie")||"");t.cookies={};for(let[i,p]of Object.entries(n)){if(e.sign&&e.secret){let d=await vr(p,e.secret);d!==false&&(t.cookies[i]=d);continue}t.cookies[i]=p;}}r.cookie=(n,i,p)=>{vt(r,n,i,{...e.defaults,...p},e);},r.clearCookie=(n,i)=>{gr(r,n,{...e.defaults,...i});},await o();}};function hr(s){let e={};if(!s)return e;let t=s.split(";");for(let r of t){let[o,n]=r.trim().split("=");o&&n&&(e[decodeURIComponent(o)]=decodeURIComponent(n));}return e}async function vt(s,e,t,r,o){let n=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;r.domain&&(n+=`; Domain=${r.domain}`),r.path&&(n+=`; Path=${r.path}`),r.expires&&(n+=`; Expires=${r.expires.toUTCString()}`),r.maxAge&&(n+=`; Max-Age=${r.maxAge}`),r.secure&&(n+="; Secure"),r.httpOnly&&(n+="; HttpOnly"),r.sameSite&&(n+=`; SameSite=${r.sameSite}`),r.priority&&(n+=`; Priority=${r.priority}`),o.sign&&o.secret&&(n=await yr(n,o.secret));let i=s.headers["set-cookie"]||"",p=i?`${i}, ${n}`:n;s.setHeader("Set-Cookie",p);}function gr(s,e,t){let r={...t,expires:new Date(0),maxAge:0};vt(s,e,"",r,{secret:"",sign:false});}async function yr(s,e){let t=new TextEncoder,r=t.encode(e),o=t.encode(s),n=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},false,["sign"]),i=await crypto.subtle.sign("HMAC",n,o),p=new Uint8Array(i),d=Array.from(p).map(a=>a.toString(16).padStart(2,"0")).join("");return `${s}.${d}`}async function vr(s,e){let t=s.split(".");if(t.length!==2)return false;let[r,o]=t,n=new TextEncoder,i=n.encode(e),p=n.encode(r),d=await crypto.subtle.importKey("raw",i,{name:"HMAC",hash:"SHA-256"},false,["sign"]),a=await crypto.subtle.sign("HMAC",d,p),c=new Uint8Array(a),u=Array.from(c).map(f=>f.toString(16).padStart(2,"0")).join("");return o===u?r:false}function wt(s,e=""){let t=new URL(s.url),r=Object.fromEntries(s.headers.entries());return {body:s.body,query:s.query,params:s.params,cookies:s.cookies,session:s.session,originalUrl:t.pathname+t.search,baseUrl:e,path:t.pathname.replace(e,"")||"/",method:s.method,ip:s.ip,headers:r,url:t.pathname,get(n){return s.headers.get(n.toLowerCase())??void 0},header(n){return s.headers.get(n.toLowerCase())??void 0},app:{},res:null,route:null,protocol:t.protocol.replace(":",""),secure:t.protocol==="https:",hostname:t.hostname,host:t.host,fresh:false,stale:true,xhr:r["x-requested-with"]?.toLowerCase()==="xmlhttprequest",accepts:()=>{},acceptsCharsets:()=>{},acceptsEncodings:()=>{},acceptsLanguages:()=>{},is:()=>null,range:()=>{},param:n=>s.params[n]??s.query[n],files:s.files,file:s.file,rawBody:s.rawBody}}function St(s){return {locals:{},headersSent:false,statusCode:s.responseStatus,status(t){return s.status(t),this.statusCode=t,this},sendStatus(t){return this.status(t).send(String(t)),this},send(t){if(this.headersSent=true,!!!s.headers["Content-Type"]&&typeof t=="string"){let o=t.trim();if(o.startsWith("<!DOCTYPE")||o.startsWith("<html")||o.startsWith("<HTML"))return s.html(t),this}return s.send(t),this},json(t){return this.headersSent=true,s.json(t),this},redirect(t,r){this.headersSent=true;let o=typeof t=="string"?t:r,n=typeof t=="number"?t:302;return s.status(n).setHeader("Location",o),s.send(""),this},setHeader(t,r){let o=Array.isArray(r)?r.join(", "):String(r);return s.setHeader(t,o),this},set(t,r){if(typeof t=="object")for(let[o,n]of Object.entries(t))s.setHeader(o,n);else r!==void 0&&s.setHeader(t,r);return this},header(t,r){return this.set(t,r)},type(t){return s.setHeader("Content-Type",t),this},contentType(t){return this.type(t)},end(t){return this.headersSent=true,s.send(t??""),this},write(t){return true},get(t){return s.headers[t]},getHeader(t){return s.headers[t]},removeHeader(t){return delete s.headers[t],this},append(t,r){let o=s.headers[t],n=Array.isArray(r)?r.join(", "):r;return s.setHeader(t,o?`${o}, ${n}`:n),this},cookie(t,r,o){return s.cookie?.(t,r,o),this},clearCookie(t,r){return s.clearCookie?.(t,r),this},render(t,r,o){throw new Error("render() is not supported in Express compatibility layer")},format(t){return this},attachment(t){return t?s.setHeader("Content-Disposition",`attachment; filename="${t}"`):s.setHeader("Content-Disposition","attachment"),this},sendFile(t,r,o){s.file(t);},download(t,r,o,n){let i=typeof r=="string"?r:t.split("/").pop();this.attachment(i),s.file(t);},links(t){let r=Object.entries(t).map(([o,n])=>`<${n}>; rel="${o}"`).join(", ");return s.setHeader("Link",r),this},location(t){return s.setHeader("Location",t),this},vary(t){return s.setHeader("Vary",t),this},app:{},req:null}}function ye(s,e=""){return async(t,r,o)=>{let n=wt(t,e),i=St(r);await new Promise((p,d)=>{let a=c=>{if(c){d(c);return}p();};try{let c=s(n,i,a);c instanceof Promise&&c.catch(d);}catch(c){d(c);}}),await o();}}function wr(s,e=""){return async(t,r)=>{let o=wt(t,e),n=St(r);await s(o,n,()=>{});}}function Me(s,e){let t=et(s),r=e.stack;if(!r){console.warn("Express router has no stack - routes may not be registered");return}for(let o of r)bt(o,t);}function bt(s,e){if(s.route){let t=et(e+s.route.path),r=Object.keys(s.route.methods).filter(o=>s.route.methods[o]);for(let o of r){let n=s.route.stack.map(i=>i.handle);Sr(o.toUpperCase(),t,n,e);}return}if(s.handle&&typeof s.handle=="function"){let t=s.path||"",r=et(e+t),o=s.handle.stack;if(o&&Array.isArray(o)){for(let d of o)bt(d,r);return}let n=r==="/"?"/*":`${r}/*`,i=ye(s.handle,e),p=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];for(let d of p)w.addOrUpdate(d,n,[i],async()=>{},{excludeFromSwagger:true});}}function Sr(s,e,t,r){let o=t.slice(0,-1).map(p=>ye(p,r)),n=t[t.length-1],i=wr(n,r);w.addOrUpdate(s,e,o,i,{excludeFromSwagger:true});}function et(s){let e=s.replace(/\/+/g,"/");return e.startsWith("/")||(e="/"+e),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function xt(s){return {use(e,t){if(typeof e=="string"){let n=e,i=t,p=i.stack;if(p&&Array.isArray(p)){Me(n,i);return}s.use(ye(i,n));return}let r=e,o=r.stack;if(o&&Array.isArray(o)){Me("/",r);return}s.use(ye(r));}}}var Ot=s=>async(e,t,r)=>{try{let o=e.body;(s?.logRequest??!0)&&exports.logger.info({type:"request",requestId:e.id,method:s?.requestPayload?.method??!0?e.method:void 0,url:s?.requestPayload?.url??!0?e.url:void 0,ip:s?.requestPayload?.ip??!0?e.ip:void 0,headers:s?.requestPayload?.headers??!0?e.headers:void 0,body:s?.requestPayload?.body??!1?Rt(o):void 0});let n=performance.now();await r();let p=performance.now()-n;(s?.logResponse??!0)&&exports.logger.info({type:"response",requestId:e.id,status:s?.responsePayload?.status??t.responseStatus,duration:`${p.toFixed(2)}ms`,body:s?.responsePayload?.body??!1?Rt(t.getBody()):void 0,headers:s?.responsePayload?.headers??!1?t.headers:void 0});}catch(o){throw exports.logger.error(o),o}};function Rt(s){if(typeof s=="string"||s&&typeof s=="object"&&s.constructor===Object)return s}var Ae=class{storage=new Map;windowMs;constructor(e){this.windowMs=e;}async set(e,t){this.storage.set(e,t),setTimeout(()=>{this.storage.delete(e);},this.windowMs);}async get(e){let t=this.storage.get(e);return t||0}async delete(e){this.storage.delete(e);}};var Tt=(s,e)=>{let t={type:"ip",limit:100,message:"ERR_RATE_LIMIT_EXCEEDED",statusCode:429,...s},r={type:"memory",...e};r.type==="memory"&&!r.windowMs&&(r.windowMs=6e4);let o=r.type==="memory"?new Ae(r.windowMs):{get:r.get,set:r.set};return async(n,i,p)=>{let d=t.type==="ip"?n.ip:t.key(n),a=await o.get(d);return a>=t.limit?i.status(t.statusCode).json({message:t.message}):(await o.set(d,a+1),p())}};var He=class{store=new Map;async get(e){let t=this.store.get(e);if(t){if(t.exp&&Date.now()>t.exp){this.store.delete(e);return}return t.value}}async set(e,t,r){let o=r?Date.now()+r*1e3:void 0;this.store.set(e,{value:t,exp:o});}async destroy(e){this.store.delete(e);}};var Pt=s=>{let e=s?.name??"sid",t=s?.ttl??3600*24,r=s?.store??new He,o={path:"/",httpOnly:true,secure:false,sameSite:"Lax",...s?.cookie??{}};return async(n,i,p)=>{let a=n.cookies&&n.cookies[e],c=a?await r.get(a):void 0;(!a||!c)&&(a||=U.randomUUID(),c||={},await r.set(a,c,t),i.cookie?.(e,a,o)),n.session=c,n.saveSession=async()=>r.set(a,c,t),n.destroySession=async()=>{await r.destroy(a),i.clearCookie?.(e,o);},await p(),await r.set(a,c,t);}};var Ct=s=>async(e,t,r)=>{e.timeout=false;let o=setTimeout(()=>{e.timeout=true;},s.ms);try{await r();}finally{clearTimeout(o);}};var Et=s=>{let e=s?.header??"x-forwarded-for",t=s?.trust??true,r=s?.hop??"first";return async(o,n,i)=>{if(!t)return i();let p=o.headers.get(e);if(p&&typeof p=="string"){let d=p.split(",").map(a=>a.trim()).filter(Boolean);d.length&&(o.ip=r==="first"?d[0]:d[d.length-1]);}return i()}};var Mt=1024*1024,At=s=>{let t={limit:pe(s?.limit,Mt)??Mt,extended:s?.extended??false,charset:s?.charset??"utf8",allowEmpty:s?.allowEmpty??true,parameterLimit:s?.parameterLimit??1e3};return async(r,o,n)=>{if(!(r.headers.get("content-type")||"").includes("application/x-www-form-urlencoded"))return n();try{await br(r,t),await n();}catch(p){if(p instanceof Error&&p.message.includes("limit")){o.status(413).json({error:"Payload too large",message:"Request body exceeds the size limit"});return}throw p}}};async function br(s,e){let t=s.rawBody;if(t.byteLength>e.limit)throw new Error(`Body size ${t.byteLength} exceeds limit ${e.limit}`);let o=new TextDecoder(e.charset).decode(t),n=xr(o,e);s.body=n;}function xr(s,e){let t={},r=new URLSearchParams(s);if(r.size>e.parameterLimit)throw new Error(`Too many parameters: ${r.size} exceeds limit ${e.parameterLimit}`);for(let[o,n]of r.entries())!e.allowEmpty&&n===""||(e.extended?Rr(t,o,n):t[o]=n);return t}function Rr(s,e,t){let r=["__proto__","constructor","prototype"];if(r.includes(e))return;let o=e.match(/\[([^\]]*)\]/g);if(!o){r.includes(e)||(s[e]=t);return}let n=s,i=e.split("[")[0];if(r.includes(i))return;for(let d=0;d<o.length-1;d++){let a=o[d].slice(1,-1);if(r.includes(a))return;if(n[i]||(n[i]={}),a===""){Array.isArray(n[i])||(n[i]=[]),n=n[i];continue}n[i][a]||(n[i][a]={}),n=n[i][a];}let p=o[o.length-1].slice(1,-1);if(!r.includes(p)){if(p===""){Array.isArray(n)||(n=[]),n.push(t);return}n[p]=t;}}var tt=class{ITERATIONS=6e5;SALT_LENGTH=16;KEY_LENGTH=256;async hash(e){if(!e)throw new Error("Data to hash cannot be empty");let r=new TextEncoder().encode(e),o=crypto.getRandomValues(new Uint8Array(this.SALT_LENGTH)),n=await crypto.subtle.importKey("raw",r,{name:"PBKDF2"},false,["deriveBits"]),i=await crypto.subtle.deriveBits({name:"PBKDF2",salt:o,iterations:this.ITERATIONS,hash:"SHA-256"},n,this.KEY_LENGTH),p=this.encodeBase64(o),d=this.encodeBase64(new Uint8Array(i));return `${p}:${d}`}async compare(e,t){if(!e||!t)return false;try{let o=new TextEncoder().encode(t),n=e.split(":");if(n.length!==2)throw new Error("Invalid hash format");let[i,p]=n,d=this.decodeBase64(i),a=this.decodeBase64(p),c=await crypto.subtle.importKey("raw",o,{name:"PBKDF2"},!1,["deriveBits"]),u=await crypto.subtle.deriveBits({name:"PBKDF2",salt:d,iterations:this.ITERATIONS,hash:"SHA-256"},c,this.KEY_LENGTH),f=new Uint8Array(u);if(f.length!==a.length)return !1;let l=0;for(let m=0;m<f.length;m++)l|=f[m]^a[m];return l===0}catch{return false}}encodeBase64(e){let t="",r=e.byteLength;for(let o=0;o<r;o++)t+=String.fromCharCode(e[o]);return btoa(t)}decodeBase64(e){let t=atob(e),r=t.length,o=new Uint8Array(r);for(let n=0;n<r;n++)o[n]=t.charCodeAt(n);return o}},$e=new tt;var Ht=()=>async(s,e,t)=>(K(s.method)&&(s.rawBody=await s.arrayBuffer(),Object.defineProperty(s,"body",{value:void 0,writable:true,configurable:true,enumerable:true})),t());var $t=s=>{let e={origin:"*",methods:["GET","HEAD","PUT","PATCH","POST","DELETE"],allowedHeaders:"",exposedHeaders:"",credentials:false,maxAge:void 0,preflightContinue:false,optionsSuccessStatus:204,...s};return async(t,r,o)=>{let n=t.headers.get("origin")||"";if(t.method==="OPTIONS")return Or(t,r,e,n,o);Tr(t,r,e,n),await o();}};function Or(s,e,t,r,o){let n=kt(t,r);if(!n){e.forbidden("CORS origin not allowed");return}if(qt(e,t,n),t.preflightContinue){o();return}e.status(t.optionsSuccessStatus||204),e.send("");}function Tr(s,e,t,r){let o=kt(t,r);o&&qt(e,t,o);}function kt(s,e){if(typeof s.origin=="string")return s.origin;if(Array.isArray(s.origin)){let t=s.origin.find(r=>typeof r=="string"?r===e:r instanceof RegExp&&r.test(e));return typeof t=="string"?t:false}return "*"}function qt(s,e,t){if(s.setHeader("Access-Control-Allow-Origin",t),e.credentials&&s.setHeader("Access-Control-Allow-Credentials","true"),e.exposedHeaders&&e.exposedHeaders!==""){let o=Array.isArray(e.exposedHeaders)?e.exposedHeaders.join(","):e.exposedHeaders;s.setHeader("Access-Control-Expose-Headers",o);}if(e.allowedHeaders&&e.allowedHeaders!==""){let o=Array.isArray(e.allowedHeaders)?e.allowedHeaders.join(","):e.allowedHeaders;s.setHeader("Access-Control-Allow-Headers",o);}let r=Array.isArray(e.methods)?e.methods.join(","):e.methods;s.setHeader("Access-Control-Allow-Methods",String(r||"")),typeof e.maxAge=="number"&&s.setHeader("Access-Control-Max-Age",e.maxAge.toString());}var ke=class extends O{constructor(e,t,r){super(`FILE_TOO_LARGE: "${e}" is too large. Max size is ${r} bytes, but got ${t} bytes`);}};var rt=class{async tmpdir(){switch(g.type){case "node":case "bun":return (await import('os')).tmpdir();case "deno":return Deno.makeTempDir();default:throw new Error("Unsupported runtime")}}},jt=new rt;var Ft=1024*1024,Nt=s=>async(e,t,r)=>{let o=[];try{let n=e.headers.get("content-type")??e.headers.get("Content-Type");if(!n||!n.startsWith("multipart/form-data")||!e.rawBody)return r();let i=n.match(/boundary=(.*)(;|$)/i);if(!i)return r();let p=i[1].replace(/(^\s*"?|"?\s*$)/g,""),d=new Uint8Array(e.rawBody),a=new TextEncoder().encode(`--${p}`),c=new Uint8Array([13,10,13,10]),u=[],f=(C,N,ae=0)=>{e:for(let k=ae;k<=C.length-N.length;k++){for(let H=0;H<N.length;H++)if(C[k+H]!==N[H])continue e;return k}return -1},l=f(d,a);for(;l!==-1&&(l+=a.length,!(d[l]===45&&d[l+1]===45));){d[l]===13&&d[l+1]===10&&(l+=2);let C=f(d,c,l);if(C===-1)break;let N=d.subarray(l,C),ae=new TextDecoder().decode(N),k=C+c.length,H=f(d,a,k);if(H===-1)break;let q=H-1;d[q]===10&&q--,d[q]===13&&q--;let st=d.subarray(k,q+1);u.push({headers:ae,data:st}),l=H;}let m=[],v={},P=pe(s?.maxFileSize,Ft)??Ft;for(let C of u){let N=C.headers.split(`\r
83
- `).find(Se=>Se.toLowerCase().startsWith("content-disposition:"));if(!N)continue;let ae=N.match(/name="([^"]+)"/);if(!ae)continue;let k=ae[1],H=N.match(/filename="([^"]*)"/),q=H?H[1]:"";if(!!q){if(s?.maxFiles&&m.length>=s.maxFiles)return t.badRequest({...R(new O(`Too many files: Maximum ${s.maxFiles} files allowed`))});if(P&&C.data.length>P)return t.badRequest({...R(new ke(q,C.data.length,P))});let Se=C.headers.split(`\r
84
- `).find(er=>er.toLowerCase().startsWith("content-type:")),Ne=Se?Se.split(":")[1].trim():"application/octet-stream";if(s?.allowedMimeTypes&&!s.allowedMimeTypes.includes(Ne))return t.badRequest({...R(new O(`Invalid file type: "${Ne}" is not allowed. Allowed types: ${s.allowedMimeTypes.join(", ")}`))});let Yt=Pr(q),Xt=y.extName(Yt),De=y.join(await jt.tmpdir(),`${U.randomUUID()}${Xt}`);await S.writeFile(De,C.data),o.push(De),m.push({formName:k,mimeType:Ne,size:C.data.length,tmpPath:De,originalName:q});}else v[k]=new TextDecoder().decode(C.data);}e.files=m,e.body=v,await r(),await _t(o);}catch(n){throw await _t(o),n}},_t=async s=>{await Promise.allSettled(s.map(e=>S.unlink(e)));},Pr=s=>s.replace(/\.\./g,"").replace(/[\/\\]/g,"").replace(/\0/g,"").replace(/[\x00-\x1f\x80-\x9f]/g,"").trim();var Dt=s=>{let e={dnsPrefetchControl:true,frameguard:{action:"SAMEORIGIN"},hsts:{maxAge:15552e3,includeSubDomains:true,preload:false},contentTypeOptions:true,ieNoOpen:true,xssFilter:true,referrerPolicy:"no-referrer",crossOriginResourcePolicy:"same-origin",crossOriginOpenerPolicy:"same-origin",crossOriginEmbedderPolicy:"require-corp",contentSecurityPolicy:false,...s};return async(t,r,o)=>{if(e.dnsPrefetchControl&&r.setHeader("X-DNS-Prefetch-Control","off"),e.frameguard){let n="SAMEORIGIN";typeof e.frameguard=="object"&&(n=e.frameguard.action),r.setHeader("X-Frame-Options",n);}if(e.hsts){let n={};typeof e.hsts=="object"&&(n=e.hsts);let i=n.maxAge!==void 0?n.maxAge:15552e3,p=n.includeSubDomains!==void 0?n.includeSubDomains:true,d=n.preload!==void 0?n.preload:false,a=`max-age=${i}`;p!==false&&(a+="; includeSubDomains"),d&&(a+="; preload"),r.setHeader("Strict-Transport-Security",a);}e.contentTypeOptions&&r.setHeader("X-Content-Type-Options","nosniff"),e.ieNoOpen&&r.setHeader("X-Download-Options","noopen"),e.xssFilter&&r.setHeader("X-XSS-Protection","0"),e.referrerPolicy&&r.setHeader("Referrer-Policy",e.referrerPolicy),e.crossOriginResourcePolicy&&r.setHeader("Cross-Origin-Resource-Policy",e.crossOriginResourcePolicy),e.crossOriginOpenerPolicy&&r.setHeader("Cross-Origin-Opener-Policy",e.crossOriginOpenerPolicy),e.crossOriginEmbedderPolicy&&r.setHeader("Cross-Origin-Embedder-Policy",e.crossOriginEmbedderPolicy),e.contentSecurityPolicy&&r.setHeader("Content-Security-Policy",e.contentSecurityPolicy),await o();}};var we=class extends O{constructor(e){super(`JSON_NOT_VALID: "${JSON.stringify(e)}" is not a valid JSON`);}};var Bt=100*1024,Lt=s=>async(e,t,r)=>{if(!Cr(e)||!K(e.method))return r();let o=pe(s?.sizeLimit,Bt)??Bt,n=e.rawBody;if(!n)return s?.parseEmptyBodyAsObject&&(e.body={}),r();let i=n.byteLength;if(!i)return s?.parseEmptyBodyAsObject&&(e.body={}),r();if(i>o){let p={status:413,message:"ERR_REQUEST_BODY_TOO_LARGE",...s?.customErrorMessage};return t.status(p.status).json({error:p.message})}try{let p=s?.encoding??"utf-8",d=new TextDecoder(p).decode(n);e.body=JSON.parse(d);}catch(p){return p instanceof SyntaxError?t.badRequest({...R(new we("Invalid JSON syntax"))}):t.badRequest({...R(new we("Invalid request body encoding"))})}await r();};function Cr(s){let e=Er(s);return e?Mr(e)==="application/json":false}function Er(s){let e=s.headers.get("content-type")??s.headers.get("Content-Type");return e?Array.isArray(e)?e[0]||null:e:null}function Mr(s){let e=s.trim(),t=e.indexOf(";");return t===-1?e.toLowerCase():e.substring(0,t).trim().toLowerCase()}var It=s=>{let e={type:"standard",path:"/docs",title:"Balda API Documentation",description:"API Documentation from the Balda Framework",version:"1.0.0",servers:["http://localhost"],security:[],tags:[],components:{},securitySchemes:{},models:{}};s&&typeof s!="boolean"&&(e={...e,...s});let t=Hr(e),r=`${e.path}`,o=`${r}/json`,n;e.type==="rapidoc"?n=kr(o,e):e.type==="scalar"?n=qr(o,e):e.type==="elements"?n=jr(o,e):e.type==="custom"?n=e.customUIGenerator(o,e):n=$r(o,e),w.addOrUpdate("GET",r,[],(i,p)=>{p.html(n);}),w.addOrUpdate("GET",o,[],(i,p)=>{p.json(t);});},Z=s=>s?s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;"):"";function V(s){try{return zod.z.toJSONSchema(s)}catch(e){if(e instanceof Error&&e.message.includes("Custom types cannot be represented in JSON Schema")){let t=s._def;if(t?.typeName==="ZodInstanceof"){let r=new File([],"test");if(s.safeParse(r).success)return {type:"string",format:"binary"}}if(t?.typeName==="ZodObject"&&t?.shape){let r={},o=[];for(let[n,i]of Object.entries(t.shape))try{r[n]=V(i);let p=i._def;p?.typeName!=="ZodOptional"&&p?.typeName!=="ZodDefault"&&o.push(n);}catch{r[n]={type:"string",format:"binary"};}return {type:"object",properties:r,...o.length>0?{required:o}:{}}}return {type:"object",description:"Custom type"}}throw e}}function Hr(s){let e=w.getRoutes(),t={},r;if(s.models)if(Array.isArray(s.models))r=s.models.reduce((n,i,p)=>{let a=i&&typeof i=="object"&&"_def"in i?V(i):i,c=a.$id||a.title||`Model${p}`;return n[c]=a,n},{});else {r={};for(let[n,i]of Object.entries(s.models)){let p=i&&typeof i=="object"&&"_def"in i;r[n]=p?V(i):i;}}let o={...s.components,securitySchemes:s.securitySchemes||{},schemas:r?{...s.components?.schemas||{},...r}:s.components?.schemas?{...s.components.schemas}:void 0};for(let n of e){let i=n.swaggerOptions;if(i?.excludeFromSwagger)continue;t[n.path]||(t[n.path]={});let p=n.method.toLowerCase(),d={summary:i?.name||`${p.toUpperCase()} ${n.path}`,description:i?.description||"",tags:i?.service?[i.service]:[],deprecated:i?.deprecated||false},a=[];if(i?.query&&i.query.type==="object"&&i.query.shape)for(let[c,u]of Object.entries(i.query.shape))a.push({name:c,in:"query",required:Array.isArray(i.query.shape[c].required)?i.query.shape[c].required.includes(c):false,schema:V(u)});if(i&&i.params?a=a.concat(Ut(n.path,i.params)):a=a.concat(Ut(n.path)),a.length>0&&(d.parameters=a),i?.requestBody){let c="application/json";i.bodyType==="form-data"?c="multipart/form-data":i.bodyType==="urlencoded"&&(c="application/x-www-form-urlencoded"),d.requestBody={content:{[c]:{schema:V(i.requestBody)}},required:true};}else i?.bodyType&&(i.bodyType.includes("form-data")||i.bodyType.includes("urlencoded"))&&(d.requestBody={content:{[i.bodyType]:{schema:{type:"object"}}},required:true});if(d.responses={},i?.responses)for(let[c,u]of Object.entries(i.responses))d.responses[c]={description:`Response for ${c}`,content:{"application/json":{schema:V(u)}}};if(i?.errors)for(let[c,u]of Object.entries(i.errors))d.responses[c]={description:`Error response for ${c}`,content:{"application/json":{schema:V(u)}}};if(Object.keys(d.responses).length===0&&(d.responses[200]={description:"Successful response",content:{"application/json":{schema:{type:"object"}}}}),i?.security){let c=[];Array.isArray(i.security)||(i.security=[i.security]);for(let u of i.security)if(u.type==="bearer")o.securitySchemes.bearer||(o.securitySchemes.bearer={type:"http",scheme:"bearer",bearerFormat:u.bearerFormat||"JWT",description:u.description}),c.push({bearer:[]});else if(u.type==="apiKey")o.securitySchemes[u.name]||(o.securitySchemes[u.name]={type:"apiKey",name:u.name,in:u.in,description:u.description}),c.push({[u.name]:[]});else if(u.type==="oauth2"){let f=u.name||"oauth2";o.securitySchemes[f]||(o.securitySchemes[f]={type:"oauth2",flows:u.flows,description:u.description}),c.push({[f]:[]});}else if(u.type==="openIdConnect"){let f=u.name||"openIdConnect";o.securitySchemes[f]||(o.securitySchemes[f]={type:"openIdConnect",openIdConnectUrl:u.openIdConnectUrl,description:u.description}),c.push({[f]:[]});}c.length&&(d.security=c);}else s.security&&(d.security=s.security);t[n.path][p]=d;}return {openapi:"3.0.0",info:{title:s.title,description:s.description,version:s.version,...s.info},servers:s.servers?.map(n=>({url:n}))||[{url:"/"}],paths:t,components:o,security:s.security||[],tags:s.tags?Object.entries(s.tags).map(([n,i])=>({name:n,...i})):[]}}function $r(s,e){return `
82
+ `));let n=o.reduce((d,a)=>d+a.byteLength,0),i=new Uint8Array(n),p=0;for(let d of o)i.set(d,p),p+=d.byteLength;return i}validateOptions(e){let{body:t,formData:r,urlencoded:o}=e;if(t&&(r||o))throw new Error("Only one of body, formData, urlencoded can be provided");if(r&&(o||t))throw new Error("Only one of formData, urlencoded can be provided");if(o&&(t||r))throw new Error("Only one of urlencoded, body can be provided")}};var vr=1024,wr=6,Sr=[/text\/.+/,/application\/json/,/application\/javascript/,/application\/xml/,/application\/.*\+json/,/application\/.*\+xml/],wt=s=>{let e=s?.threshold??vr,t=Math.max(0,Math.min(9,s?.level??wr)),r=s?.filter??Sr;return async(o,n,i)=>{if(!(o.headers.get("accept-encoding")||"").includes("gzip"))return i();let a=n.send.bind(n),c=n.json.bind(n),u=n.text.bind(n),h=(l,m)=>{if(!br(l,m,e,r))return l;let v=St(l);if(!v||v.length<e)return l;let P=zlib.gzipSync(v,{level:t});return n.setHeader("Content-Encoding","gzip"),n.setHeader("Content-Length",P.length.toString()),P};n.send=function(l){let m=n.headers["content-type"],v=h(l,m);return a(v)},n.json=function(l){let m=JSON.stringify(l),v=h(m,"application/json");return v!==m?(n.setHeader("Content-Type","application/json"),a(v)):c(l)},n.text=function(l){let m=h(l,"text/plain");return m!==l?(n.setHeader("Content-Type","text/plain"),a(m)):u(l)},await i();}},br=(s,e,t,r)=>{if(!s||!e)return false;let o=St(s);return !o||o.length<t?false:r.some(n=>n.test(e))},St=s=>typeof s=="string"?Buffer.from(s,"utf-8"):Buffer.isBuffer(s)?s:s instanceof Uint8Array?Buffer.from(s):typeof s=="object"?Buffer.from(JSON.stringify(s),"utf-8"):null;var bt=s=>{let e={secret:s?.secret??"",defaults:{path:"/",httpOnly:true,secure:true,sameSite:"Lax",...s?.defaults},parse:s?.parse??true,sign:s?.sign??false};return async(t,r,o)=>{if(e.parse){let n=Rr(t.headers.get("cookie")||"");t.cookies={};for(let[i,p]of Object.entries(n)){if(e.sign&&e.secret){let d=await Tr(p,e.secret);d!==false&&(t.cookies[i]=d);continue}t.cookies[i]=p;}}r.cookie=(n,i,p)=>{Rt(r,n,i,{...e.defaults,...p},e);},r.clearCookie=(n,i)=>{xr(r,n,{...e.defaults,...i});},await o();}};function Rr(s){let e={};if(!s)return e;let t=s.split(";");for(let r of t){let[o,n]=r.trim().split("=");o&&n&&(e[decodeURIComponent(o)]=decodeURIComponent(n));}return e}async function Rt(s,e,t,r,o){let n=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;r.domain&&(n+=`; Domain=${r.domain}`),r.path&&(n+=`; Path=${r.path}`),r.expires&&(n+=`; Expires=${r.expires.toUTCString()}`),r.maxAge&&(n+=`; Max-Age=${r.maxAge}`),r.secure&&(n+="; Secure"),r.httpOnly&&(n+="; HttpOnly"),r.sameSite&&(n+=`; SameSite=${r.sameSite}`),r.priority&&(n+=`; Priority=${r.priority}`),o.sign&&o.secret&&(n=await Or(n,o.secret));let i=s.headers["set-cookie"]||"",p=i?`${i}, ${n}`:n;s.setHeader("Set-Cookie",p);}function xr(s,e,t){let r={...t,expires:new Date(0),maxAge:0};Rt(s,e,"",r,{secret:"",sign:false});}async function Or(s,e){let t=new TextEncoder,r=t.encode(e),o=t.encode(s),n=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},false,["sign"]),i=await crypto.subtle.sign("HMAC",n,o),p=new Uint8Array(i),d=Array.from(p).map(a=>a.toString(16).padStart(2,"0")).join("");return `${s}.${d}`}async function Tr(s,e){let t=s.split(".");if(t.length!==2)return false;let[r,o]=t,n=new TextEncoder,i=n.encode(e),p=n.encode(r),d=await crypto.subtle.importKey("raw",i,{name:"HMAC",hash:"SHA-256"},false,["sign"]),a=await crypto.subtle.sign("HMAC",d,p),c=new Uint8Array(a),u=Array.from(c).map(h=>h.toString(16).padStart(2,"0")).join("");return o===u?r:false}function xt(s,e=""){let t=new URL(s.url),r=Object.fromEntries(s.headers.entries());return {body:s.body,query:s.query,params:s.params,cookies:s.cookies,session:s.session,originalUrl:t.pathname+t.search,baseUrl:e,path:t.pathname.replace(e,"")||"/",method:s.method,ip:s.ip,headers:r,url:t.pathname,get(n){return s.headers.get(n.toLowerCase())??void 0},header(n){return s.headers.get(n.toLowerCase())??void 0},app:{},res:null,route:null,protocol:t.protocol.replace(":",""),secure:t.protocol==="https:",hostname:t.hostname,host:t.host,fresh:false,stale:true,xhr:r["x-requested-with"]?.toLowerCase()==="xmlhttprequest",accepts:()=>{},acceptsCharsets:()=>{},acceptsEncodings:()=>{},acceptsLanguages:()=>{},is:()=>null,range:()=>{},param:n=>s.params[n]??s.query[n],files:s.files,file:s.file,rawBody:s.rawBody}}function Ot(s){return {locals:{},headersSent:false,statusCode:s.responseStatus,status(t){return s.status(t),this.statusCode=t,this},sendStatus(t){return this.status(t).send(String(t)),this},send(t){if(this.headersSent=true,!!!s.headers["Content-Type"]&&typeof t=="string"){let o=t.trim();if(o.startsWith("<!DOCTYPE")||o.startsWith("<html")||o.startsWith("<HTML"))return s.html(t),this}return s.send(t),this},json(t){return this.headersSent=true,s.json(t),this},redirect(t,r){this.headersSent=true;let o=typeof t=="string"?t:r,n=typeof t=="number"?t:302;return s.status(n).setHeader("Location",o),s.send(""),this},setHeader(t,r){let o=Array.isArray(r)?r.join(", "):String(r);return s.setHeader(t,o),this},set(t,r){if(typeof t=="object")for(let[o,n]of Object.entries(t))s.setHeader(o,n);else r!==void 0&&s.setHeader(t,r);return this},header(t,r){return this.set(t,r)},type(t){return s.setHeader("Content-Type",t),this},contentType(t){return this.type(t)},end(t){return this.headersSent=true,s.send(t??""),this},write(t){return true},get(t){return s.headers[t]},getHeader(t){return s.headers[t]},removeHeader(t){return delete s.headers[t],this},append(t,r){let o=s.headers[t],n=Array.isArray(r)?r.join(", "):r;return s.setHeader(t,o?`${o}, ${n}`:n),this},cookie(t,r,o){return s.cookie?.(t,r,o),this},clearCookie(t,r){return s.clearCookie?.(t,r),this},render(t,r,o){throw new Error("render() is not supported in Express compatibility layer")},format(t){return this},attachment(t){return t?s.setHeader("Content-Disposition",`attachment; filename="${t}"`):s.setHeader("Content-Disposition","attachment"),this},sendFile(t,r,o){s.file(t);},download(t,r,o,n){let i=typeof r=="string"?r:t.split("/").pop();this.attachment(i),s.file(t);},links(t){let r=Object.entries(t).map(([o,n])=>`<${n}>; rel="${o}"`).join(", ");return s.setHeader("Link",r),this},location(t){return s.setHeader("Location",t),this},vary(t){return s.setHeader("Vary",t),this},app:{},req:null}}function we(s,e=""){return async(t,r,o)=>{let n=xt(t,e),i=Ot(r);await new Promise((p,d)=>{let a=c=>{if(c){d(c);return}p();};try{let c=s(n,i,a);c instanceof Promise&&c.catch(d);}catch(c){d(c);}}),await o();}}function Pr(s,e=""){return async(t,r)=>{let o=xt(t,e),n=Ot(r);await s(o,n,()=>{});}}function He(s,e){let t=rt(s),r=e.stack;if(!r){console.warn("Express router has no stack - routes may not be registered");return}for(let o of r)Tt(o,t);}function Tt(s,e){if(s.route){let t=rt(e+s.route.path),r=Object.keys(s.route.methods).filter(o=>s.route.methods[o]);for(let o of r){let n=s.route.stack.map(i=>i.handle);Cr(o.toUpperCase(),t,n,e);}return}if(s.handle&&typeof s.handle=="function"){let t=s.path||"",r=rt(e+t),o=s.handle.stack;if(o&&Array.isArray(o)){for(let d of o)Tt(d,r);return}let n=r==="/"?"/*":`${r}/*`,i=we(s.handle,e),p=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];for(let d of p)w.addOrUpdate(d,n,[i],async()=>{},{excludeFromSwagger:true});}}function Cr(s,e,t,r){let o=t.slice(0,-1).map(p=>we(p,r)),n=t[t.length-1],i=Pr(n,r);w.addOrUpdate(s,e,o,i,{excludeFromSwagger:true});}function rt(s){let e=s.replace(/\/+/g,"/");return e.startsWith("/")||(e="/"+e),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function Pt(s){return {use(e,t){if(typeof e=="string"){let n=e,i=t,p=i.stack;if(p&&Array.isArray(p)){He(n,i);return}s.use(we(i,n));return}let r=e,o=r.stack;if(o&&Array.isArray(o)){He("/",r);return}s.use(we(r));}}}var Et=s=>async(e,t,r)=>{try{let o=e.body;(s?.logRequest??!0)&&exports.logger.info({type:"request",requestId:e.id,method:s?.requestPayload?.method??!0?e.method:void 0,url:s?.requestPayload?.url??!0?e.url:void 0,ip:s?.requestPayload?.ip??!0?e.ip:void 0,headers:s?.requestPayload?.headers??!0?e.headers:void 0,body:s?.requestPayload?.body??!1?Ct(o):void 0});let n=performance.now();await r();let p=performance.now()-n;(s?.logResponse??!0)&&exports.logger.info({type:"response",requestId:e.id,status:s?.responsePayload?.status??t.responseStatus,duration:`${p.toFixed(2)}ms`,body:s?.responsePayload?.body??!1?Ct(t.getBody()):void 0,headers:s?.responsePayload?.headers??!1?t.headers:void 0});}catch(o){throw exports.logger.error(o),o}};function Ct(s){if(typeof s=="string"||s&&typeof s=="object"&&s.constructor===Object)return s}var Er=["POST"],Mr="X-HTTP-Method-Override",Ar=["GET","POST","PUT","PATCH","DELETE"],Mt=s=>{let e=(s?.methods??Er).map(r=>r.toUpperCase()),t=s?.header??Mr;return async(r,o,n)=>{let i=r.method.toUpperCase();if(!e.includes(i))return n();let p=r.headers.get(t);if(!p)return n();let d=p.toUpperCase();if(!Ar.includes(d))return n();r.method=d,await n();}};var qe=class{storage=new Map;windowMs;constructor(e){this.windowMs=e;}async set(e,t){this.storage.set(e,t),setTimeout(()=>{this.storage.delete(e);},this.windowMs);}async get(e){let t=this.storage.get(e);return t||0}async delete(e){this.storage.delete(e);}};var At=(s,e)=>{let t={type:"ip",limit:100,message:"ERR_RATE_LIMIT_EXCEEDED",statusCode:429,...s},r={type:"memory",...e};r.type==="memory"&&!r.windowMs&&(r.windowMs=6e4);let o=r.type==="memory"?new qe(r.windowMs):{get:r.get,set:r.set};return async(n,i,p)=>{let d=t.type==="ip"?n.ip:t.key(n),a=await o.get(d);return a>=t.limit?i.status(t.statusCode).json({message:t.message}):(await o.set(d,a+1),p())}};var ke=class{store=new Map;async get(e){let t=this.store.get(e);if(t){if(t.exp&&Date.now()>t.exp){this.store.delete(e);return}return t.value}}async set(e,t,r){let o=r?Date.now()+r*1e3:void 0;this.store.set(e,{value:t,exp:o});}async destroy(e){this.store.delete(e);}};var Ht=s=>{let e=s?.name??"sid",t=s?.ttl??3600*24,r=s?.store??new ke,o={path:"/",httpOnly:true,secure:false,sameSite:"Lax",...s?.cookie??{}};return async(n,i,p)=>{let a=n.cookies&&n.cookies[e],c=a?await r.get(a):void 0;(!a||!c)&&(a||=I.randomUUID(),c||={},await r.set(a,c,t),i.cookie?.(e,a,o)),n.session=c,n.saveSession=async()=>r.set(a,c,t),n.destroySession=async()=>{await r.destroy(a),i.clearCookie?.(e,o);},await p(),await r.set(a,c,t);}};var qt=s=>async(e,t,r)=>{e.timeout=false;let o=setTimeout(()=>{e.timeout=true;},s.ms);try{await r();}finally{clearTimeout(o);}};var kt=s=>{let e=s?.header??"x-forwarded-for",t=s?.trust??true,r=s?.hop??"first";return async(o,n,i)=>{if(!t)return i();let p=o.headers.get(e);if(p&&typeof p=="string"){let d=p.split(",").map(a=>a.trim()).filter(Boolean);d.length&&(o.ip=r==="first"?d[0]:d[d.length-1]);}return i()}};var $t=1024*1024,jt=s=>{let t={limit:de(s?.limit,$t)??$t,extended:s?.extended??false,charset:s?.charset??"utf8",allowEmpty:s?.allowEmpty??true,parameterLimit:s?.parameterLimit??1e3};return async(r,o,n)=>{if(!(r.headers.get("content-type")||"").includes("application/x-www-form-urlencoded"))return n();try{await Hr(r,t),await n();}catch(p){if(p instanceof Error&&p.message.includes("limit")){o.status(413).json({error:"Payload too large",message:"Request body exceeds the size limit"});return}throw p}}};async function Hr(s,e){let t=s.rawBody;if(t.byteLength>e.limit)throw new Error(`Body size ${t.byteLength} exceeds limit ${e.limit}`);let o=new TextDecoder(e.charset).decode(t),n=qr(o,e);s.body=n;}function qr(s,e){let t={},r=new URLSearchParams(s);if(r.size>e.parameterLimit)throw new Error(`Too many parameters: ${r.size} exceeds limit ${e.parameterLimit}`);for(let[o,n]of r.entries())!e.allowEmpty&&n===""||(e.extended?kr(t,o,n):t[o]=n);return t}function kr(s,e,t){let r=["__proto__","constructor","prototype"];if(r.includes(e))return;let o=e.match(/\[([^\]]*)\]/g);if(!o){r.includes(e)||(s[e]=t);return}let n=s,i=e.split("[")[0];if(r.includes(i))return;for(let d=0;d<o.length-1;d++){let a=o[d].slice(1,-1);if(r.includes(a))return;if(n[i]||(n[i]={}),a===""){Array.isArray(n[i])||(n[i]=[]),n=n[i];continue}n[i][a]||(n[i][a]={}),n=n[i][a];}let p=o[o.length-1].slice(1,-1);if(!r.includes(p)){if(p===""){Array.isArray(n)||(n=[]),n.push(t);return}n[p]=t;}}var st=class{ITERATIONS=6e5;SALT_LENGTH=16;KEY_LENGTH=256;async hash(e){if(!e)throw new Error("Data to hash cannot be empty");let r=new TextEncoder().encode(e),o=crypto.getRandomValues(new Uint8Array(this.SALT_LENGTH)),n=await crypto.subtle.importKey("raw",r,{name:"PBKDF2"},false,["deriveBits"]),i=await crypto.subtle.deriveBits({name:"PBKDF2",salt:o,iterations:this.ITERATIONS,hash:"SHA-256"},n,this.KEY_LENGTH),p=this.encodeBase64(o),d=this.encodeBase64(new Uint8Array(i));return `${p}:${d}`}async compare(e,t){if(!e||!t)return false;try{let o=new TextEncoder().encode(t),n=e.split(":");if(n.length!==2)throw new Error("Invalid hash format");let[i,p]=n,d=this.decodeBase64(i),a=this.decodeBase64(p),c=await crypto.subtle.importKey("raw",o,{name:"PBKDF2"},!1,["deriveBits"]),u=await crypto.subtle.deriveBits({name:"PBKDF2",salt:d,iterations:this.ITERATIONS,hash:"SHA-256"},c,this.KEY_LENGTH),h=new Uint8Array(u);if(h.length!==a.length)return !1;let l=0;for(let m=0;m<h.length;m++)l|=h[m]^a[m];return l===0}catch{return false}}encodeBase64(e){let t="",r=e.byteLength;for(let o=0;o<r;o++)t+=String.fromCharCode(e[o]);return btoa(t)}decodeBase64(e){let t=atob(e),r=t.length,o=new Uint8Array(r);for(let n=0;n<r;n++)o[n]=t.charCodeAt(n);return o}},$e=new st;var Lt=()=>async(s,e,t)=>(V(s.method)&&(s.rawBody=await s.arrayBuffer(),Object.defineProperty(s,"body",{value:void 0,writable:true,configurable:true,enumerable:true})),t());var Ft=s=>{let e={origin:"*",methods:["GET","HEAD","PUT","PATCH","POST","DELETE"],allowedHeaders:"",exposedHeaders:"",credentials:false,maxAge:void 0,preflightContinue:false,optionsSuccessStatus:204,...s};return async(t,r,o)=>{let n=t.headers.get("origin")||"";if(t.method==="OPTIONS")return $r(t,r,e,n,o);jr(t,r,e,n),await o();}};function $r(s,e,t,r,o){let n=_t(t,r);if(!n){e.forbidden("CORS origin not allowed");return}if(Nt(e,t,n),t.preflightContinue){o();return}e.status(t.optionsSuccessStatus||204),e.send("");}function jr(s,e,t,r){let o=_t(t,r);o&&Nt(e,t,o);}function _t(s,e){if(typeof s.origin=="string")return s.origin;if(Array.isArray(s.origin)){let t=s.origin.find(r=>typeof r=="string"?r===e:r instanceof RegExp&&r.test(e));return typeof t=="string"?t:false}return "*"}function Nt(s,e,t){if(s.setHeader("Access-Control-Allow-Origin",t),e.credentials&&s.setHeader("Access-Control-Allow-Credentials","true"),e.exposedHeaders&&e.exposedHeaders!==""){let o=Array.isArray(e.exposedHeaders)?e.exposedHeaders.join(","):e.exposedHeaders;s.setHeader("Access-Control-Expose-Headers",o);}if(e.allowedHeaders&&e.allowedHeaders!==""){let o=Array.isArray(e.allowedHeaders)?e.allowedHeaders.join(","):e.allowedHeaders;s.setHeader("Access-Control-Allow-Headers",o);}let r=Array.isArray(e.methods)?e.methods.join(","):e.methods;s.setHeader("Access-Control-Allow-Methods",String(r||"")),typeof e.maxAge=="number"&&s.setHeader("Access-Control-Max-Age",e.maxAge.toString());}var je=class extends O{constructor(e,t,r){super(`FILE_TOO_LARGE: "${e}" is too large. Max size is ${r} bytes, but got ${t} bytes`);}};var ot=class{async tmpdir(){switch(g.type){case "node":case "bun":return (await import('os')).tmpdir();case "deno":return Deno.makeTempDir();default:throw new Error("Unsupported runtime")}}},Dt=new ot;var Bt=1024*1024,It=s=>async(e,t,r)=>{let o=[];try{let n=e.headers.get("content-type")??e.headers.get("Content-Type");if(!n||!n.startsWith("multipart/form-data")||!e.rawBody)return r();let i=n.match(/boundary=(.*)(;|$)/i);if(!i)return r();let p=i[1].replace(/(^\s*"?|"?\s*$)/g,""),d=new Uint8Array(e.rawBody),a=new TextEncoder().encode(`--${p}`),c=new Uint8Array([13,10,13,10]),u=[],h=(C,N,pe=0)=>{e:for(let k=pe;k<=C.length-N.length;k++){for(let H=0;H<N.length;H++)if(C[k+H]!==N[H])continue e;return k}return -1},l=h(d,a);for(;l!==-1&&(l+=a.length,!(d[l]===45&&d[l+1]===45));){d[l]===13&&d[l+1]===10&&(l+=2);let C=h(d,c,l);if(C===-1)break;let N=d.subarray(l,C),pe=new TextDecoder().decode(N),k=C+c.length,H=h(d,a,k);if(H===-1)break;let $=H-1;d[$]===10&&$--,d[$]===13&&$--;let nt=d.subarray(k,$+1);u.push({headers:pe,data:nt}),l=H;}let m=[],v={},P=de(s?.maxFileSize,Bt)??Bt;for(let C of u){let N=C.headers.split(`\r
83
+ `).find(Re=>Re.toLowerCase().startsWith("content-disposition:"));if(!N)continue;let pe=N.match(/name="([^"]+)"/);if(!pe)continue;let k=pe[1],H=N.match(/filename="([^"]*)"/),$=H?H[1]:"";if(!!$){if(s?.maxFiles&&m.length>=s.maxFiles)return t.badRequest({...x(new O(`Too many files: Maximum ${s.maxFiles} files allowed`))});if(P&&C.data.length>P)return t.badRequest({...x(new je($,C.data.length,P))});let Re=C.headers.split(`\r
84
+ `).find(rr=>rr.toLowerCase().startsWith("content-type:")),De=Re?Re.split(":")[1].trim():"application/octet-stream";if(s?.allowedMimeTypes&&!s.allowedMimeTypes.includes(De))return t.badRequest({...x(new O(`Invalid file type: "${De}" is not allowed. Allowed types: ${s.allowedMimeTypes.join(", ")}`))});let er=Lr($),tr=y.extName(er),Be=y.join(await Dt.tmpdir(),`${I.randomUUID()}${tr}`);await S.writeFile(Be,C.data),o.push(Be),m.push({formName:k,mimeType:De,size:C.data.length,tmpPath:Be,originalName:$});}else v[k]=new TextDecoder().decode(C.data);}e.files=m,e.body=v,await r(),await Qt(o);}catch(n){throw await Qt(o),n}},Qt=async s=>{await Promise.allSettled(s.map(e=>S.unlink(e)));},Lr=s=>s.replace(/\.\./g,"").replace(/[\/\\]/g,"").replace(/\0/g,"").replace(/[\x00-\x1f\x80-\x9f]/g,"").trim();var Ut=s=>{let e={dnsPrefetchControl:true,frameguard:{action:"SAMEORIGIN"},hsts:{maxAge:15552e3,includeSubDomains:true,preload:false},contentTypeOptions:true,ieNoOpen:true,xssFilter:true,referrerPolicy:"no-referrer",crossOriginResourcePolicy:"same-origin",crossOriginOpenerPolicy:"same-origin",crossOriginEmbedderPolicy:"require-corp",contentSecurityPolicy:false,...s};return async(t,r,o)=>{if(e.dnsPrefetchControl&&r.setHeader("X-DNS-Prefetch-Control","off"),e.frameguard){let n="SAMEORIGIN";typeof e.frameguard=="object"&&(n=e.frameguard.action),r.setHeader("X-Frame-Options",n);}if(e.hsts){let n={};typeof e.hsts=="object"&&(n=e.hsts);let i=n.maxAge!==void 0?n.maxAge:15552e3,p=n.includeSubDomains!==void 0?n.includeSubDomains:true,d=n.preload!==void 0?n.preload:false,a=`max-age=${i}`;p!==false&&(a+="; includeSubDomains"),d&&(a+="; preload"),r.setHeader("Strict-Transport-Security",a);}e.contentTypeOptions&&r.setHeader("X-Content-Type-Options","nosniff"),e.ieNoOpen&&r.setHeader("X-Download-Options","noopen"),e.xssFilter&&r.setHeader("X-XSS-Protection","0"),e.referrerPolicy&&r.setHeader("Referrer-Policy",e.referrerPolicy),e.crossOriginResourcePolicy&&r.setHeader("Cross-Origin-Resource-Policy",e.crossOriginResourcePolicy),e.crossOriginOpenerPolicy&&r.setHeader("Cross-Origin-Opener-Policy",e.crossOriginOpenerPolicy),e.crossOriginEmbedderPolicy&&r.setHeader("Cross-Origin-Embedder-Policy",e.crossOriginEmbedderPolicy),e.contentSecurityPolicy&&r.setHeader("Content-Security-Policy",e.contentSecurityPolicy),await o();}};var be=class extends O{constructor(e){super(`JSON_NOT_VALID: "${JSON.stringify(e)}" is not a valid JSON`);}};var Gt=100*1024,zt=s=>async(e,t,r)=>{if(!Fr(e)||!V(e.method))return r();let o=de(s?.sizeLimit,Gt)??Gt,n=e.rawBody;if(!n)return s?.parseEmptyBodyAsObject&&(e.body={}),r();let i=n.byteLength;if(!i)return s?.parseEmptyBodyAsObject&&(e.body={}),r();if(i>o){let p={status:413,message:"ERR_REQUEST_BODY_TOO_LARGE",...s?.customErrorMessage};return t.status(p.status).json({error:p.message})}try{let p=s?.encoding??"utf-8",d=new TextDecoder(p).decode(n);e.body=JSON.parse(d);}catch(p){return p instanceof SyntaxError?t.badRequest({...x(new be("Invalid JSON syntax"))}):t.badRequest({...x(new be("Invalid request body encoding"))})}await r();};function Fr(s){let e=_r(s);return e?Nr(e)==="application/json":false}function _r(s){let e=s.headers.get("content-type")??s.headers.get("Content-Type");return e?Array.isArray(e)?e[0]||null:e:null}function Nr(s){let e=s.trim(),t=e.indexOf(";");return t===-1?e.toLowerCase():e.substring(0,t).trim().toLowerCase()}var Vt=s=>{let e={type:"standard",path:"/docs",title:"Balda API Documentation",description:"API Documentation from the Balda Framework",version:"1.0.0",servers:["http://localhost"],security:[],tags:[],components:{},securitySchemes:{},models:{}};s&&typeof s!="boolean"&&(e={...e,...s});let t=Br(e),r=`${e.path}`,o=`${r}/json`,n;e.type==="rapidoc"?n=Ir(o,e):e.type==="scalar"?n=Ur(o,e):e.type==="elements"?n=Gr(o,e):e.type==="custom"?n=e.customUIGenerator(o,e):n=Qr(o,e),w.addOrUpdate("GET",r,[],(i,p)=>{p.html(n);}),w.addOrUpdate("GET",o,[],(i,p)=>{p.json(t);});},W=s=>s?s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;"):"";function Z(s){try{return zod.z.toJSONSchema(s)}catch(e){if(e instanceof Error&&e.message.includes("Custom types cannot be represented in JSON Schema")){let t=s._def;if(t?.typeName==="ZodInstanceof"){let r=new File([],"test");if(s.safeParse(r).success)return {type:"string",format:"binary"}}if(t?.typeName==="ZodObject"&&t?.shape){let r={},o=[];for(let[n,i]of Object.entries(t.shape))try{r[n]=Z(i);let p=i._def;p?.typeName!=="ZodOptional"&&p?.typeName!=="ZodDefault"&&o.push(n);}catch{r[n]={type:"string",format:"binary"};}return {type:"object",properties:r,...o.length>0?{required:o}:{}}}return {type:"object",description:"Custom type"}}throw e}}function Br(s){let e=w.getRoutes(),t={},r;if(s.models)if(Array.isArray(s.models))r=s.models.reduce((n,i,p)=>{let a=i&&typeof i=="object"&&"_def"in i?Z(i):i,c=a.$id||a.title||`Model${p}`;return n[c]=a,n},{});else {r={};for(let[n,i]of Object.entries(s.models)){let p=i&&typeof i=="object"&&"_def"in i;r[n]=p?Z(i):i;}}let o={...s.components,securitySchemes:s.securitySchemes||{},schemas:r?{...s.components?.schemas||{},...r}:s.components?.schemas?{...s.components.schemas}:void 0};for(let n of e){let i=n.swaggerOptions;if(i?.excludeFromSwagger)continue;t[n.path]||(t[n.path]={});let p=n.method.toLowerCase(),d={summary:i?.name||`${p.toUpperCase()} ${n.path}`,description:i?.description||"",tags:i?.service?[i.service]:[],deprecated:i?.deprecated||false},a=[];if(i?.query&&i.query.type==="object"&&i.query.shape)for(let[c,u]of Object.entries(i.query.shape))a.push({name:c,in:"query",required:Array.isArray(i.query.shape[c].required)?i.query.shape[c].required.includes(c):false,schema:Z(u)});if(i&&i.params?a=a.concat(Kt(n.path,i.params)):a=a.concat(Kt(n.path)),a.length>0&&(d.parameters=a),i?.requestBody){let c="application/json";i.bodyType==="form-data"?c="multipart/form-data":i.bodyType==="urlencoded"&&(c="application/x-www-form-urlencoded"),d.requestBody={content:{[c]:{schema:Z(i.requestBody)}},required:true};}else i?.bodyType&&(i.bodyType.includes("form-data")||i.bodyType.includes("urlencoded"))&&(d.requestBody={content:{[i.bodyType]:{schema:{type:"object"}}},required:true});if(d.responses={},i?.responses)for(let[c,u]of Object.entries(i.responses))d.responses[c]={description:`Response for ${c}`,content:{"application/json":{schema:Z(u)}}};if(i?.errors)for(let[c,u]of Object.entries(i.errors))d.responses[c]={description:`Error response for ${c}`,content:{"application/json":{schema:Z(u)}}};if(Object.keys(d.responses).length===0&&(d.responses[200]={description:"Successful response",content:{"application/json":{schema:{type:"object"}}}}),i?.security){let c=[];Array.isArray(i.security)||(i.security=[i.security]);for(let u of i.security)if(u.type==="bearer")o.securitySchemes.bearer||(o.securitySchemes.bearer={type:"http",scheme:"bearer",bearerFormat:u.bearerFormat||"JWT",description:u.description}),c.push({bearer:[]});else if(u.type==="apiKey")o.securitySchemes[u.name]||(o.securitySchemes[u.name]={type:"apiKey",name:u.name,in:u.in,description:u.description}),c.push({[u.name]:[]});else if(u.type==="oauth2"){let h=u.name||"oauth2";o.securitySchemes[h]||(o.securitySchemes[h]={type:"oauth2",flows:u.flows,description:u.description}),c.push({[h]:[]});}else if(u.type==="openIdConnect"){let h=u.name||"openIdConnect";o.securitySchemes[h]||(o.securitySchemes[h]={type:"openIdConnect",openIdConnectUrl:u.openIdConnectUrl,description:u.description}),c.push({[h]:[]});}c.length&&(d.security=c);}else s.security&&(d.security=s.security);t[n.path][p]=d;}return {openapi:"3.0.0",info:{title:s.title,description:s.description,version:s.version,...s.info},servers:s.servers?.map(n=>({url:n}))||[{url:"/"}],paths:t,components:o,security:s.security||[],tags:s.tags?Object.entries(s.tags).map(([n,i])=>({name:n,...i})):[]}}function Qr(s,e){return `
85
85
  <!DOCTYPE html>
86
86
  <html lang="en">
87
87
  <head>
88
88
  <meta charset="utf-8" />
89
89
  <meta name="viewport" content="width=device-width, initial-scale=1" />
90
- <meta name="description" content="${Z(e.description)}" />
91
- <title>${Z(e.title)}</title>
90
+ <meta name="description" content="${W(e.description)}" />
91
+ <title>${W(e.title)}</title>
92
92
  <link rel="stylesheet" type="text/css" href="https://unpkg.com/swagger-ui-dist@5.9.0/swagger-ui.css" />
93
93
  <style>
94
94
  html {
@@ -129,14 +129,14 @@ ${u}\r
129
129
  };
130
130
  </script>
131
131
  </body>
132
- </html>`}function kr(s,e){return `
132
+ </html>`}function Ir(s,e){return `
133
133
  <!DOCTYPE html>
134
134
  <html>
135
135
  <head>
136
- <title>${Z(e.title)}</title>
136
+ <title>${W(e.title)}</title>
137
137
  <meta charset="utf-8"/>
138
138
  <meta name="viewport" content="width=device-width, initial-scale=1">
139
- <meta name="description" content="${Z(e.description)}" />
139
+ <meta name="description" content="${W(e.description)}" />
140
140
  <link rel="icon" type="image/png" href="https://mrin9.github.io/RapiDoc/images/favicon.png">
141
141
  <style>
142
142
  body { margin: 0; padding: 0; }
@@ -160,14 +160,14 @@ ${u}\r
160
160
  <script type="module" src="https://unpkg.com/rapidoc/dist/rapidoc-min.js"></script>
161
161
  </body>
162
162
  </html>
163
- `}function qr(s,e){return `
163
+ `}function Ur(s,e){return `
164
164
  <!DOCTYPE html>
165
165
  <html lang="en">
166
166
  <head>
167
167
  <meta charset="utf-8" />
168
168
  <meta name="viewport" content="width=device-width, initial-scale=1" />
169
- <meta name="description" content="${Z(e.description)}" />
170
- <title>${Z(e.title)}</title>
169
+ <meta name="description" content="${W(e.description)}" />
170
+ <title>${W(e.title)}</title>
171
171
  <style>
172
172
  body {
173
173
  margin: 0;
@@ -184,14 +184,14 @@ ${u}\r
184
184
  <script src="https://unpkg.com/@scalar/api-reference@latest/dist/browser/standalone.js"></script>
185
185
  </body>
186
186
  </html>
187
- `}function jr(s,e){return `
187
+ `}function Gr(s,e){return `
188
188
  <!DOCTYPE html>
189
189
  <html lang="en">
190
190
  <head>
191
191
  <meta charset="utf-8" />
192
192
  <meta name="viewport" content="width=device-width, initial-scale=1" />
193
- <meta name="description" content="${Z(e.description)}" />
194
- <title>${Z(e.title)}</title>
193
+ <meta name="description" content="${W(e.description)}" />
194
+ <title>${W(e.title)}</title>
195
195
  <link rel="stylesheet" href="https://unpkg.com/@stoplight/elements@7.7.9/styles.min.css">
196
196
  <style>
197
197
  body {
@@ -211,6 +211,6 @@ ${u}\r
211
211
  <script src="https://unpkg.com/@stoplight/elements@7.7.9/web-components.min.js"></script>
212
212
  </body>
213
213
  </html>
214
- `}function Ut(s,e){let t=[],r=/:([a-zA-Z0-9_]+)/g,o;for(;(o=r.exec(s))!==null;){let n=o[1],i={type:"string"};e&&e.shape&&e.shape[n]&&(i=V(e.shape[n])||{type:"string"}),t.push({name:n,in:"path",required:true,schema:i});}return t}var qe=class{port;hostname;host;routes;tapOptions;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.hostname=e?.host??"0.0.0.0",this.host=e?.host??"0.0.0.0",this.url=`http://${this.host}:${this.port}`,this.tapOptions=e?.tapOptions;}listen(){let e=this.tapOptions?.bun,{fetch:t,...r}=e??{};this.runtimeServer=Bun.serve({port:this.port,hostname:this.hostname,fetch:async(o,n)=>{let i=new URL(o.url),p=w.find(o.method,i.pathname);_.enrichRequest(o),o.params=p?.params??{},o.query=Object.fromEntries(i.searchParams.entries()),o.ip=o.headers.get("x-forwarded-for")?.split(",")[0]??n.requestIP(o)?.address,await t?.call(this,o,n);let d=await G(p?.middleware??[],p?.handler??((c,u)=>{u.notFound({...R(new M(c.url,c.method))});}),o);return d.headers["Content-Type"]==="application/json"?Response.json(d.getBody(),{status:d.responseStatus,headers:d.headers}):new Response(d.getBody(),{status:d.responseStatus,headers:d.headers})},...r}),this.url=this.runtimeServer.url.toString();}async close(){if(!this.runtimeServer)throw new Error("Server is not listening or not initialized");await this.runtimeServer.stop();}};var je=class{constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.hostname=e?.host??"0.0.0.0",this.host=e?.host??"0.0.0.0",this.url=`http://${this.host}:${this.port}`,this.tapOptions=e?.tapOptions;}listen(){let e=this.tapOptions?.deno,{handler:t,...r}=e??{};this.runtimeServer=Deno.serve({port:this.port,hostname:this.hostname,handler:async(o,n)=>{let i=new URL(o.url),p=w.find(o.method,i.pathname);if(_.enrichRequest(o),o.params=p?.params??{},o.query=Object.fromEntries(i.searchParams.entries()),o.ip=o.headers.get("x-forwarded-for")?.split(",")[0]??n.remoteAddr?.hostname,await t?.(o,n))return new Response(null,{status:426});let a=await G(p?.middleware??[],p?.handler??((u,f)=>{f.notFound({...R(new M(u.url,u.method))});}),o);return a.headers["Content-Type"]==="application/json"?Response.json(a.getBody(),{status:a.responseStatus,headers:a.headers}):new Response(a.getBody(),{status:a.responseStatus,headers:a.headers})},...r}),this.url=`http://${this.host}:${this.port}`;}async close(){if(!this.runtimeServer)throw new Error("Server is not listening or not initialized");await this.runtimeServer.shutdown();}};async function Br(s,e){let t=s.getReader();try{for(;;){let{done:r,value:o}=await t.read();if(r){e.end();break}e.write(o);}}catch(r){e.destroy(r);}}var Fe=class{port;host;url;routes;tapOptions;runtimeServer;nodeHttpClient;httpsOptions;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.host=e?.host??"0.0.0.0",this.tapOptions=e?.tapOptions,this.nodeHttpClient=e?.nodeHttpClient??"http",this.httpsOptions=e?.nodeHttpClient==="https"||e?.nodeHttpClient==="http2-secure"?e?.httpsOptions:void 0;let t=this.nodeHttpClient==="https"||this.nodeHttpClient==="http2-secure"?"https":"http";this.url=`${t}://${this.host}:${this.port}`,this.runtimeServer=this.createServer(async(r,o)=>{if(this.tapOptions&&this.tapOptions.node){let m=this.tapOptions.node;await m?.(r);}let n=w.find(r.method,r.url),i={};for(let m of Object.keys(r.headers)){if(m.startsWith(":"))continue;let v=r.headers[m];v!==void 0&&(i[m]=Array.isArray(v)?v.join(", "):v);}let p=new _(`${this.url}${r.url}`,{method:r.method,body:K(r.method)?await this.readRequestBody(r):void 0,headers:i}),d=r.headers["x-forwarded-for"];Array.isArray(d)&&(d=d[0]),p.ip=d??r.socket.remoteAddress;let[a,c=""]=r.url?.split("?",2)??[];p.query=Object.fromEntries(new URLSearchParams(c)),p.params=n?.params??{};let u=new B;u.nodeResponse=o;let f=await G(n?.middleware??[],n?.handler??((m,v)=>{v.notFound({...R(new M(m.url,m.method))});}),p,u);if(o.headersSent||o.writableEnded)return;let l=f.getBody();if(l instanceof ReadableStream){Br(l,o);return}l instanceof Buffer||l instanceof Uint8Array||typeof l=="string"?l=l:f.headers["Content-Type"]==="application/json"&&typeof l!="string"?l=JSON.stringify(l):l=String(l),o.writeHead(f.responseStatus,f.headers),o.end(l);});}listen(){this.runtimeServer.listen(this.port,this.host);}async close(){return new Promise((e,t)=>{this.runtimeServer.close(r=>{r&&"code"in r&&r.code!=="ERR_SERVER_NOT_RUNNING"?t(r):e();});})}async readRequestBody(e){return new Promise((t,r)=>{let o=[];e.on("data",n=>o.push(Buffer.from(n))),e.on("error",r),e.on("end",()=>t(Buffer.concat(o).toString()));})}createServer(e){if(this.nodeHttpClient==="http")return http.createServer(e);if(this.nodeHttpClient==="http2")return http2.createServer(e);if(this.nodeHttpClient==="http2-secure"){if(!this.httpsOptions)throw new Error("httpsOptions (key, cert) are required when using http2-secure client");return http2.createSecureServer(this.httpsOptions,e)}if(!this.httpsOptions)throw new Error("httpsOptions (key, cert) are required when using https client");return https.createServer(this.httpsOptions,e)}};var _e=class{server;constructor(e){this.server=this.getRuntimeServer(e),this.routes=this.server.routes;}get url(){return this.server.url}get port(){return this.server.port}get host(){return this.server.host}getServer(e){return this.server.runtimeServer}listen(){return this.server.listen()}async close(){return this.server.close()}getRuntimeServer(e){if(e?.runtime==="bun")return new qe(e);if(e?.runtime==="node")return new Fe(e);if(e?.runtime==="deno")return new je(e);throw new Error("No server implementation found for runtime: "+e?.runtime)}};var Qt=["isListening","url","port","host","routes","embed","constructor","get","post","put","patch","delete","getNodeServer","getBunServer","getDenoServer","use","setErrorHandler","listen","close","tapOptions","startUpOptions","tmpDir","logger","getMockServer","useExpress","expressMiddleware","mountExpressRouter","setNotFoundHandler","setGlobalCronErrorHandler","startRegisteredCrons","bootstrap","handleNotFound","registerNotFoundRoutes","importControllers","applyPlugins"];var Ur=1024,Ir=6,Qr=[/text\/.+/,/application\/json/,/application\/javascript/,/application\/xml/,/application\/.*\+json/,/application\/.*\+xml/],zt=s=>{let e=s?.threshold??Ur,t=Math.max(0,Math.min(9,s?.level??Ir)),r=s?.filter??Qr;return async(o,n,i)=>{if(!(o.headers.get("accept-encoding")||"").includes("gzip"))return i();let a=n.send.bind(n),c=n.json.bind(n),u=n.text.bind(n),f=(l,m)=>{if(!zr(l,m,e,r))return l;let v=Gt(l);if(!v||v.length<e)return l;let P=zlib.gzipSync(v,{level:t});return n.setHeader("Content-Encoding","gzip"),n.setHeader("Content-Length",P.length.toString()),P};n.send=function(l){let m=n.headers["content-type"],v=f(l,m);return a(v)},n.json=function(l){let m=JSON.stringify(l),v=f(m,"application/json");return v!==m?(n.setHeader("Content-Type","application/json"),a(v)):c(l)},n.text=function(l){let m=f(l,"text/plain");return m!==l?(n.setHeader("Content-Type","text/plain"),a(m)):u(l)},await i();}},zr=(s,e,t,r)=>{if(!s||!e)return false;let o=Gt(s);return !o||o.length<t?false:r.some(n=>n.test(e))},Gt=s=>typeof s=="string"?Buffer.from(s,"utf-8"):Buffer.isBuffer(s)?s:s instanceof Uint8Array?Buffer.from(s):typeof s=="object"?Buffer.from(JSON.stringify(s),"utf-8"):null;var Gr=["POST"],Kr="X-HTTP-Method-Override",Vr=["GET","POST","PUT","PATCH","DELETE"],Kt=s=>{let e=(s?.methods??Gr).map(r=>r.toUpperCase()),t=s?.header??Kr;return async(r,o,n)=>{let i=r.method.toUpperCase();if(!e.includes(i))return n();let p=r.headers.get(t);if(!p)return n();let d=p.toUpperCase();if(!Vr.includes(d))return n();r.method=d,await n();}};var Vt=class{isListening;isProduction;router=w;wasInitialized;serverConnector;globalMiddlewares=[];serverOptions;controllerImportBlacklistedPaths=["node_modules"];notFoundHandler;nativeEnv=new fe;httpsOptions;constructor(e){this.wasInitialized=false,this.serverOptions={nodeHttpClient:e?.nodeHttpClient??"http",port:e?.port??Number(this.nativeEnv.get("PORT"))??80,host:e?.host??this.nativeEnv.get("HOST")??"0.0.0.0",controllerPatterns:e?.controllerPatterns??[],plugins:e?.plugins??{},tapOptions:e?.tapOptions??{},swagger:e?.swagger??true,useBodyParser:e?.useBodyParser??true},this.httpsOptions=e?.nodeHttpClient==="https"||e?.nodeHttpClient==="http2-secure"?e.httpsOptions:void 0,this.serverConnector=new _e({routes:[],port:this.serverOptions.port,host:this.serverOptions.host,tapOptions:this.serverOptions.tapOptions,runtime:g.type,nodeHttpClient:this.serverOptions.nodeHttpClient,httpsOptions:this.httpsOptions}),this.serverOptions.useBodyParser&&this.use(Ht()),this.isListening=false,this.isProduction=this.nativeEnv.get("NODE_ENV")==="production";}get url(){return this.serverConnector.url}get port(){return this.serverConnector.port}get host(){return this.serverConnector.host}get routes(){return w.getRoutes()||[]}async hash(e){return $e.hash(e)}async compareHash(e,t){return $e.compare(e,t)}getEnvironment(){return this.nativeEnv.getEnvironment()}tmpDir(...e){return y.join("tmp",...e)}async mkdir(e,t){await S.mkdir(e,t);}get(e,t,r){let{middlewares:o,handler:n,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);w.addOrUpdate("GET",e,o,n,i);}post(e,t,r){let{middlewares:o,handler:n,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);w.addOrUpdate("POST",e,o,n,i);}patch(e,t,r){let{middlewares:o,handler:n,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);w.addOrUpdate("PATCH",e,o,n,i);}put(e,t,r){let{middlewares:o,handler:n,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);w.addOrUpdate("PUT",e,o,n,i);}delete(e,t,r){let{middlewares:o,handler:n,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);w.addOrUpdate("DELETE",e,o,n,i);}options(e,t,r){let{middlewares:o,handler:n,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);w.addOrUpdate("OPTIONS",e,o,n,i);}head(e,t,r){let{middlewares:o,handler:n,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);w.addOrUpdate("HEAD",e,o,n,i);}group(e,t,r){this.router.group(e,t,r);}getNodeServer(){if(g.type!=="node")throw new Error("Server is not using node runtime, you can't call `.getNodeServer()`");return this.serverConnector.getServer("node")}getBunServer(){if(g.type!=="bun")throw new Error("Server is not using bun runtime, you can't call `.getBunServer()`");return this.serverConnector.getServer("bun")}getDenoServer(){if(g.type!=="deno")throw new Error("Server is not using deno runtime, you can't call `.getDenoServer()`");return this.serverConnector.getServer("deno")}embed(e,t){if(typeof e!="string"||e.trim()==="")throw new Error(`Invalid key provided to embed: ${e}. Key must be a non-empty string.`);if(Qt.includes(e))throw new Error(`Cannot embed value with key '${e}' as it conflicts with a protected server property.`);Object.defineProperty(this,e,{value:t,writable:false,configurable:true,enumerable:true});}exit(e=0){switch(g.type){case "bun":case "node":process.exit(e);case "deno":Deno.exit(e);default:throw new Error(`Unsupported runtime: ${g.type}`)}}on(e,t){switch(g.type){case "bun":case "node":process.on(e,t);break;case "deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${g.type}, only node, bun and deno are supported`)}}once(e,t){switch(g.type){case "bun":case "node":process.once(e,t);break;case "deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${g.type}, only node, bun and deno are supported`)}}use(...e){this.globalMiddlewares.push(...e);}useExpress(e,t){xt(this).use(e,t);}expressMiddleware(e){return ye(e)}mountExpressRouter(e,t){Me(e,t);}setErrorHandler(e){this.globalMiddlewares.unshift(async(t,r,o)=>{try{await o();}catch(n){await e?.(t,r,o,n);}});}setNotFoundHandler(e){this.notFoundHandler=e;}setGlobalCronErrorHandler(e){j.globalErrorHandler=e;}startRegisteredCrons=async(e,t)=>{e?.length&&await j.massiveImportCronJobs(e),j.run().then(()=>{t?.();});};startRegisteredQueues=async(e,t)=>{e?.length&&await re.massiveImportQueues(e),re.run().then(()=>{t?.();});};listen(e){if(this.isListening)throw new Error("Server is already listening, you can't call `.listen()` multiple times");this.bootstrap().then(()=>{this.serverConnector.listen(),this.isListening=true,this.serverOptions.swagger&&It(this.serverOptions.swagger),e?.({port:this.port,host:this.host,url:this.url});});}async close(){await this.serverConnector.close(),this.isListening=false;}async getMockServer(e){return await this.bootstrap(e),new Ee(this)}async importControllers(e){let t=e??this.serverOptions.controllerPatterns,r=await Promise.all(t.map(async o=>glob.glob(o,{absolute:true,cwd:$.getCwd()}))).then(o=>o.flat());r=r.flat(),r=r.filter(o=>!this.controllerImportBlacklistedPaths.some(n=>o.includes(n))),exports.logger.debug(`Found ${r.length} controllers to import`),await Promise.all(r.map(async o=>{exports.logger.debug(`Importing controller ${o}`),await import(o).catch(n=>{exports.logger.error(`Error importing controller ${o}: ${n}`);});}));}extractOptionsAndHandlerFromRouteRegistration(e,t){if(typeof e=="function")return {middlewares:[],handler:e,swaggerOptions:void 0};let r=e;return {middlewares:Array.isArray(r.middlewares)?r.middlewares:r.middlewares?[r.middlewares]:[],handler:t,swaggerOptions:r.swagger}}applyPlugins(e){Object.entries(e).forEach(([t,r])=>{switch(t){case "cors":this.use($t(r));break;case "json":this.use(Lt(r));break;case "static":this.use(gt(r));break;case "fileParser":this.use(Nt(r));break;case "helmet":this.use(Dt(r));break;case "cookie":this.use(yt(r));break;case "methodOverride":this.use(Kt(r));break;case "compression":this.use(zt(r));break;case "log":this.use(Ot(r));break;case "rateLimiter":let{keyOptions:o,storageOptions:n}=r;this.use(Tt(o,n));break;case "urlencoded":this.use(At(r));break;case "trustProxy":this.use(Et(r));break;case "timeout":this.use(Ct(r));break;case "session":this.use(Pt(r));break;default:exports.logger.warn(`Unknown plugin ${t}`);break}});}async bootstrap(e){this.wasInitialized||(await this.importControllers(e?.controllerPatterns),this.applyPlugins(this.serverOptions.plugins),this.registerNotFoundRoutes(),this.globalMiddlewares.length&&w.applyGlobalMiddlewaresToAllRoutes(this.globalMiddlewares),this.wasInitialized=true);}handleNotFound=(e,t)=>{if(this.notFoundHandler){this.notFoundHandler(e,t);return}let r=new URL(e.url).pathname,o=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"],n=[];for(let p of o){if(p===e.method.toUpperCase())continue;let d=w.find(p,r);d&&d.handler!==this.handleNotFound&&n.push(p);}if(n.length){t.setHeader("Allow",n.join(", "));let p=new he(r,e.method);t.methodNotAllowed({...R(p)});return}let i=new M(r,e.method);t.notFound({...R(i)});};registerNotFoundRoutes(){let e=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];for(let t of e)w.addOrUpdate(t,"*",[],this.handleNotFound,{excludeFromSwagger:true});}};var Zt=class{};var Jt=s=>(e,t)=>(r,o,n)=>{let i={scope:e,handler:t,manager:s};if(typeof o>"u"){let d=h.get(r.prototype,"__class__");return d||(d={policies:[]}),d.policies||(d.policies=[]),d.policies.push(i),h.set(r.prototype,"__class__",d),r}let p=h.get(r,o);return p||(p={policies:[]}),p.policies||(p.policies=[]),p.policies.push(i),h.set(r,o,p),n};var Wt=class{providers;constructor(e){this.providers=e;}createDecorator(){return Jt(this)}canAccess(e,t,...r){let o=this.providers[e];if(!o)throw new O(`Policy provider for ${String(e)} not found`);return o[t](...r)}};var pd=w;
215
- exports.ARG_SYMBOL=Rs;exports.BasePlugin=Zt;exports.BullMQPubSub=xe;exports.Command=E;exports.CommandRegistry=We;exports.CronService=j;exports.PGBossPubSub=Re;exports.PolicyManager=Wt;exports.QueueManager=Q;exports.QueueService=re;exports.Request=_;exports.Response=B;exports.SQSPubSub=Oe;exports.Server=Vt;exports.VALIDATION_ERROR_SYMBOL=W;exports.arg=L;exports.commandRegistry=mt;exports.compression=zt;exports.controller=Fs;exports.cookie=yt;exports.cors=$t;exports.createExpressAdapter=xt;exports.createPolicyDecorator=Jt;exports.cron=us;exports.defineLoggerConfig=Xr;exports.defineQueueConfiguration=Ko;exports.del=Ds;exports.expressHandler=wr;exports.expressMiddleware=ye;exports.fileParser=Nt;exports.flag=T;exports.get=Us;exports.getContentType=Xe;exports.hash=$e;exports.helmet=Dt;exports.json=Lt;exports.log=Ot;exports.methodOverride=Kt;exports.middleware=eo;exports.mountExpressRouter=Me;exports.patch=zs;exports.post=Vs;exports.publish=Lo;exports.put=Ws;exports.queue=ue;exports.rateLimiter=Tt;exports.router=pd;exports.serialize=io;exports.serveStatic=gt;exports.session=Pt;exports.setCronGlobalErrorHandler=ps;exports.timeout=Ct;exports.trustProxy=Et;exports.urlencoded=At;exports.validate=uo;//# sourceMappingURL=index.cjs.map
214
+ `}function Kt(s,e){let t=[],r=/:([a-zA-Z0-9_]+)/g,o;for(;(o=r.exec(s))!==null;){let n=o[1],i={type:"string"};e&&e.shape&&e.shape[n]&&(i=Z(e.shape[n])||{type:"string"}),t.push({name:n,in:"path",required:true,schema:i});}return t}var Le=class{port;hostname;host;routes;tapOptions;graphql;ensureGraphQLHandler;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.hostname=e?.host??"0.0.0.0",this.host=e?.host??"0.0.0.0",this.url=`http://${this.host}:${this.port}`,this.tapOptions=e?.tapOptions,this.graphql=e?.graphql??new _,this.ensureGraphQLHandler=ve(this.graphql);}listen(){let e=this.tapOptions?.bun,{fetch:t,...r}=e??{};this.runtimeServer=Bun.serve({port:this.port,hostname:this.hostname,fetch:async(o,n)=>{let i=new URL(o.url),p=w.find(o.method,i.pathname);if(F.enrichRequest(o),o.params=p?.params??{},o.query=Object.fromEntries(i.searchParams.entries()),o.ip=o.headers.get("x-forwarded-for")?.split(",")[0]??n.requestIP(o)?.address,await t?.call(this,o,n),this.graphql.isEnabled&&i.pathname.startsWith(this.graphql.getYogaOptions().graphqlEndpoint??"/graphql")){let c=await this.ensureGraphQLHandler();if(c)return c.fetch(o,{server:n})}let d=await K(p?.middleware??[],p?.handler??((c,u)=>{u.notFound({...x(new M(c.url,c.method))});}),o);return d.headers["Content-Type"]==="application/json"?Response.json(d.getBody(),{status:d.responseStatus,headers:d.headers}):new Response(d.getBody(),{status:d.responseStatus,headers:d.headers})},...r}),this.url=this.runtimeServer.url.toString();}async close(){if(!this.runtimeServer)throw new Error("Server is not listening or not initialized");await this.runtimeServer.stop();}};var Fe=class{graphql;ensureGraphQLHandler;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.hostname=e?.host??"0.0.0.0",this.host=e?.host??"0.0.0.0",this.url=`http://${this.host}:${this.port}`,this.tapOptions=e?.tapOptions,this.graphql=e?.graphql??new _,this.ensureGraphQLHandler=ve(this.graphql);}listen(){let e=this.tapOptions?.deno,{handler:t,...r}=e??{};this.runtimeServer=Deno.serve({port:this.port,hostname:this.hostname,handler:async(o,n)=>{let i=new URL(o.url),p=w.find(o.method,i.pathname);if(F.enrichRequest(o),o.params=p?.params??{},o.query=Object.fromEntries(i.searchParams.entries()),o.ip=o.headers.get("x-forwarded-for")?.split(",")[0]??n.remoteAddr?.hostname,await t?.(o,n))return new Response(null,{status:426});if(this.graphql.isEnabled&&i.pathname.startsWith(this.graphql.getYogaOptions().graphqlEndpoint??"/graphql")){let u=await this.ensureGraphQLHandler();if(u)return u.fetch(o,{info:n})}let a=await K(p?.middleware??[],p?.handler??((u,h)=>{h.notFound({...x(new M(u.url,u.method))});}),o);return a.headers["Content-Type"]==="application/json"?Response.json(a.getBody(),{status:a.responseStatus,headers:a.headers}):new Response(a.getBody(),{status:a.responseStatus,headers:a.headers})},...r}),this.url=`http://${this.host}:${this.port}`;}async close(){if(!this.runtimeServer)throw new Error("Server is not listening or not initialized");await this.runtimeServer.shutdown();}};async function Wr(s,e){let t=s.getReader();try{for(;;){let{done:r,value:o}=await t.read();if(r){e.end();break}e.write(o);}}catch(r){e.destroy(r);}}var _e=class{port;host;url;routes;tapOptions;runtimeServer;nodeHttpClient;httpsOptions;graphql;ensureGraphQLHandler;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.host=e?.host??"0.0.0.0",this.tapOptions=e?.tapOptions,this.nodeHttpClient=e?.nodeHttpClient??"http",this.httpsOptions=e?.nodeHttpClient==="https"||e?.nodeHttpClient==="http2-secure"?e?.httpsOptions:void 0,this.graphql=e?.graphql??new _,this.ensureGraphQLHandler=ve(this.graphql);let t=this.nodeHttpClient==="https"||this.nodeHttpClient==="http2-secure"?"https":"http";this.url=`${t}://${this.host}:${this.port}`,this.runtimeServer=this.createServer(async(r,o)=>{if(this.tapOptions&&this.tapOptions.node){let m=this.tapOptions.node;await m?.(r);}if(this.graphql.isEnabled&&r.url?.startsWith(this.graphql.getYogaOptions().graphqlEndpoint??"/graphql")){let m=await this.ensureGraphQLHandler();if(m){m(r,o);return}}let n=w.find(r.method,r.url),i={};for(let m of Object.keys(r.headers)){if(m.startsWith(":"))continue;let v=r.headers[m];v!==void 0&&(i[m]=Array.isArray(v)?v.join(", "):v);}let p=new F(`${this.url}${r.url}`,{method:r.method,body:V(r.method)?await this.readRequestBody(r):void 0,headers:i}),d=r.headers["x-forwarded-for"];Array.isArray(d)&&(d=d[0]),p.ip=d??r.socket.remoteAddress;let[a,c=""]=r.url?.split("?",2)??[];p.query=Object.fromEntries(new URLSearchParams(c)),p.params=n?.params??{};let u=new B;u.nodeResponse=o;let h=await K(n?.middleware??[],n?.handler??((m,v)=>{v.notFound({...x(new M(m.url,m.method))});}),p,u);if(o.headersSent||o.writableEnded)return;let l=h.getBody();if(l instanceof ReadableStream){Wr(l,o);return}l instanceof Buffer||l instanceof Uint8Array||typeof l=="string"?l=l:h.headers["Content-Type"]==="application/json"&&typeof l!="string"?l=JSON.stringify(l):l=String(l),o.writeHead(h.responseStatus,h.headers),o.end(l);});}listen(){this.runtimeServer.listen(this.port,this.host);}async close(){return new Promise((e,t)=>{this.runtimeServer.close(r=>{r&&"code"in r&&r.code!=="ERR_SERVER_NOT_RUNNING"?t(r):e();});})}async readRequestBody(e){return new Promise((t,r)=>{let o=[];e.on("data",n=>o.push(Buffer.from(n))),e.on("error",r),e.on("end",()=>t(Buffer.concat(o).toString()));})}createServer(e){if(this.nodeHttpClient==="http")return http.createServer(e);if(this.nodeHttpClient==="http2")return http2.createServer(e);if(this.nodeHttpClient==="http2-secure"){if(!this.httpsOptions)throw new Error("httpsOptions (key, cert) are required when using http2-secure client");return http2.createSecureServer(this.httpsOptions,e)}if(!this.httpsOptions)throw new Error("httpsOptions (key, cert) are required when using https client");return https.createServer(this.httpsOptions,e)}};var Ne=class{routes;server;constructor(e){this.server=this.getRuntimeServer(e),this.routes=this.server.routes;}get url(){return this.server.url}get port(){return this.server.port}get host(){return this.server.host}getServer(e){return this.server.runtimeServer}listen(){return this.server.listen()}async close(){return this.server.close()}getRuntimeServer(e){if(e?.runtime==="bun")return new Le(e);if(e?.runtime==="node")return new _e(e);if(e?.runtime==="deno")return new Fe(e);throw new Error("No server implementation found for runtime: "+e?.runtime)}};var Zt=["isListening","url","port","host","routes","embed","constructor","get","post","put","patch","delete","getNodeServer","getBunServer","getDenoServer","use","setErrorHandler","listen","close","tapOptions","startUpOptions","tmpDir","logger","getMockServer","useExpress","expressMiddleware","mountExpressRouter","setNotFoundHandler","setGlobalCronErrorHandler","startRegisteredCrons","bootstrap","handleNotFound","registerNotFoundRoutes","importControllers","applyPlugins"];var Wt=class{isListening;isProduction;graphql;router=w;wasInitialized;serverConnector;globalMiddlewares=[];serverOptions;controllerImportBlacklistedPaths=["node_modules"];notFoundHandler;nativeEnv=new fe;httpsOptions;constructor(e){this.wasInitialized=false,this.serverOptions={nodeHttpClient:e?.nodeHttpClient??"http",port:e?.port??Number(this.nativeEnv.get("PORT"))??80,host:e?.host??this.nativeEnv.get("HOST")??"0.0.0.0",controllerPatterns:e?.controllerPatterns??[],plugins:e?.plugins??{},tapOptions:e?.tapOptions??{},swagger:e?.swagger??true,useBodyParser:e?.useBodyParser??true,graphql:e?.graphql??void 0},this.httpsOptions=e?.nodeHttpClient==="https"||e?.nodeHttpClient==="http2-secure"?e.httpsOptions:void 0,this.isListening=false,this.isProduction=this.nativeEnv.get("NODE_ENV")==="production",this.graphql=new _(this.serverOptions.graphql),this.serverConnector=new Ne({routes:[],port:this.serverOptions.port,host:this.serverOptions.host,tapOptions:this.serverOptions.tapOptions,runtime:g.type,nodeHttpClient:this.serverOptions.nodeHttpClient,httpsOptions:this.httpsOptions,graphql:this.graphql}),this.serverOptions.useBodyParser&&this.use(Lt());}get url(){return this.serverConnector.url}get port(){return this.serverConnector.port}get host(){return this.serverConnector.host}get routes(){return w.getRoutes()||[]}async hash(e){return $e.hash(e)}async compareHash(e,t){return $e.compare(e,t)}getEnvironment(){return this.nativeEnv.getEnvironment()}tmpDir(...e){return y.join("tmp",...e)}async mkdir(e,t){await S.mkdir(e,t);}get(e,t,r){let{middlewares:o,handler:n,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);w.addOrUpdate("GET",e,o,n,i);}post(e,t,r){let{middlewares:o,handler:n,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);w.addOrUpdate("POST",e,o,n,i);}patch(e,t,r){let{middlewares:o,handler:n,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);w.addOrUpdate("PATCH",e,o,n,i);}put(e,t,r){let{middlewares:o,handler:n,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);w.addOrUpdate("PUT",e,o,n,i);}delete(e,t,r){let{middlewares:o,handler:n,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);w.addOrUpdate("DELETE",e,o,n,i);}options(e,t,r){let{middlewares:o,handler:n,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);w.addOrUpdate("OPTIONS",e,o,n,i);}head(e,t,r){let{middlewares:o,handler:n,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);w.addOrUpdate("HEAD",e,o,n,i);}group(e,t,r){this.router.group(e,t,r);}getNodeServer(){if(g.type!=="node")throw new Error("Server is not using node runtime, you can't call `.getNodeServer()`");return this.serverConnector.getServer("node")}getBunServer(){if(g.type!=="bun")throw new Error("Server is not using bun runtime, you can't call `.getBunServer()`");return this.serverConnector.getServer("bun")}getDenoServer(){if(g.type!=="deno")throw new Error("Server is not using deno runtime, you can't call `.getDenoServer()`");return this.serverConnector.getServer("deno")}embed(e,t){if(typeof e!="string"||e.trim()==="")throw new Error(`Invalid key provided to embed: ${e}. Key must be a non-empty string.`);if(Zt.includes(e))throw new Error(`Cannot embed value with key '${e}' as it conflicts with a protected server property.`);Object.defineProperty(this,e,{value:t,writable:false,configurable:true,enumerable:true});}exit(e=0){switch(g.type){case "bun":case "node":process.exit(e);case "deno":Deno.exit(e);default:throw new Error(`Unsupported runtime: ${g.type}`)}}on(e,t){switch(g.type){case "bun":case "node":process.on(e,t);break;case "deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${g.type}, only node, bun and deno are supported`)}}once(e,t){switch(g.type){case "bun":case "node":process.once(e,t);break;case "deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${g.type}, only node, bun and deno are supported`)}}use(...e){this.globalMiddlewares.push(...e);}useExpress(e,t){Pt(this).use(e,t);}expressMiddleware(e){return we(e)}mountExpressRouter(e,t){He(e,t);}setErrorHandler(e){this.globalMiddlewares.unshift(async(t,r,o)=>{try{await o();}catch(n){await e?.(t,r,o,n);}});}setNotFoundHandler(e){this.notFoundHandler=e;}setGlobalCronErrorHandler(e){j.globalErrorHandler=e;}startRegisteredCrons=async(e,t)=>{e?.length&&await j.massiveImportCronJobs(e),j.run().then(()=>{t?.();});};startRegisteredQueues=async(e,t)=>{e?.length&&await se.massiveImportQueues(e),se.run().then(()=>{t?.();});};listen(e){if(this.isListening)throw new Error("Server is already listening, you can't call `.listen()` multiple times");this.bootstrap().then(()=>{this.serverConnector.listen(),this.isListening=true,this.serverOptions.swagger&&Vt(this.serverOptions.swagger),e?.({port:this.port,host:this.host,url:this.url});});}async close(){await this.serverConnector.close(),this.isListening=false;}async getMockServer(e){return await this.bootstrap(e),new Ae(this)}async importControllers(e){let t=e??this.serverOptions.controllerPatterns,r=await Promise.all(t.map(async o=>glob.glob(o,{absolute:true,cwd:q.getCwd()}))).then(o=>o.flat());r=r.flat(),r=r.filter(o=>!this.controllerImportBlacklistedPaths.some(n=>o.includes(n))),exports.logger.debug(`Found ${r.length} controllers to import`),await Promise.all(r.map(async o=>{exports.logger.debug(`Importing controller ${o}`),await import(o).catch(n=>{exports.logger.error(`Error importing controller ${o}: ${n}`);});}));}extractOptionsAndHandlerFromRouteRegistration(e,t){if(typeof e=="function")return {middlewares:[],handler:e,swaggerOptions:void 0};let r=e;return {middlewares:Array.isArray(r.middlewares)?r.middlewares:r.middlewares?[r.middlewares]:[],handler:t,swaggerOptions:r.swagger}}applyPlugins(e){Object.entries(e).forEach(([t,r])=>{switch(t){case "cors":this.use(Ft(r));break;case "json":this.use(zt(r));break;case "static":this.use(vt(r));break;case "fileParser":this.use(It(r));break;case "helmet":this.use(Ut(r));break;case "cookie":this.use(bt(r));break;case "methodOverride":this.use(Mt(r));break;case "compression":this.use(wt(r));break;case "log":this.use(Et(r));break;case "rateLimiter":let{keyOptions:o,storageOptions:n}=r;this.use(At(o,n));break;case "urlencoded":this.use(jt(r));break;case "trustProxy":this.use(kt(r));break;case "timeout":this.use(qt(r));break;case "session":this.use(Ht(r));break;default:exports.logger.warn(`Unknown plugin ${t}`);break}});}async bootstrap(e){this.wasInitialized||(await this.importControllers(e?.controllerPatterns),this.applyPlugins(this.serverOptions.plugins),this.registerNotFoundRoutes(),this.globalMiddlewares.length&&w.applyGlobalMiddlewaresToAllRoutes(this.globalMiddlewares),this.wasInitialized=true);}handleNotFound=(e,t)=>{if(this.notFoundHandler){this.notFoundHandler(e,t);return}let r=new URL(e.url).pathname,o=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"],n=[];for(let p of o){if(p===e.method.toUpperCase())continue;let d=w.find(p,r);d&&d.handler!==this.handleNotFound&&n.push(p);}if(n.length){t.setHeader("Allow",n.join(", "));let p=new ge(r,e.method);t.methodNotAllowed({...x(p)});return}let i=new M(r,e.method);t.notFound({...x(i)});};registerNotFoundRoutes(){let e=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];for(let t of e)w.addOrUpdate(t,"*",[],this.handleNotFound,{excludeFromSwagger:true});}};var Jt=class{};var Yt=s=>(e,t)=>(r,o,n)=>{let i={scope:e,handler:t,manager:s};if(typeof o>"u"){let d=f.get(r.prototype,"__class__");return d||(d={policies:[]}),d.policies||(d.policies=[]),d.policies.push(i),f.set(r.prototype,"__class__",d),r}let p=f.get(r,o);return p||(p={policies:[]}),p.policies||(p.policies=[]),p.policies.push(i),f.set(r,o,p),n};var Xt=class{providers;constructor(e){this.providers=e;}createDecorator(){return Yt(this)}canAccess(e,t,...r){let o=this.providers[e];if(!o)throw new O(`Policy provider for ${String(e)} not found`);return o[t](...r)}};var fd=w;
215
+ exports.ARG_SYMBOL=Ts;exports.BasePlugin=Jt;exports.BullMQPubSub=Oe;exports.Command=E;exports.CommandRegistry=Xe;exports.CronService=j;exports.GraphQL=_;exports.PGBossPubSub=Te;exports.PolicyManager=Xt;exports.QueueManager=G;exports.QueueService=se;exports.Request=F;exports.Response=B;exports.SQSPubSub=Pe;exports.Server=Wt;exports.VALIDATION_ERROR_SYMBOL=Y;exports.arg=Q;exports.commandRegistry=ft;exports.compression=wt;exports.controller=_s;exports.cookie=bt;exports.cors=Ft;exports.createExpressAdapter=Pt;exports.createPolicyDecorator=Yt;exports.cron=ms;exports.defineLoggerConfig=ts;exports.defineQueueConfiguration=Zo;exports.del=Bs;exports.expressHandler=Pr;exports.expressMiddleware=we;exports.fileParser=It;exports.flag=T;exports.get=Us;exports.getContentType=tt;exports.hash=$e;exports.helmet=Ut;exports.json=zt;exports.log=Et;exports.methodOverride=Mt;exports.middleware=ro;exports.mountExpressRouter=He;exports.patch=Ks;exports.post=Ws;exports.publish=Io;exports.put=Xs;exports.queue=le;exports.rateLimiter=At;exports.router=fd;exports.serialize=po;exports.serveStatic=vt;exports.session=Ht;exports.setCronGlobalErrorHandler=cs;exports.timeout=qt;exports.trustProxy=kt;exports.urlencoded=jt;exports.validate=mo;//# sourceMappingURL=index.cjs.map
216
216
  //# sourceMappingURL=index.cjs.map