balda 0.0.9 → 0.0.10

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.js CHANGED
@@ -1,9 +1,9 @@
1
- import {glob}from'glob';import At from'pino';import We from'path';import {Ajv,ValidationError}from'ajv';import Ye from'fs';import {execSync}from'child_process';import*as Ut from'readline';import {AsyncLocalStorage}from'async_hooks';import {gzipSync}from'zlib';import {createServer}from'http';import {createServer as createServer$1,createSecureServer}from'http2';import {createServer as createServer$2}from'https';import {Readable}from'stream';var Mt=Object.defineProperty;var Nr=(i,e)=>()=>(i&&(e=i(i=0)),e);var Lr=(i,e)=>{for(var t in e)Mt(i,t,{get:e[t],enumerable:true});};var y=(i,e,t,r)=>{for(var s=void 0,o=i.length-1,n;o>=0;o--)(n=i[o])&&(s=(n(e,t,s))||s);return s&&Mt(e,t,s),s};var kt={};Lr(kt,{runtime:()=>R});var mt,R,Q=Nr(()=>{mt=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")}},R=new mt;});var T=class extends Error{constructor(e){super(e);}};var _r=()=>At({level:"info",formatters:{level:e=>({level:e})}}),v=_r(),zs=i=>{v=At(i);};Q();var ht=class{getCwd(){switch(R.type){case "node":case "bun":return process.cwd();case "deno":return Deno.cwd();default:throw new Error("Unsupported runtime")}}},$=new ht;var xe=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 T("node-cron not installed as a dependency, it is required in order to run cron jobs with the @cron decorator")})).default;if(v.info("Scheduling cron jobs"),!this.scheduledJobs.length){v.info("No cron jobs to schedule");return}for(let{name:t,args:r}of this.scheduledJobs)v.info(`Scheduling cron job: ${t}`),e.schedule(...r).on("execution:failed",o=>this.globalErrorHandler(o));v.info("Cron jobs scheduled");}static globalErrorHandler(e){v.error(e.execution?.error);}static async massiveImportCronJobs(e){let t=[];for(let r of e){let s=await glob(r,{absolute:true,cwd:$.getCwd()});t.push(...s);}await Promise.all(t.map(async r=>{await import(r).catch(s=>{v.error(`Error importing cron job: ${r}`),v.error(s);});}));}},Xs=i=>{xe.globalErrorHandler=i.bind(xe);};var ro=(i,e)=>function(t,r,s){let o=s.value,n=async(...a)=>{let c=new t.constructor;return await o.apply(c,a)};return xe.register(`${t.constructor.name}.${r}`,i,n,e),s};Q();var gt=class{getCliArgs(){switch(R.type){case "bun":return this.getBunArgs();case "node":return this.getNodeArgs();case "deno":return Deno.args;default:throw new Error("Unsupported runtime")}}getCliCaller(){switch(R.type){case "bun":return "bun";case "node":return process.argv[0];case "deno":return "deno";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],s=r.split("/").pop()||r;if(!r.startsWith("-")){if(s==="yarn"&&t+1<e.length&&e[t+1]==="run"||s==="npx"&&t+1<e.length)return t+1;if(s==="yarn"||s==="pnpm")return t;if(s==="npm"&&t+1<e.length&&e[t+1]==="run"||s==="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(s)){for(let o=t+1;o<e.length;o++)if(!e[o].startsWith("-")&&/\.(js|ts|mjs|cjs)$/.test(e[o]))return o;return t}}}for(let t=e.length-1;t>=0;t--)if(!e[t].startsWith("-"))return t;return 1}},ft=new gt;var Ue=i=>i.toLowerCase().replace(/[-_.]/g,"_").replace(/([A-Z])/g,"_$1").replace(/^_+/,"").replace(/_+$/,"").toLowerCase(),ze=i=>i.split(/[-_.]/g).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),$t=i=>i.split(/[-_.]/g).map(e=>e.toLowerCase()).join("-");var Pe=(i,e)=>{if(!i||typeof i!="string")return e;let t=i.toLowerCase().trim(),r=t.match(/^(\d+(?:\.\d+)?)kb$/),s=t.match(/^(\d+(?:\.\d+)?)mb$/);if(r){let o=Number.parseFloat(r[1]);return Number.isNaN(o)||o<0?e:Math.floor(o*1024)}if(s){let o=Number.parseFloat(s[1]);return Number.isNaN(o)||o<0?e:Math.floor(o*1024*1024)}return e};var Ir=i=>{if(!i||i==="-"||i==="--")return null;let e=i.indexOf("=");if(e>0){let t=i.substring(0,e),r=i.substring(e+1);return {name:t,value:Ht(r)}}return {name:i,value:true}},Ht=i=>{if(i.toLowerCase()==="true")return true;if(i.toLowerCase()==="false")return false;let e=Number(i);return !Number.isNaN(e)&&Number.isFinite(e)?e:i},ce=()=>{let i=ft.getCliArgs(),e=[],t={};if(!i||!i.length)return {args:e,flags:t};for(let r=0;r<i.length;r++){let s=i[r];if(!(!s||typeof s!="string")){if(s.startsWith("-")){let o=Ir(s);if(o){if(o.value===true&&r+1<i.length){let n=i[r+1];n&&typeof n=="string"&&!n.startsWith("-")&&(o.value=Ht(n),r++);}if(o.name in t){let n=t[o.name];Array.isArray(n)?n.push(o.value):t[o.name]=[n,o.value];}else t[o.name]=o.value;}continue}e.push(s);}}return {args:e,flags:t}};var Ge=()=>ft.getCliArgs()[0]||null;var w=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 pe="VALIDATION_ERROR",go="ARG",Bt=ce().args.slice(1),A=i=>(e,t)=>{let r=Ge();if(!r||r!==e.commandName)return;let s=t;w.set(e,t,{type:"arg",name:s,description:i.description});let o=Bt.length?Bt.shift():i.defaultValue;if(i.required&&!o){let n=w.get(e,pe);w.set(e,pe,[...n||[],{type:"arg",name:s,message:"Required argument not provided"}]);return}i.parse&&o&&(o=i.parse(o)),Object.defineProperty(e,t,{value:o,enumerable:true,configurable:true,writable:true});};var J=i=>(e,t)=>{let r=Ge();if(!r||r!==e.commandName)return;let s=i.name||t,o=ce().flags,n=i.aliases||[],a=[s,...n],c=i.defaultValue;for(let p of a){let l=[p,`-${p}`,`--${p}`];for(let d of l)if(d in o){let h=o[d];i.type==="list"?c=(Array.isArray(h)?h:[h]).map(f=>{let b=String(f);return i.parse?i.parse(b):b}):(c=h,i.type==="boolean"?c=!!c:i.type==="number"&&(c=Number(c)),i.parse&&(c=i.parse(c)));break}if(c!==i.defaultValue)break}if(w.set(e,t,{type:"flag",name:s,aliases:n||[],description:i.description}),i.required&&(i.type==="list"?!c||Array.isArray(c)&&c.length===0:!c)){let l=w.get(e,pe);w.set(e,pe,[...l||[],{type:"flag",name:s,message:"Required flag not provided"}]);return}Object.defineProperty(e,t,{value:c,enumerable:true,configurable:true,writable:true});};J.boolean=i=>J({...i,type:"boolean"});J.string=i=>J({...i,type:"string"});J.number=i=>J({...i,type:"number"});J.list=i=>J({...i,type:"list"});var x=J;Q();var yt=class{basename(e){switch(R.type){case "node":case "bun":case "deno":return We.basename(e);default:throw new Error("Unsupported runtime")}}join(...e){switch(R.type){case "node":case "bun":case "deno":return We.join(...e);default:throw new Error("Unsupported runtime")}}extName(e){switch(R.type){case "bun":case "node":case "deno":return We.extname(e);default:throw new Error("Unsupported runtime")}}resolve(...e){switch(R.type){case "bun":case "node":case "deno":return We.resolve(...e);default:throw new Error("Unsupported runtime")}}},g=new yt;var Re=class{staticChildren;paramChild;wildcardChild;middleware;handler;constructor(){this.staticChildren=new Map,this.paramChild=null,this.wildcardChild=null,this.middleware=null,this.handler=null;}},vt=class i{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,s,o){e=e.toUpperCase();let n=this.trees.get(e);n||(n=new Re,this.trees.set(e,n));let c=t.split("?")[0].replace(/^\/+|\/+$/g,""),p=c.length===0?[]:c.split("/"),l=n;for(let h of p){if(h==="*"){l.wildcardChild||(l.wildcardChild=new Re),l=l.wildcardChild;break}if(h.startsWith(":")){let m=h.slice(1);l.paramChild||(l.paramChild={node:new Re,name:m}),l=l.paramChild.node;continue}l.staticChildren.has(h)||l.staticChildren.set(h,new Re),l=l.staticChildren.get(h);}l.middleware=r,l.handler=s;let d=this.routes.findIndex(h=>h.method===e&&h.path===t);if(d!==-1){this.routes[d].middleware=r,this.routes[d].handler=s;return}this.routes.push({method:e,path:t,middleware:r,handler:s,swaggerOptions:o});}find(e,t){e=e.toUpperCase();let r=this.trees.get(e);if(!r)return null;let o=t.split("?")[0].replace(/^\/+|\/+$/g,""),n=o.length===0?[]:o.split("/"),a={},c=r;for(let p=0;p<n.length;p++){let l=n[p];if(c.staticChildren.has(l)){c=c.staticChildren.get(l);continue}if(c.paramChild){a[c.paramChild.name]=l,c=c.paramChild.node;continue}if(c.wildcardChild){a["*"]=n.slice(p).join("/"),c=c.wildcardChild;break}return null}return !c.handler||!c.middleware?null:{middleware:c.middleware,handler:c.handler,params:a}}get(e,t,r,s){let o=this.joinPath(e),n=typeof t=="function"&&t.length!==3,a=n?t:r,c=n?[]:Array.isArray(t)?t:[t],p=[...this.middlewares,...c],l=n?r:s;this.addOrUpdate("GET",o,p,a,l);}post(e,t,r,s){let o=this.joinPath(e),n=typeof t=="function"&&t.length!==3,a=n?t:r,c=n?[]:Array.isArray(t)?t:[t],p=[...this.middlewares,...c],l=n?r:s;this.addOrUpdate("POST",o,p,a,l);}patch(e,t,r,s){let o=this.joinPath(e),n=typeof t=="function"&&t.length!==3,a=n?t:r,c=n?[]:Array.isArray(t)?t:[t],p=[...this.middlewares,...c],l=n?r:s;this.addOrUpdate("PATCH",o,p,a,l);}put(e,t,r,s){let o=this.joinPath(e),n=typeof t=="function"&&t.length!==3,a=n?t:r,c=n?[]:Array.isArray(t)?t:[t],p=[...this.middlewares,...c],l=n?r:s;this.addOrUpdate("PUT",o,p,a,l);}delete(e,t,r,s){let o=this.joinPath(e),n=typeof t=="function"&&t.length!==3,a=n?t:r,c=n?[]:Array.isArray(t)?t:[t],p=[...this.middlewares,...c],l=n?r:s;this.addOrUpdate("DELETE",o,p,a,l);}options(e,t,r,s){let o=this.joinPath(e),n=typeof t=="function"&&t.length!==3,a=n?t:r,c=n?[]:Array.isArray(t)?t:[t],p=[...this.middlewares,...c],l=n?r:s;this.addOrUpdate("OPTIONS",o,p,a,l);}head(e,t,r,s){let o=this.joinPath(e),n=typeof t=="function"&&t.length!==3,a=n?t:r,c=n?[]:Array.isArray(t)?t:[t],p=[...this.middlewares,...c],l=n?r:s;this.addOrUpdate("HEAD",o,p,a,l);}group(e,t,r){let s=Array.isArray(t)?t:typeof t=="function"?[]:t?[t]:[],o=Array.isArray(t)?r:typeof t=="function"?t:void 0,n=this.joinPath(e),a=new i(n,[...this.middlewares,...s]);o?.(a);for(let c of a.getRoutes())this.addOrUpdate(c.method,c.path,c.middleware,c.handler,c.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(s=>typeof s=="string"&&s.length>0).join("/");return r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r.length>1&&(r=r.replace(/\/+$/g,"")),r}},C=new vt;var Fr=i=>async(e,t,r)=>{for(let s of i)if(!await s.manager.canAccess(s.scope,s.handler,e))return t.unauthorized({error:"Unauthorized"});return r()},jo=(i,e)=>t=>{let r=w.get(t.prototype,"__class__"),s=r?.middlewares||[],o=r?.policies||[],n=w.getAll(t.prototype),a=new t;for(let[c,p]of n.entries()){if(!p.route)continue;let l=t.prototype[c].bind(a),d=i?g.join(i,p.route.path):p.route.path,h=[...o,...p.policies||[]],m=h.length>0?[Fr(h)]:[],f=[...s,...m,...p.middlewares||[]];C.addOrUpdate(p.route.method,d,f,l,{service:t.name.replace(/Controller$/,""),...e,...p.documentation});}w.clear(t.prototype);};var Mo=(i,e)=>(t,r,s)=>{let o=w.get(t,r);return o||(o={middlewares:[],route:{path:i,method:"DELETE"}}),o.documentation={...o.documentation||{},name:r,...e},o.route={path:i,method:"DELETE"},w.set(t,r,o),s};var $o=(i,e)=>(t,r,s)=>{let o=w.get(t,r);return o||(o={middlewares:[],route:{path:i,method:"GET"}}),o.documentation={...o.documentation||{},name:r,...e},o.route={path:i,method:"GET"},w.set(t,r,o),s};var No=(i,e)=>(t,r,s)=>{let o=w.get(t,r);return o||(o={middlewares:[],route:{path:i,method:"PATCH"}}),o.documentation={...o.documentation||{},name:r,...e},o.route={path:i,method:"PATCH"},w.set(t,r,o),s};var Do=(i,e)=>(t,r,s)=>{let o=w.get(t,r);return o||(o={middlewares:[],route:{path:i,method:"POST"}}),o.documentation={...o.documentation||{},name:r,...e},o.route={path:i,method:"POST"},w.set(t,r,o),s};var Qo=(i,e)=>(t,r,s)=>{let o=w.get(t,r);return o||(o={middlewares:[],route:{path:i,method:"PUT"}}),o.documentation={...o.documentation||{},name:r,...e},o.route={path:i,method:"PUT"},w.set(t,r,o),s};var Go=i=>(e,t,r)=>{if(typeof t>"u"){let o=w.get(e.prototype,"__class__");if(o||(o={middlewares:[]}),o.middlewares||(o.middlewares=[]),!i)throw new Error(`Middleware ${String(i)} not found, are you sure you defined it before using it?`);return Array.isArray(i)||(i=[i]),o.middlewares.push(...i),w.set(e.prototype,"__class__",o),e}let s=w.get(e,t);return s||(s={middlewares:[]}),s.middlewares||(s.middlewares=[]),Array.isArray(i)||(i=[i]),s.middlewares.push(...i),w.set(e,t,s),r};var N=class{static ajv=new Ajv({validateSchema:false,strict:false});static{this.ajv.addFormat("email",/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/),this.ajv.addFormat("url",/^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&\/=]*)$/),this.ajv.addFormat("date",/^\d{4}-\d{2}-\d{2}$/),this.ajv.addFormat("datetime",/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?(?:Z|[+-]\d{2}:\d{2})$/),this.ajv.addFormat("time",/^\d{2}:\d{2}:\d{2}$/),this.ajv.addFormat("binary",/^(?:[0-9a-fA-F]{2})+$/),this.ajv.addFormat("base64",/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/),this.ajv.addFormat("uuid",/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i);}static setGlobalInstance(e){this.ajv=e,this.ajv.opts.strict=false,this.ajv.opts.validateSchema=false;}};var k=new Map;var Te=class{static typeboxModule=null;static loadPromise=null;static async load(){return this.typeboxModule?this.typeboxModule:this.loadPromise?this.loadPromise:(this.loadPromise=(async()=>{try{return this.typeboxModule=await import('@sinclair/typebox'),this.typeboxModule}catch{throw new Error(`TypeBox is not installed. Install it with: npm install @sinclair/typebox
2
- TypeBox is a peer dependency required when using TypeBox schemas for validation.`)}})(),this.loadPromise)}static get(){if(!this.typeboxModule)throw new Error("TypeBox has not been loaded yet. Call TypeBoxLoader.load() first.");return this.typeboxModule}static isTypeBoxSchema(e){return typeof e=="object"&&e!==null&&"type"in e&&Object.getOwnPropertySymbols(e).some(t=>t.toString()==="Symbol(TypeBox.Kind)")}};var L=(i,e,t=false)=>{if(!i(e)){if(t)return e;throw new ValidationError(i.errors||[])}return e};var Y=class{static zodModule=null;static loadPromise=null;static async load(){return this.zodModule?this.zodModule:this.loadPromise?this.loadPromise:(this.loadPromise=(async()=>{try{return this.zodModule=await import('zod'),this.zodModule}catch{throw new Error(`Zod is not installed. Install it with: npm install zod
3
- Zod is a peer dependency required when using Zod schemas for validation.`)}})(),this.loadPromise)}static get(){if(!this.zodModule)throw new Error("Zod has not been loaded yet. Call ZodLoader.load() first.");return this.zodModule}static isZodSchema(e){let t=typeof e=="object"&&e!==null&&"_def"in e&&typeof e.parse=="function"&&typeof e.safeParse=="function";if(t&&!("toJSONSchema"in e))throw new Error("Zod4 is required with the toJSONSchema() method in order to work. Install it with: npm install zod with minimum version 4.0.0");return t}};var Nt=Symbol("serializeWrapped"),Ce=Symbol("serializeMetadata"),Oe=new WeakMap,ai=(i,e)=>(t,r,s)=>{let o=w.get(t,r)||{middlewares:[],route:{}};o.documentation||(o.documentation={}),o.documentation.responses||(o.documentation.responses={}),o.serializeOptions||(o.serializeOptions={});let n=Number(e?.status??200);if(o.documentation.responses[n]=i,o.serializeOptions[n]=e?.safe??true,w.set(t,r,o),s.value[Ce]||(s.value[Ce]={}),s.value[Ce][n]={name:r,schema:i,safe:e?.safe??true},!s.value[Nt]){let a=s.value,c=async function(...p){let l=p[1];await a.apply(this,p);let d=l.responseStatus,h=c[Ce],m=h?.[d]?.schema,f=h?.[d]?.safe??true;if(m&&!f){let b=l.getBody();try{let q;if(Y.isZodSchema(m)){let P=Oe.get(m);P||(P=Symbol("serialize_zod_schema"),Oe.set(m,P));let E=k.get(P);if(!E){let F=m.toJSONSchema();E=N.ajv.compile(F),k.set(P,E);}await L(E,b,f),l.send(b);}else if(Te.isTypeBoxSchema(m)){let P=Oe.get(m);P||(P=Symbol("serialize_typebox_schema"),Oe.set(m,P));let E=k.get(P);E||(E=N.ajv.compile(m),k.set(P,E)),await L(E,b,f),l.send(b);}else if(typeof m=="object"&&m!==null){let P=Oe.get(m);P||(P=Symbol("serialize_json_schema"),Oe.set(m,P));let E=k.get(P);E||(E=N.ajv.compile(m),k.set(P,E)),await L(E,b,f),l.send(b);}else {q=JSON.stringify(m);let P=k.get(q);P||(P=N.ajv.compile(m),k.set(q,P)),await L(P,b,f),l.send(b);}}catch(q){let P=await Y.load();if(q instanceof P.ZodError){l.internalServerError({received:b,schema:m,error:q});return}throw q}}};c[Nt]=true,c[Ce]=a[Ce],s.value=c;}};var le=i=>(e,t,r)=>{let s=r.value,o=w.get(e,t);return o||(o={middlewares:[],route:{}}),o.documentation||(o.documentation={}),i.body&&(o.documentation.requestBody=i.body),i.query&&(o.documentation.query=i.query),i.all&&(o.documentation.requestBody=i.body,o.documentation.query=i.query),w.set(e,t,o),r.value=async function(...n){let a=n[0],c=n[1];try{let p,l,d;i.body&&(p=a.validate(i.body,i.safe)),i.query&&(l=a.validateQuery(i.query,i.safe)),i.all&&(d=a.validateAll(i.all,i.safe));let h=[...n];return p!==void 0&&h.push(p),l!==void 0&&h.push(l),d!==void 0&&h.push(d),s.apply(this,h)}catch(p){let l=await Y.load();if(!(p instanceof l.ZodError))throw p;return i.customError?c.status(i.customError.status||400).json({received:a.body,schema:i.body,error:p}):c.badRequest(p)}},r};le.query=(i,e)=>le({query:i,customError:e});le.body=(i,e)=>le({body:i,customError:e});le.all=(i,e)=>le({all:i,customError:e});var di=le;var Lt=class{logger=v.child({scope:this.constructor.name})};var _t=class{logger=v.child({scope:this.constructor.name})};var Gr=i=>{if(!Buffer.isBuffer(i))return i;let e=i.toString();if(!e.length)return e;try{let t=JSON.parse(e);return typeof t=="object"&&t!==null?t:e}catch{return e}},Le=class i{static subscriptions=[];static client=null;static connectionOptions={};static register(e,t,r,s){this.subscriptions.push({name:e,topic:t,handler:r,options:s});}static async connect(e={}){let t=await import('mqtt').catch(()=>{throw new T("mqtt not installed as a dependency, it is required in order to use MQTT subscriptions with the @mqtt decorator")});this.connectionOptions=e,v.info("Starting MQTT client"),this.subscriptions.length||v.info("No MQTT subscriptions to register");let{host:r="localhost",port:s=1883,protocol:o="mqtt",...n}=e,a=`${o}://${r}:${s}`;this.client=await t.connectAsync(a,n),v.info("MQTT client connected"),this.client.on("error",async c=>{await this.globalErrorHandler(c);}),this.client.on("message",(c,p)=>{this.handleMessage(c,p);}),this.client.on("disconnect",()=>{v.info("MQTT client disconnected");}),this.client.on("reconnect",async()=>{await this.globalErrorHandler(new Error("MQTT client reconnecting"));}),this.subscribeToTopics();}static subscribeToTopics(){if(this.client)for(let{name:e,topic:t,options:r}of this.subscriptions)v.info(`Subscribing to MQTT topic: ${t} (${e})`),this.client.subscribe(t,r||{},s=>{if(s){v.error(`Failed to subscribe to topic ${t}: ${s.message}`);return}v.info(`Successfully subscribed to topic: ${t}`);});}static async handleMessage(e,t){let r=this.subscriptions.filter(s=>{if(s.topic===e)return true;if(!e||typeof e!="string")return false;let o=s.topic.replace(/\+/g,"[^/]+").replace(/#$/,".*");return new RegExp(`^${o}$`).test(e)});for(let s of r)try{await s.handler(e,t);}catch(o){v.error(`Error handling MQTT message for topic ${e} in ${s.name}`),this.globalErrorHandler(o);}}static globalErrorHandler(e){v.error(e);}static setOnDisconnectHandler(e){this.client?.on("disconnect",e);}static setOnReconnectHandler(e){this.client?.on("reconnect",e);}static async massiveImportMqttHandlers(e){let t=[];for(let r of e){let s=await glob(r,{absolute:true,cwd:$.getCwd()});t.push(...s);}await Promise.all(t.map(async r=>{await import(r).catch(s=>{v.error(`Error importing MQTT handler: ${r}`),v.error(s);});}));}subscribe(e,t){return function(r,s,o){let n=o.value;if(!n)return o;let a=async(c,p)=>{let l=new r.constructor,d=Gr(p);if(n.length===1){await n.call(l,d);return}await n.call(l,c,d);};return i.register(`${r.constructor.name}.${s}`,e,a,t),o}}async publish(e,t,r){if(!i.client)throw new T("MQTT client is not connected. Call MqttService.connect() first.");if(!i.client.connected)throw new T("MQTT client is not connected. Call MqttService.connect() first.");let s;Buffer.isBuffer(t)?s=t:typeof t=="object"?s=JSON.stringify(t):s=String(t);try{await i.client.publishAsync(e,s,r||{}),v.debug(`Published message to topic: ${String(e)}`);}catch(o){throw v.error(`Failed to publish to topic ${String(e)}: ${o.message}`),o}}static async disconnect(){if(this.client)return new Promise(e=>{this.client?.end(false,{},()=>{v.info("MQTT client disconnected gracefully"),this.client=null,e();});})}},Si=i=>{Le.globalErrorHandler=i.bind(Le);},xi=new Le;var Dt=class{logger=v.child({scope:this.constructor.name})};var W=class{static options={connection:{}}},It=i=>{W.options=i??{connection:{}};};var U=class extends T{constructor(...e){super(`Library not installed: ${e.join(", ")}, try run npm install ${e.join(" ")}`);}};var wt=class{randomUUID(){return crypto.randomUUID()}},X=new wt;var Ke=class{queues=new Map;workers=new Map;async publish(e,t,r){let s=await this.getQueue(e),o=X.randomUUID();return await s.add(e,t,{jobId:o,...W.options?.defaultJobOptions,...r}),{id:o}}async subscribe(e,t){if(this.workers.has(e))throw new Error(`[BullMQ] Already subscribed to topic "${e}"`);let{errorHandler:r,...s}=W.options??{},o=await this.getBullMQClient(),n=new o.Worker(e,async a=>{try{await t(a.data);}catch(c){await r?.(a,c)??Promise.reject(c);}},{...s});this.workers.set(e,n);}async getQueue(e){if(!this.queues.has(e)){let t=await import('bullmq').catch(()=>{throw new U("bullmq","ioredis")}),r=new t.Queue(e,{...W.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 U("bullmq","ioredis")})),this.bullmqClient}async publishWithConfig(e,t,r,s){let o=await this.getQueueWithConfig(e,s),n=X.randomUUID(),a={jobId:n,...W.options?.defaultJobOptions,...s?.defaultJobOptions,...r};return await o.add(e,t,a),{id:n}}async subscribeWithConfig(e,t,r){let s=this.getWorkerKey(e,r);if(this.workers.has(s))throw new Error(`[BullMQ] Already subscribed to topic "${e}"`);let o=W.options??{},{errorHandler:n}=o,a=await this.getBullMQClient(),c={...o,...r};delete c.errorHandler,delete c.defaultJobOptions;let p=new a.Worker(e,async l=>{try{await t(l.data);}catch(d){await n?.(l,d)??Promise.reject(d);}},c);this.workers.set(s,p);}async getQueueWithConfig(e,t){let r=this.getQueueKey(e,t);if(!this.queues.has(r)){let s=await import('bullmq').catch(()=>{throw new U("bullmq","ioredis")}),o={...W.options||{connection:{}},...t},n=new s.Queue(e,o);this.queues.set(r,n);}return this.queues.get(r)}getQueueKey(e,t){return t?.connection?`${e}:${JSON.stringify(t.connection)}`:e}getWorkerKey(e,t){return this.getQueueKey(e,t)}};var G=class{static options={}},Ft=i=>{G.options=i??{};};var Ve=class{createdQueues=new Set;async publish(e,t,r){let s=await this.getBoss();await this.ensureQueue(e);let o=r||{},n=await s.send(e,t,o);return {id:String(n??"")}}async subscribe(e,t){let r=await this.getBoss();await this.ensureQueue(e);let s=G.options;s.errorHandler&&r.on("error",s.errorHandler),await r.work(e,async o=>{let n=Array.isArray(o)?o:[o];for(let a of n)await t(a.data);});}async getBoss(){if(this.boss)return this.boss;let e=await import('pg-boss').catch(()=>{throw new U("pg-boss","pg")}),r=e.PgBoss.default??e.PgBoss,{connectionString:s,boss:o}=G.options,n=s??o,a=new r(n);return G.options?.errorHandler&&a.on("error",G.options.errorHandler),await a.start(),this.boss=a,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);}async publishWithConfig(e,t,r,s){let o=await this.getBossWithConfig(s);await this.ensureQueueWithBoss(e,o);let n=r||{},a=await o.send(e,t,n);return {id:String(a??"")}}async subscribeWithConfig(e,t,r){let s=await this.getBossWithConfig(r);await this.ensureQueueWithBoss(e,s);let o=G.options;o.errorHandler&&s.on("error",o.errorHandler),await s.work(e,async n=>{let a=Array.isArray(n)?n:[n];for(let c of a)await t(c.data);});}bossInstances=new Map;async getBossWithConfig(e){if(!e?.connectionString)return this.getBoss();let t=e.connectionString;if(this.bossInstances.has(t))return this.bossInstances.get(t);let r=await import('pg-boss').catch(()=>{throw new U("pg-boss","pg")}),o=r.PgBoss.default??r.PgBoss,n=new o(e.connectionString);return G.options?.errorHandler&&n.on("error",G.options.errorHandler),await n.start(),this.bossInstances.set(t,n),n}async ensureQueueWithBoss(e,t){this.createdQueues.has(e)||(typeof t.createQueue=="function"&&await t.createQueue(e),this.createdQueues.add(e));}};var se=class{static options={}},Qt=i=>{se.options=i??{};};var Ze=class{consumers=new Map;client;async publish(e,t,r){let s=await this.getClient(),{SendMessageCommand:o}=await this.getSqsLib(),n=await this.resolveQueueUrl(e);if(!n)throw new Error(`[SQS] Queue url not configured for topic "${e}"`);let a=new o({MessageBody:JSON.stringify(t),MessageAttributes:{topic:{DataType:"String",StringValue:e}},QueueUrl:n,...r??{}});return {id:(await s.send(a)).MessageId??""}}async subscribe(e,t){if(this.consumers.has(e))throw new Error(`[SQS] Already subscribed to topic "${e}"`);let r=se.options,s=await this.getSqsConsumerLib(),o={...r.consumer||{},sqs:await this.getClient(),queueUrl:await this.resolveQueueUrl(e),handleMessage:async c=>{let p=JSON.parse(c.Body||"{}");await t(p);}},n=s.Consumer.create(o),a=r.errorHandler;a&&(n.on("error",a),n.on("processing_error",a)),n.start(),this.consumers.set(e,n);}async getClient(){if(this.client)return this.client;let{SQSClient:e}=await this.getSqsLib(),t=se.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 U("@aws-sdk/client-sqs","sqs-consumer")})),this.sqsLib}async getSqsConsumerLib(){return this.sqsConsumerLib||(this.sqsConsumerLib=await import('sqs-consumer').catch(()=>{throw new U("sqs-consumer")})),this.sqsConsumerLib}async resolveQueueUrl(e){let r=se.options.consumer?.queueUrlMap;if(!r?.[e])throw new Error(`[SQS] Queue url not configured for topic "${e}"`);return r[e]}async publishWithConfig(e,t,r,s){let{...o}=r??{},n=await this.getClientWithConfig(s?.client),{SendMessageCommand:a}=await this.getSqsLib(),c=s?.queueUrl??await this.resolveQueueUrl(e),p=new a({...o,MessageBody:JSON.stringify(t),MessageAttributes:{topic:{DataType:"String",StringValue:e}},QueueUrl:c});return {id:(await n.send(p)).MessageId??""}}async subscribeWithConfig(e,t,r){if(this.consumers.has(e))throw new Error(`[SQS] Already subscribed to topic "${e}"`);let s=se.options,o=await this.getSqsConsumerLib(),n=r?.queueUrl??await this.resolveQueueUrl(e),a={...s.consumer||{},sqs:await this.getClientWithConfig(r?.client),queueUrl:n,handleMessage:async l=>{let d=JSON.parse(l.Body||"{}");await t(d);}},c=o.Consumer.create(a),p=s.errorHandler;p&&(c.on("error",p),c.on("processing_error",p)),c.start(),this.consumers.set(e,c);}async getClientWithConfig(e){if(e){let{SQSClient:t}=await this.getSqsLib();return new t(e)}return this.getClient()}};var ee=class{static map=new Map;static{this.map.set("bullmq",new Ke),this.map.set("sqs",new Ze),this.map.set("pgboss",new Ve);}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 Zi=i=>{let e=["bullmq","pgboss","sqs"];i.bullmq&&It(i.bullmq),i.pgboss&&Ft(i.pgboss),i.sqs&&Qt(i.sqs);for(let t of Object.keys(i)){let r=t;e.includes(r)||ee.setProvider(r,i[r]);}};var de=class{static typedQueueSubscribers=new Map;static customQueueSubscribers=new Map;static instanceFactory=e=>new e;static registerTypedQueue(e,t,r,s,o){let n=`${s}:${t}:${e}`;this.typedQueueSubscribers.has(n)&&v.warn(`Queue handler for ${n} already registered, overwriting previous handler`),this.typedQueueSubscribers.set(n,{name:e,topic:t,handler:r,provider:s,queueOptions:o});}static registerCustomQueue(e,t,r,s){let o=`${s.constructor.name}:${t}:${e}`;this.customQueueSubscribers.has(o)&&v.warn(`Custom queue handler for ${o} already registered, overwriting previous handler`),this.customQueueSubscribers.set(o,{name:e,topic:t,handler:r,pubsub:s});}static async run(){v.info("Subscribing queue handlers");let e=this.typedQueueSubscribers.size>0,t=this.customQueueSubscribers.size>0;if(!e&&!t){v.info("No queue handlers to subscribe");return}for(let r of this.typedQueueSubscribers.values()){let{topic:s,handler:o,provider:n,queueOptions:a}=r;v.info(`Subscribing to queue: ${s}`);let c=ee.getProvider(n);a&&"subscribeWithConfig"in c&&typeof c.subscribeWithConfig=="function"?await c.subscribeWithConfig(s,o,a):await c.subscribe(s,o);}for(let{topic:r,handler:s,pubsub:o}of this.customQueueSubscribers.values())v.info(`Subscribing to custom queue: ${r}`),await o.subscribe(r,s);v.info("Queue handlers subscribed");}static async massiveImportQueues(e,t={}){let r=[];for(let s of e){let o=await glob(s,{absolute:true,cwd:$.getCwd()});r.push(...o);}await Promise.all(r.map(async s=>{await import(s).catch(o=>{if(v.error(`Error importing queue handler: ${s}`),v.error(o),t.throwOnError)throw o});}));}};var Je=new WeakMap,ue=class{constructor(e,t,r){this.topic=e;this.provider=t;this.queueOptions=r;}async publish(e,t){let r=ee.getProvider(this.provider);return this.queueOptions?r.publishWithConfig(this.topic,e,t,this.queueOptions):r.publish(this.topic,e,t??{})}subscribe(e){return e?this.subscribeWithCallback(e):this.createSubscribeDecorator()}createSubscribeDecorator(){let e=this.topic,t=this.provider,r=this.queueOptions;return function(s,o,n){let a=n.value,c=async p=>{let l=Je.get(s.constructor);return l||(l=de.instanceFactory(s.constructor),Je.set(s.constructor,l)),a.apply(l,[p])};return de.registerTypedQueue(`${s.constructor.name}.${String(o)}`,e,c,t,r),n}}async subscribeWithCallback(e){let t=ee.getProvider(this.provider);return this.queueOptions?t.subscribeWithConfig(this.topic,e,this.queueOptions):t.subscribe(this.topic,e)}},_e=class{constructor(e,t){this.topic=e;this.pubsub=t;}async publish(e,t){return this.pubsub.publish(this.topic,e,t)}subscribe(e){return e?this.pubsub.subscribe(this.topic,e):this.createSubscribeDecorator()}createSubscribeDecorator(){let e=this.topic,t=this.pubsub;return function(r,s,o){let n=o.value,a=async c=>{let p=Je.get(r.constructor);return p||(p=de.instanceFactory(r.constructor),Je.set(r.constructor,p)),n.apply(p,[c])};return de.registerCustomQueue(`${r.constructor.name}.${String(s)}`,e,a,t),o}}};function Kr(i,e){return new ue(i,"sqs",e)}function Vr(i,e){return new ue(i,"bullmq",e)}function Zr(i,e){return new ue(i,"pgboss",e)}function Jr(i,e){return new _e(i,e)}Q();var bt=class{exit(e){switch(R.type){case "bun":case "node":process.exit(e);case "deno":Deno.exit(e);default:throw new Error("Unsupported runtime")}}},St=new bt;var j=class{static commandName=this.name;static calledBy=this.name;static description="";static help=[];static options={keepAlive:false};static args=ce().args.slice(1);static flags=ce().flags;static logger=v;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(p=>t.includes(p)))return;let s=this.commandName,o=this.description||"No description available",n=this.help||[],a=this.options,c=this.generateHelpOutput({name:s,description:o,helpText:n,options:a,args:this.args,flags:this.flags},this);console.log(c),St.exit(0);}static generateHelpOutput=(e,t)=>{let{name:r,description:s,helpText:o,options:n,args:a,flags:c}=e,p={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"},l=[`${p.title}${r}${p.reset}`,`${p.description}${s}${p.reset}`,"",`${p.subtitle}Usage:${p.reset}`,` ${p.code}${r}${p.reset} [options] [arguments]`,"",`${p.subtitle}Options:${p.reset}`,` ${p.flag}-h, --help${p.reset} Show this help message`,"",`${p.subtitle}Command Options:${p.reset}`,` ${p.flag}keepAlive${p.reset} ${n?.keepAlive??false?p.success+"Enabled"+p.reset:p.error+"Disabled"+p.reset}`,""];if(o){let f=Array.isArray(o)?o:[o];l.push(`${p.subtitle}Help:${p.reset}`),f.forEach(b=>{l.push(` ${p.description}${b}${p.reset}`);}),l.push("");}let d=w.getAll(t),h=Array.from(d.values()).filter(f=>f.type==="arg"),m=Array.from(d.values()).filter(f=>f.type==="flag");return h.length&&(l.push(`${p.subtitle}Available Arguments:${p.reset}`),h.forEach(f=>{let b=f.required?` ${p.error}(required)${p.reset}`:"",q=f.description?` ${p.description}${f.description}${p.reset}`:"";l.push(` ${p.code}${f.name}${p.reset}${b}${q}`);}),l.push("")),m.length&&(l.push(`${p.subtitle}Available Flags:${p.reset}`),m.forEach(f=>{f.aliases&&!Array.isArray(f.aliases)&&(f.aliases=[f.aliases]);let b=f.aliases.length?` ${p.flag}(${f.aliases.join(", ")})${p.reset}`:"",q=f.required?` ${p.error}(required)${p.reset}`:"",P=f.description?` ${p.description}${f.description}${p.reset}`:"";l.push(` ${p.flag}--${f.name}${b}${p.reset}${q}${P}`);}),l.push("")),((a?.length??0)>0||c&&Object.keys(c).length>0)&&(l.push(`${p.subtitle}Current Context:${p.reset}`),a?.length&&l.push(` ${p.info}Provided Arguments:${p.reset} ${p.code}${a.join(" ")}${p.reset}`),c&&Object.keys(c).length>0&&(l.push(` ${p.info}Provided Flags:${p.reset}`),Object.keys(c).forEach(f=>{let b=c[f],q=b!=null?` = ${p.code}${b}${p.reset}`:"";l.push(` ${p.flag}${f}${p.reset}${q}`);})),l.push("")),o&&(Array.isArray(o)?o.some(f=>f.includes("example")):o.includes("example"))&&(l.push(`${p.subtitle}Examples:${p.reset}`),(Array.isArray(o)?o.filter(b=>b.includes("example")):[o.split("example")[1].trim()]).forEach(b=>{l.push(` ${p.code}${b}${p.reset}`);}),l.push("")),l.join(`
4
- `)};static validateContext=e=>{let t=Array.from(w.get(e,pe)||[]);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((s,o)=>{let n=`${r.info}${o+1}.${r.reset}`,a=`${r.error}${s.type.toUpperCase()}${r.reset}`,c=`${r.code}${s.name}${r.reset}`;console.error(` ${n} ${a} ${c}: ${r.error}${s.message}${r.reset}`);}),console.error(""),console.error(`${r.info}\u{1F4A1} Tip: Use --help for usage information${r.reset}`),St.exit(1);}}};Q();var xt=class{async mkdir(e,t){switch(R.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(R.type){case "node":return (await import('fs')).existsSync(e);case "bun":return (await import('fs')).existsSync(e);case "deno":return Deno.stat(e).then(()=>true).catch(()=>false);default:throw new Error("Unsupported runtime")}}async readFile(e,t){switch(R.type){case "node":let s=await(await import('fs/promises')).readFile(e,{encoding:t?.encoding??null});return t?.encoding==="utf8"?s:new Uint8Array(s);case "bun":let o=Bun.file(e);return t?.encoding==="utf8"?o.text():new Uint8Array(await o.arrayBuffer());case "deno":let n=await Deno.readFile(e);return t?.encoding==="utf8"?new TextDecoder().decode(n):new Uint8Array(n)}}async writeFile(e,t){switch(R.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(R.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(await import('fs/promises')).stat(e);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(R.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")}}async streamFile(e){switch(R.type){case "node":let t=await import('fs'),{Readable:r}=await import('stream'),s=t.createReadStream(e);return r.toWeb(s);case "bun":return Bun.file(e).stream();case "deno":return (await Deno.open(e)).readable;default:throw new Error("Unsupported runtime")}}async readdir(e){switch(R.type){case "bun":case "node":return (await import('fs/promises')).readdir(e);case "deno":let r=[];for await(let s of Deno.readDir(e))r.push(s.name);return r;default:throw new Error("Unsupported runtime")}}},u=new xt;var je=async i=>{let e=g.join(process.cwd(),"node_modules");if(!await u.exists(e))return i;let r=[];for(let s of i){let o=g.join(e,s);await u.exists(o)||r.push(s);}return r},z=async()=>await u.exists(g.join(process.cwd(),"yarn.lock"))?["yarn","add","-D"]:await u.exists(g.join(process.cwd(),"pnpm-lock.yaml"))?["pnpm","add","-D"]:await u.exists(g.join(process.cwd(),"package-lock.json"))?["npm","install","-D"]:await u.exists(g.join(process.cwd(),"bun.lockb"))?["bun","add","-D"]:await u.exists(g.join(process.cwd(),"deno.lock"))?["deno","add","-D"]:["npm","install","-D"],_=async(i,e,t,r,s=true)=>{let o=Ut.createInterface({input:process.stdin,output:process.stdout}),n=t.join(", "),a=`Do you want to install the following ${s?"dev":""} dependencies using ${e}?
5
- ${n}
6
- (y/n): `;return new Promise(c=>{o.question(a,p=>{if(o.close(),p.toLowerCase()==="y"||p.toLowerCase()==="yes"){execSync(i,r),c(true);return}c(false);});})};var I=class extends j{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(){if(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)),!await import('esbuild').then(a=>true).catch(()=>false)){let[a,c,p]=await z();await _(`${a} ${c} esbuild ${p}`,a,["esbuild"],{stdio:"inherit"})||(this.logger.warn("User chose to not continue with the installation of esbuild, exiting..."),process.exit(0));}let t=await import('esbuild').catch(a=>{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")}),r=We.join(this.output,"assets"),s=[];if(this.assets){let{copy:a}=await import('esbuild-plugin-copy').catch(c=>{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")});Ye.existsSync(r)||Ye.mkdirSync(r,{recursive:true}),s.push(a({assets:{from:this.assets,to:r}}));}this.clearDist&&Ye.existsSync(this.output)&&(this.logger.info("Clearing dist directory..."),Ye.rmSync(this.output,{recursive:true})),this.logger.info("Building project...");let o=We.join(this.output,"server.js"),n=await t.build({tsconfig:this.tsconfig,entryPoints:[this.entry],bundle:true,platform:"node",outfile:o,minify:true,sourcemap:this.sourcemap,plugins:s,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);}};y([x({type:"boolean",aliases:["c"],name:"clear-dist",required:false,defaultValue:false,description:"Whether to clear the dist directory before building the project"})],I,"clearDist"),y([x({type:"string",aliases:["e"],name:"entry",required:false,defaultValue:"./src/index.ts",description:"The entry point of the project, default is ./src/index.ts"})],I,"entry"),y([x({type:"string",aliases:["o"],name:"output",required:false,defaultValue:"./dist",description:"The path to the output directory, default is ./dist"})],I,"output"),y([x({type:"string",aliases:["t"],name:"tsconfig",required:false,defaultValue:"./tsconfig.json",description:"The path to the tsconfig.json file, default is ./tsconfig.json"})],I,"tsconfig"),y([x({type:"string",aliases:["a"],name:"assets",required:false,description:"The path to the assets directory that will be loaded in the production build"})],I,"assets"),y([x({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'"})],I,"format"),y([x({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'"})],I,"packages"),y([x({type:"boolean",aliases:["s"],name:"sourcemap",required:false,defaultValue:true,description:"Whether to generate sourcemaps or not, default is true"})],I,"sourcemap");var Ee=class extends j{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(){if(qe.getCommand(this.name)){let s=qe.isBuiltInCommand(this.name)?"built-in":"user-defined";this.logger.error({commandName:this.name,type:s},`Command "${this.name}" already exists as a ${s} command. Cannot override existing commands.`);return}let t=this.getCommandTemplate();this.path=g.join(this.path,`${this.name}.ts`),await u.exists(g.join(process.cwd(),this.path))||await u.mkdir(g.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await u.writeFile(this.path,new TextEncoder().encode(t)),this.logger.info(`Command ${this.name} created successfully at ${this.path}`);}static getCommandTemplate(){return `import { Command, CommandOptions } from "balda";
1
+ import {glob}from'glob';import kt from'pino';import Ze from'path';import {Ajv,ValidationError}from'ajv';import tt from'fs';import {execSync}from'child_process';import*as zt from'readline';import {AsyncLocalStorage}from'async_hooks';import {gzipSync}from'zlib';import {createServer}from'http';import {createServer as createServer$1,createSecureServer}from'http2';import {createServer as createServer$2}from'https';import {Readable}from'stream';import {pipeline}from'stream/promises';var At=Object.defineProperty;var Nr=(n,e)=>()=>(n&&(e=n(n=0)),e);var _r=(n,e)=>{for(var t in e)At(n,t,{get:e[t],enumerable:true});};var w=(n,e,t,r)=>{for(var s=void 0,o=n.length-1,i;o>=0;o--)(i=n[o])&&(s=(i(e,t,s))||s);return s&&At(e,t,s),s};var $t={};_r($t,{runtime:()=>T});var mt,T,U=Nr(()=>{mt=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")}},T=new mt;});var O=class extends Error{constructor(e){super(e);}};var Dr=()=>kt({level:"info",formatters:{level:e=>({level:e})}}),b=Dr(),Vs=n=>{b=kt(n);};U();var ht=class{getCwd(){switch(T.type){case "node":case "bun":return process.cwd();case "deno":return Deno.cwd();default:throw new Error("Unsupported runtime")}}},B=new ht;var Te=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(b.info("Scheduling cron jobs"),!this.scheduledJobs.length){b.info("No cron jobs to schedule");return}for(let{name:t,args:r}of this.scheduledJobs)b.info(`Scheduling cron job: ${t}`),e.schedule(...r).on("execution:failed",o=>this.globalErrorHandler(o));b.info("Cron jobs scheduled");}static globalErrorHandler(e){b.error(e.execution?.error);}static async massiveImportCronJobs(e){let t=[];for(let r of e){let s=await glob(r,{absolute:true,cwd:B.getCwd()});t.push(...s);}await Promise.all(t.map(async r=>{await import(r).catch(s=>{b.error(`Error importing cron job: ${r}`),b.error(s);});}));}},so=n=>{Te.globalErrorHandler=n.bind(Te);};var io=(n,e)=>function(t,r,s){let o=s.value,i=async(...a)=>{let c=new t.constructor;return await o.apply(c,a)};return Te.register(`${t.constructor.name}.${r}`,n,i,e),s};U();var gt=class{getCliArgs(){switch(T.type){case "bun":return this.getBunArgs();case "node":return this.getNodeArgs();case "deno":return Deno.args;default:throw new Error("Unsupported runtime")}}getCliCaller(){switch(T.type){case "bun":return "bun";case "node":return process.argv[0];case "deno":return "deno";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],s=r.split("/").pop()||r;if(!r.startsWith("-")){if(s==="yarn"&&t+1<e.length&&e[t+1]==="run"||s==="npx"&&t+1<e.length)return t+1;if(s==="yarn"||s==="pnpm")return t;if(s==="npm"&&t+1<e.length&&e[t+1]==="run"||s==="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(s)){for(let o=t+1;o<e.length;o++)if(!e[o].startsWith("-")&&/\.(js|ts|mjs|cjs)$/.test(e[o]))return o;return t}}}for(let t=e.length-1;t>=0;t--)if(!e[t].startsWith("-"))return t;return 1}},ft=new gt;var We=n=>n.toLowerCase().replace(/[-_.]/g,"_").replace(/([A-Z])/g,"_$1").replace(/^_+/,"").replace(/_+$/,"").toLowerCase(),Ke=n=>n.split(/[-_.]/g).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),Bt=n=>n.split(/[-_.]/g).map(e=>e.toLowerCase()).join("-");var le=(n,e)=>{if(!n||typeof n!="string")return e;let t=n.toLowerCase().trim(),r=t.match(/^(\d+(?:\.\d+)?)kb$/),s=t.match(/^(\d+(?:\.\d+)?)mb$/);if(r){let o=Number.parseFloat(r[1]);return Number.isNaN(o)||o<0?e:Math.floor(o*1024)}if(s){let o=Number.parseFloat(s[1]);return Number.isNaN(o)||o<0?e:Math.floor(o*1024*1024)}return e};var Fr=n=>{if(!n||n==="-"||n==="--")return null;let e=n.indexOf("=");if(e>0){let t=n.substring(0,e),r=n.substring(e+1);return {name:t,value:Ht(r)}}return {name:n,value:true}},Ht=n=>{if(n.toLowerCase()==="true")return true;if(n.toLowerCase()==="false")return false;let e=Number(n);return !Number.isNaN(e)&&Number.isFinite(e)?e:n},de=()=>{let n=ft.getCliArgs(),e=[],t={};if(!n||!n.length)return {args:e,flags:t};for(let r=0;r<n.length;r++){let s=n[r];if(!(!s||typeof s!="string")){if(s.startsWith("-")){let o=Fr(s);if(o){if(o.value===true&&r+1<n.length){let i=n[r+1];i&&typeof i=="string"&&!i.startsWith("-")&&(o.value=Ht(i),r++);}if(o.name in t){let i=t[o.name];Array.isArray(i)?i.push(o.value):t[o.name]=[i,o.value];}else t[o.name]=o.value;}continue}e.push(s);}}return {args:e,flags:t}};var Ve=()=>ft.getCliArgs()[0]||null;var x=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 ue="VALIDATION_ERROR",wo="ARG",Lt=de().args.slice(1),k=n=>(e,t)=>{let r=Ve();if(!r||r!==e.commandName)return;let s=t;x.set(e,t,{type:"arg",name:s,description:n.description});let o=Lt.length?Lt.shift():n.defaultValue;if(n.required&&!o){let i=x.get(e,ue);x.set(e,ue,[...i||[],{type:"arg",name:s,message:"Required argument not provided"}]);return}n.parse&&o&&(o=n.parse(o)),Object.defineProperty(e,t,{value:o,enumerable:true,configurable:true,writable:true});};var X=n=>(e,t)=>{let r=Ve();if(!r||r!==e.commandName)return;let s=n.name||t,o=de().flags,i=n.aliases||[],a=[s,...i],c=n.defaultValue;for(let p of a){let l=[p,`-${p}`,`--${p}`];for(let d of l)if(d in o){let g=o[d];n.type==="list"?c=(Array.isArray(g)?g:[g]).map(m=>{let y=String(m);return n.parse?n.parse(y):y}):(c=g,n.type==="boolean"?c=!!c:n.type==="number"&&(c=Number(c)),n.parse&&(c=n.parse(c)));break}if(c!==n.defaultValue)break}if(x.set(e,t,{type:"flag",name:s,aliases:i||[],description:n.description}),n.required&&(n.type==="list"?!c||Array.isArray(c)&&c.length===0:!c)){let l=x.get(e,ue);x.set(e,ue,[...l||[],{type:"flag",name:s,message:"Required flag not provided"}]);return}Object.defineProperty(e,t,{value:c,enumerable:true,configurable:true,writable:true});};X.boolean=n=>X({...n,type:"boolean"});X.string=n=>X({...n,type:"string"});X.number=n=>X({...n,type:"number"});X.list=n=>X({...n,type:"list"});var R=X;U();var yt=class{basename(e){switch(T.type){case "node":case "bun":case "deno":return Ze.basename(e);default:throw new Error("Unsupported runtime")}}join(...e){switch(T.type){case "node":case "bun":case "deno":return Ze.join(...e);default:throw new Error("Unsupported runtime")}}extName(e){switch(T.type){case "bun":case "node":case "deno":return Ze.extname(e);default:throw new Error("Unsupported runtime")}}resolve(...e){switch(T.type){case "bun":case "node":case "deno":return Ze.resolve(...e);default:throw new Error("Unsupported runtime")}}},h=new yt;var Oe=class{staticChildren;paramChild;wildcardChild;middleware;handler;constructor(){this.staticChildren=new Map,this.paramChild=null,this.wildcardChild=null,this.middleware=null,this.handler=null;}},vt=class n{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,s,o){e=e.toUpperCase();let i=this.trees.get(e);i||(i=new Oe,this.trees.set(e,i));let c=t.split("?")[0].replace(/^\/+|\/+$/g,""),p=c.length===0?[]:c.split("/"),l=i;for(let g of p){if(g==="*"){l.wildcardChild||(l.wildcardChild=new Oe),l=l.wildcardChild;break}if(g.startsWith(":")){let f=g.slice(1);l.paramChild||(l.paramChild={node:new Oe,name:f}),l=l.paramChild.node;continue}l.staticChildren.has(g)||l.staticChildren.set(g,new Oe),l=l.staticChildren.get(g);}l.middleware=r,l.handler=s;let d=this.routes.findIndex(g=>g.method===e&&g.path===t);if(d!==-1){this.routes[d].middleware=r,this.routes[d].handler=s;return}this.routes.push({method:e,path:t,middleware:r,handler:s,swaggerOptions:o});}find(e,t){e=e.toUpperCase();let r=this.trees.get(e);if(!r)return null;let o=t.split("?")[0].replace(/^\/+|\/+$/g,""),i=o.length===0?[]:o.split("/"),a={},c=r;for(let p=0;p<i.length;p++){let l=i[p];if(c.staticChildren.has(l)){c=c.staticChildren.get(l);continue}if(c.paramChild){a[c.paramChild.name]=l,c=c.paramChild.node;continue}if(c.wildcardChild){a["*"]=i.slice(p).join("/"),c=c.wildcardChild;break}return null}return !c.handler||!c.middleware?null:{middleware:c.middleware,handler:c.handler,params:a}}get(e,t,r,s){let o=this.joinPath(e),i=typeof t=="function"&&t.length!==3,a=i?t:r,c=i?[]:Array.isArray(t)?t:[t],p=[...this.middlewares,...c],l=i?r:s;this.addOrUpdate("GET",o,p,a,l);}post(e,t,r,s){let o=this.joinPath(e),i=typeof t=="function"&&t.length!==3,a=i?t:r,c=i?[]:Array.isArray(t)?t:[t],p=[...this.middlewares,...c],l=i?r:s;this.addOrUpdate("POST",o,p,a,l);}patch(e,t,r,s){let o=this.joinPath(e),i=typeof t=="function"&&t.length!==3,a=i?t:r,c=i?[]:Array.isArray(t)?t:[t],p=[...this.middlewares,...c],l=i?r:s;this.addOrUpdate("PATCH",o,p,a,l);}put(e,t,r,s){let o=this.joinPath(e),i=typeof t=="function"&&t.length!==3,a=i?t:r,c=i?[]:Array.isArray(t)?t:[t],p=[...this.middlewares,...c],l=i?r:s;this.addOrUpdate("PUT",o,p,a,l);}delete(e,t,r,s){let o=this.joinPath(e),i=typeof t=="function"&&t.length!==3,a=i?t:r,c=i?[]:Array.isArray(t)?t:[t],p=[...this.middlewares,...c],l=i?r:s;this.addOrUpdate("DELETE",o,p,a,l);}options(e,t,r,s){let o=this.joinPath(e),i=typeof t=="function"&&t.length!==3,a=i?t:r,c=i?[]:Array.isArray(t)?t:[t],p=[...this.middlewares,...c],l=i?r:s;this.addOrUpdate("OPTIONS",o,p,a,l);}head(e,t,r,s){let o=this.joinPath(e),i=typeof t=="function"&&t.length!==3,a=i?t:r,c=i?[]:Array.isArray(t)?t:[t],p=[...this.middlewares,...c],l=i?r:s;this.addOrUpdate("HEAD",o,p,a,l);}group(e,t,r){let s=Array.isArray(t)?t:typeof t=="function"?[]:t?[t]:[],o=Array.isArray(t)?r:typeof t=="function"?t:void 0,i=this.joinPath(e),a=new n(i,[...this.middlewares,...s]);o?.(a);for(let c of a.getRoutes())this.addOrUpdate(c.method,c.path,c.middleware,c.handler,c.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(s=>typeof s=="string"&&s.length>0).join("/");return r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r.length>1&&(r=r.replace(/\/+$/g,"")),r}},j=new vt;var Qr=n=>async(e,t,r)=>{for(let s of n)if(!await s.manager.canAccess(s.scope,s.handler,e))return t.unauthorized({error:"Unauthorized"});return r()},Ao=(n,e)=>t=>{let r=x.get(t.prototype,"__class__"),s=r?.middlewares||[],o=r?.policies||[],i=x.getAll(t.prototype),a=new t;for(let[c,p]of i.entries()){if(!p.route)continue;let l=t.prototype[c].bind(a),d=n?h.join(n,p.route.path):p.route.path,g=[...o,...p.policies||[]],f=g.length>0?[Qr(g)]:[],m=[...s,...f,...p.middlewares||[]];j.addOrUpdate(p.route.method,d,m,l,{service:t.name.replace(/Controller$/,""),...e,...p.documentation});}x.clear(t.prototype);};var Bo=(n,e)=>(t,r,s)=>{let o=x.get(t,r);return o||(o={middlewares:[],route:{path:n,method:"DELETE"}}),o.documentation={...o.documentation||{},name:r,...e},o.route={path:n,method:"DELETE"},x.set(t,r,o),s};var No=(n,e)=>(t,r,s)=>{let o=x.get(t,r);return o||(o={middlewares:[],route:{path:n,method:"GET"}}),o.documentation={...o.documentation||{},name:r,...e},o.route={path:n,method:"GET"},x.set(t,r,o),s};var Io=(n,e)=>(t,r,s)=>{let o=x.get(t,r);return o||(o={middlewares:[],route:{path:n,method:"PATCH"}}),o.documentation={...o.documentation||{},name:r,...e},o.route={path:n,method:"PATCH"},x.set(t,r,o),s};var Uo=(n,e)=>(t,r,s)=>{let o=x.get(t,r);return o||(o={middlewares:[],route:{path:n,method:"POST"}}),o.documentation={...o.documentation||{},name:r,...e},o.route={path:n,method:"POST"},x.set(t,r,o),s};var Wo=(n,e)=>(t,r,s)=>{let o=x.get(t,r);return o||(o={middlewares:[],route:{path:n,method:"PUT"}}),o.documentation={...o.documentation||{},name:r,...e},o.route={path:n,method:"PUT"},x.set(t,r,o),s};var Zo=n=>(e,t,r)=>{if(typeof t>"u"){let o=x.get(e.prototype,"__class__");if(o||(o={middlewares:[]}),o.middlewares||(o.middlewares=[]),!n)throw new Error(`Middleware ${String(n)} not found, are you sure you defined it before using it?`);return Array.isArray(n)||(n=[n]),o.middlewares.push(...n),x.set(e.prototype,"__class__",o),e}let s=x.get(e,t);return s||(s={middlewares:[]}),s.middlewares||(s.middlewares=[]),Array.isArray(n)||(n=[n]),s.middlewares.push(...n),x.set(e,t,s),r};var N=class{static ajv=new Ajv({validateSchema:false,strict:false});static{this.ajv.addFormat("email",/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/),this.ajv.addFormat("url",/^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&\/=]*)$/),this.ajv.addFormat("date",/^\d{4}-\d{2}-\d{2}$/),this.ajv.addFormat("datetime",/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?(?:Z|[+-]\d{2}:\d{2})$/),this.ajv.addFormat("time",/^\d{2}:\d{2}:\d{2}$/),this.ajv.addFormat("binary",/^(?:[0-9a-fA-F]{2})+$/),this.ajv.addFormat("base64",/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/),this.ajv.addFormat("uuid",/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i);}static setGlobalInstance(e){this.ajv=e,this.ajv.opts.strict=false,this.ajv.opts.validateSchema=false;}};var $=new Map;var Ce=class{static typeboxModule=null;static loadPromise=null;static async load(){return this.typeboxModule?this.typeboxModule:this.loadPromise?this.loadPromise:(this.loadPromise=(async()=>{try{return this.typeboxModule=await import('@sinclair/typebox'),this.typeboxModule}catch{throw new Error(`TypeBox is not installed. Install it with: npm install @sinclair/typebox
2
+ TypeBox is a peer dependency required when using TypeBox schemas for validation.`)}})(),this.loadPromise)}static get(){if(!this.typeboxModule)throw new Error("TypeBox has not been loaded yet. Call TypeBoxLoader.load() first.");return this.typeboxModule}static isTypeBoxSchema(e){return typeof e=="object"&&e!==null&&"type"in e&&Object.getOwnPropertySymbols(e).some(t=>t.toString()==="Symbol(TypeBox.Kind)")}};var _=(n,e,t=false)=>{if(!n(e)){if(t)return e;throw new ValidationError(n.errors||[])}return e};var ee=class{static zodModule=null;static loadPromise=null;static async load(){return this.zodModule?this.zodModule:this.loadPromise?this.loadPromise:(this.loadPromise=(async()=>{try{return this.zodModule=await import('zod'),this.zodModule}catch{throw new Error(`Zod is not installed. Install it with: npm install zod
3
+ Zod is a peer dependency required when using Zod schemas for validation.`)}})(),this.loadPromise)}static get(){if(!this.zodModule)throw new Error("Zod has not been loaded yet. Call ZodLoader.load() first.");return this.zodModule}static isZodSchema(e){let t=typeof e=="object"&&e!==null&&"_def"in e&&typeof e.parse=="function"&&typeof e.safeParse=="function";if(t&&!("toJSONSchema"in e))throw new Error("Zod4 is required with the toJSONSchema() method in order to work. Install it with: npm install zod with minimum version 4.0.0");return t}};var Nt=Symbol("serializeWrapped"),je=Symbol("serializeMetadata"),qe=new WeakMap,un=(n,e)=>(t,r,s)=>{let o=x.get(t,r)||{middlewares:[],route:{}};o.documentation||(o.documentation={}),o.documentation.responses||(o.documentation.responses={}),o.serializeOptions||(o.serializeOptions={});let i=Number(e?.status??200);if(o.documentation.responses[i]=n,o.serializeOptions[i]=e?.safe??true,x.set(t,r,o),s.value[je]||(s.value[je]={}),s.value[je][i]={name:r,schema:n,safe:e?.safe??true},!s.value[Nt]){let a=s.value,c=async function(...p){let l=p[1];await a.apply(this,p);let d=l.responseStatus,g=c[je],f=g?.[d]?.schema,m=g?.[d]?.safe??true;if(f&&!m){let y=l.getBody();try{let S;if(ee.isZodSchema(f)){let v=qe.get(f);v||(v=Symbol("serialize_zod_schema"),qe.set(f,v));let C=$.get(v);if(!C){let M=f.toJSONSchema();C=N.ajv.compile(M),$.set(v,C);}await _(C,y,m),l.send(y);}else if(Ce.isTypeBoxSchema(f)){let v=qe.get(f);v||(v=Symbol("serialize_typebox_schema"),qe.set(f,v));let C=$.get(v);C||(C=N.ajv.compile(f),$.set(v,C)),await _(C,y,m),l.send(y);}else if(typeof f=="object"&&f!==null){let v=qe.get(f);v||(v=Symbol("serialize_json_schema"),qe.set(f,v));let C=$.get(v);C||(C=N.ajv.compile(f),$.set(v,C)),await _(C,y,m),l.send(y);}else {S=JSON.stringify(f);let v=$.get(S);v||(v=N.ajv.compile(f),$.set(S,v)),await _(v,y,m),l.send(y);}}catch(S){let v=await ee.load();if(S instanceof v.ZodError){l.internalServerError({received:y,schema:f,error:S});return}throw S}}};c[Nt]=true,c[je]=a[je],s.value=c;}};var me=n=>(e,t,r)=>{let s=r.value,o=x.get(e,t);return o||(o={middlewares:[],route:{}}),o.documentation||(o.documentation={}),n.body&&(o.documentation.requestBody=n.body),n.query&&(o.documentation.query=n.query),n.all&&(o.documentation.requestBody=n.body,o.documentation.query=n.query),x.set(e,t,o),r.value=async function(...i){let a=i[0],c=i[1];try{let p,l,d;n.body&&(p=a.validate(n.body,n.safe)),n.query&&(l=a.validateQuery(n.query,n.safe)),n.all&&(d=a.validateAll(n.all,n.safe));let g=[...i];return p!==void 0&&g.push(p),l!==void 0&&g.push(l),d!==void 0&&g.push(d),s.apply(this,g)}catch(p){let l=await ee.load();if(!(p instanceof l.ZodError))throw p;return n.customError?c.status(n.customError.status||400).json({received:a.parsedBody,schema:n.body,error:p}):c.badRequest(p)}},r};me.query=(n,e)=>me({query:n,customError:e});me.body=(n,e)=>me({body:n,customError:e});me.all=(n,e)=>me({all:n,customError:e});var fn=me;var _t=class{logger=b.child({scope:this.constructor.name})};var Dt=class{logger=b.child({scope:this.constructor.name})};var Wr=n=>{if(!Buffer.isBuffer(n))return n;let e=n.toString();if(!e.length)return e;try{let t=JSON.parse(e);return typeof t=="object"&&t!==null?t:e}catch{return e}},De=class n{static subscriptions=[];static client=null;static connectionOptions={};static register(e,t,r,s){this.subscriptions.push({name:e,topic:t,handler:r,options:s});}static async connect(e={}){let t=await import('mqtt').catch(()=>{throw new O("mqtt not installed as a dependency, it is required in order to use MQTT subscriptions with the @mqtt decorator")});this.connectionOptions=e,b.info("Starting MQTT client"),this.subscriptions.length||b.info("No MQTT subscriptions to register");let{host:r="localhost",port:s=1883,protocol:o="mqtt",...i}=e,a=`${o}://${r}:${s}`;this.client=await t.connectAsync(a,i),b.info("MQTT client connected"),this.client.on("error",async c=>{await this.globalErrorHandler(c);}),this.client.on("message",(c,p)=>{this.handleMessage(c,p);}),this.client.on("disconnect",()=>{b.info("MQTT client disconnected");}),this.client.on("reconnect",async()=>{await this.globalErrorHandler(new Error("MQTT client reconnecting"));}),this.subscribeToTopics();}static subscribeToTopics(){if(this.client)for(let{name:e,topic:t,options:r}of this.subscriptions)b.info(`Subscribing to MQTT topic: ${t} (${e})`),this.client.subscribe(t,r||{},s=>{if(s){b.error(`Failed to subscribe to topic ${t}: ${s.message}`);return}b.info(`Successfully subscribed to topic: ${t}`);});}static async handleMessage(e,t){let r=this.subscriptions.filter(s=>{if(s.topic===e)return true;if(!e||typeof e!="string")return false;let o=s.topic.replace(/\+/g,"[^/]+").replace(/#$/,".*");return new RegExp(`^${o}$`).test(e)});for(let s of r)try{await s.handler(e,t);}catch(o){b.error(`Error handling MQTT message for topic ${e} in ${s.name}`),this.globalErrorHandler(o);}}static globalErrorHandler(e){b.error(e);}static setOnDisconnectHandler(e){this.client?.on("disconnect",e);}static setOnReconnectHandler(e){this.client?.on("reconnect",e);}static async massiveImportMqttHandlers(e){let t=[];for(let r of e){let s=await glob(r,{absolute:true,cwd:B.getCwd()});t.push(...s);}await Promise.all(t.map(async r=>{await import(r).catch(s=>{b.error(`Error importing MQTT handler: ${r}`),b.error(s);});}));}subscribe(e,t){return function(r,s,o){let i=o.value;if(!i)return o;let a=async(c,p)=>{let l=new r.constructor,d=Wr(p);if(i.length===1){await i.call(l,d);return}await i.call(l,c,d);};return n.register(`${r.constructor.name}.${s}`,e,a,t),o}}async publish(e,t,r){if(!n.client)throw new O("MQTT client is not connected. Call MqttService.connect() first.");if(!n.client.connected)throw new O("MQTT client is not connected. Call MqttService.connect() first.");let s;Buffer.isBuffer(t)?s=t:typeof t=="object"?s=JSON.stringify(t):s=String(t);try{await n.client.publishAsync(e,s,r||{}),b.debug(`Published message to topic: ${String(e)}`);}catch(o){throw b.error(`Failed to publish to topic ${String(e)}: ${o.message}`),o}}static async disconnect(){if(this.client)return new Promise(e=>{this.client?.end(false,{},()=>{b.info("MQTT client disconnected gracefully"),this.client=null,e();});})}},On=n=>{De.globalErrorHandler=n.bind(De);},Cn=new De;var It=class{logger=b.child({scope:this.constructor.name})};var V=class{static options={connection:{}}},Ft=n=>{V.options=n??{connection:{}};};var z=class extends O{constructor(...e){super(`Library not installed: ${e.join(", ")}, try run npm install ${e.join(" ")}`);}};var wt=class{randomUUID(){return crypto.randomUUID()}},te=new wt;var Je=class{queues=new Map;workers=new Map;async publish(e,t,r){let s=await this.getQueue(e),o=te.randomUUID();return await s.add(e,t,{jobId:o,...V.options?.defaultJobOptions,...r}),{id:o}}async subscribe(e,t){if(this.workers.has(e))throw new Error(`[BullMQ] Already subscribed to topic "${e}"`);let{errorHandler:r,...s}=V.options??{},o=await this.getBullMQClient(),i=new o.Worker(e,async a=>{try{await t(a.data);}catch(c){await r?.(a,c)??Promise.reject(c);}},{...s});this.workers.set(e,i);}async getQueue(e){if(!this.queues.has(e)){let t=await import('bullmq').catch(()=>{throw new z("bullmq","ioredis")}),r=new t.Queue(e,{...V.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 z("bullmq","ioredis")})),this.bullmqClient}async publishWithConfig(e,t,r,s){let o=await this.getQueueWithConfig(e,s),i=te.randomUUID(),a={jobId:i,...V.options?.defaultJobOptions,...s?.defaultJobOptions,...r};return await o.add(e,t,a),{id:i}}async subscribeWithConfig(e,t,r){let s=this.getWorkerKey(e,r);if(this.workers.has(s))throw new Error(`[BullMQ] Already subscribed to topic "${e}"`);let o=V.options??{},{errorHandler:i}=o,a=await this.getBullMQClient(),c={...o,...r};delete c.errorHandler,delete c.defaultJobOptions;let p=new a.Worker(e,async l=>{try{await t(l.data);}catch(d){await i?.(l,d)??Promise.reject(d);}},c);this.workers.set(s,p);}async getQueueWithConfig(e,t){let r=this.getQueueKey(e,t);if(!this.queues.has(r)){let s=await import('bullmq').catch(()=>{throw new z("bullmq","ioredis")}),o={...V.options||{connection:{}},...t},i=new s.Queue(e,o);this.queues.set(r,i);}return this.queues.get(r)}getQueueKey(e,t){return t?.connection?`${e}:${JSON.stringify(t.connection)}`:e}getWorkerKey(e,t){return this.getQueueKey(e,t)}};var K=class{static options={}},Qt=n=>{K.options=n??{};};var Ye=class{createdQueues=new Set;async publish(e,t,r){let s=await this.getBoss();await this.ensureQueue(e);let o=r||{},i=await s.send(e,t,o);return {id:String(i??"")}}async subscribe(e,t){let r=await this.getBoss();await this.ensureQueue(e);let s=K.options;s.errorHandler&&r.on("error",s.errorHandler),await r.work(e,async o=>{let i=Array.isArray(o)?o:[o];for(let a of i)await t(a.data);});}async getBoss(){if(this.boss)return this.boss;let e=await import('pg-boss').catch(()=>{throw new z("pg-boss","pg")}),r=e.PgBoss.default??e.PgBoss,{connectionString:s,boss:o}=K.options,i=s??o,a=new r(i);return K.options?.errorHandler&&a.on("error",K.options.errorHandler),await a.start(),this.boss=a,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);}async publishWithConfig(e,t,r,s){let o=await this.getBossWithConfig(s);await this.ensureQueueWithBoss(e,o);let i=r||{},a=await o.send(e,t,i);return {id:String(a??"")}}async subscribeWithConfig(e,t,r){let s=await this.getBossWithConfig(r);await this.ensureQueueWithBoss(e,s);let o=K.options;o.errorHandler&&s.on("error",o.errorHandler),await s.work(e,async i=>{let a=Array.isArray(i)?i:[i];for(let c of a)await t(c.data);});}bossInstances=new Map;async getBossWithConfig(e){if(!e?.connectionString)return this.getBoss();let t=e.connectionString;if(this.bossInstances.has(t))return this.bossInstances.get(t);let r=await import('pg-boss').catch(()=>{throw new z("pg-boss","pg")}),o=r.PgBoss.default??r.PgBoss,i=new o(e.connectionString);return K.options?.errorHandler&&i.on("error",K.options.errorHandler),await i.start(),this.bossInstances.set(t,i),i}async ensureQueueWithBoss(e,t){this.createdQueues.has(e)||(typeof t.createQueue=="function"&&await t.createQueue(e),this.createdQueues.add(e));}};var ne=class{static options={}},Ut=n=>{ne.options=n??{};};var Xe=class{consumers=new Map;client;async publish(e,t,r){let s=await this.getClient(),{SendMessageCommand:o}=await this.getSqsLib(),i=await this.resolveQueueUrl(e);if(!i)throw new Error(`[SQS] Queue url not configured for topic "${e}"`);let a=new o({MessageBody:JSON.stringify(t),MessageAttributes:{topic:{DataType:"String",StringValue:e}},QueueUrl:i,...r??{}});return {id:(await s.send(a)).MessageId??""}}async subscribe(e,t){if(this.consumers.has(e))throw new Error(`[SQS] Already subscribed to topic "${e}"`);let r=ne.options,s=await this.getSqsConsumerLib(),o={...r.consumer||{},sqs:await this.getClient(),queueUrl:await this.resolveQueueUrl(e),handleMessage:async c=>{let p=JSON.parse(c.Body||"{}");await t(p);}},i=s.Consumer.create(o),a=r.errorHandler;a&&(i.on("error",a),i.on("processing_error",a)),i.start(),this.consumers.set(e,i);}async getClient(){if(this.client)return this.client;let{SQSClient:e}=await this.getSqsLib(),t=ne.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 z("@aws-sdk/client-sqs","sqs-consumer")})),this.sqsLib}async getSqsConsumerLib(){return this.sqsConsumerLib||(this.sqsConsumerLib=await import('sqs-consumer').catch(()=>{throw new z("sqs-consumer")})),this.sqsConsumerLib}async resolveQueueUrl(e){let r=ne.options.consumer?.queueUrlMap;if(!r?.[e])throw new Error(`[SQS] Queue url not configured for topic "${e}"`);return r[e]}async publishWithConfig(e,t,r,s){let{...o}=r??{},i=await this.getClientWithConfig(s?.client),{SendMessageCommand:a}=await this.getSqsLib(),c=s?.queueUrl??await this.resolveQueueUrl(e),p=new a({...o,MessageBody:JSON.stringify(t),MessageAttributes:{topic:{DataType:"String",StringValue:e}},QueueUrl:c});return {id:(await i.send(p)).MessageId??""}}async subscribeWithConfig(e,t,r){if(this.consumers.has(e))throw new Error(`[SQS] Already subscribed to topic "${e}"`);let s=ne.options,o=await this.getSqsConsumerLib(),i=r?.queueUrl??await this.resolveQueueUrl(e),a={...s.consumer||{},sqs:await this.getClientWithConfig(r?.client),queueUrl:i,handleMessage:async l=>{let d=JSON.parse(l.Body||"{}");await t(d);}},c=o.Consumer.create(a),p=s.errorHandler;p&&(c.on("error",p),c.on("processing_error",p)),c.start(),this.consumers.set(e,c);}async getClientWithConfig(e){if(e){let{SQSClient:t}=await this.getSqsLib();return new t(e)}return this.getClient()}};var re=class{static map=new Map;static{this.map.set("bullmq",new Je),this.map.set("sqs",new Xe),this.map.set("pgboss",new Ye);}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 he=class{static typedQueueSubscribers=new Map;static customQueueSubscribers=new Map;static instanceFactory=e=>new e;static registerTypedQueue(e,t,r,s,o){let i=`${s}:${t}:${e}`;this.typedQueueSubscribers.has(i)&&b.warn(`Queue handler for ${i} already registered, overwriting previous handler`),this.typedQueueSubscribers.set(i,{name:e,topic:t,handler:r,provider:s,queueOptions:o});}static registerCustomQueue(e,t,r,s){let o=`${s.constructor.name}:${t}:${e}`;this.customQueueSubscribers.has(o)&&b.warn(`Custom queue handler for ${o} already registered, overwriting previous handler`),this.customQueueSubscribers.set(o,{name:e,topic:t,handler:r,pubsub:s});}static async run(){b.info("Subscribing queue handlers");let e=this.typedQueueSubscribers.size>0,t=this.customQueueSubscribers.size>0;if(!e&&!t){b.info("No queue handlers to subscribe");return}for(let r of this.typedQueueSubscribers.values()){let{topic:s,handler:o,provider:i,queueOptions:a}=r;b.info(`Subscribing to queue: ${s}`);let c=re.getProvider(i);a&&"subscribeWithConfig"in c&&typeof c.subscribeWithConfig=="function"?await c.subscribeWithConfig(s,o,a):await c.subscribe(s,o);}for(let{topic:r,handler:s,pubsub:o}of this.customQueueSubscribers.values())b.info(`Subscribing to custom queue: ${r}`),await o.subscribe(r,s);b.info("Queue handlers subscribed");}static async massiveImportQueues(e,t={}){let r=[];for(let s of e){let o=await glob(s,{absolute:true,cwd:B.getCwd()});r.push(...o);}await Promise.all(r.map(async s=>{await import(s).catch(o=>{if(b.error(`Error importing queue handler: ${s}`),b.error(o),t.throwOnError)throw o});}));}};var et=new WeakMap,ge=class{constructor(e,t,r){this.topic=e;this.provider=t;this.queueOptions=r;}async publish(e,t){let r=re.getProvider(this.provider);return this.queueOptions?r.publishWithConfig(this.topic,e,t,this.queueOptions):r.publish(this.topic,e,t??{})}subscribe(e){return e?this.subscribeWithCallback(e):this.createSubscribeDecorator()}createSubscribeDecorator(){let e=this.topic,t=this.provider,r=this.queueOptions;return function(s,o,i){let a=i.value,c=async p=>{let l=et.get(s.constructor);return l||(l=he.instanceFactory(s.constructor),et.set(s.constructor,l)),a.apply(l,[p])};return he.registerTypedQueue(`${s.constructor.name}.${String(o)}`,e,c,t,r),i}}async subscribeWithCallback(e){let t=re.getProvider(this.provider);return this.queueOptions?t.subscribeWithConfig(this.topic,e,this.queueOptions):t.subscribe(this.topic,e)}},Ie=class{constructor(e,t){this.topic=e;this.pubsub=t;}async publish(e,t){return this.pubsub.publish(this.topic,e,t)}subscribe(e){return e?this.pubsub.subscribe(this.topic,e):this.createSubscribeDecorator()}createSubscribeDecorator(){let e=this.topic,t=this.pubsub;return function(r,s,o){let i=o.value,a=async c=>{let p=et.get(r.constructor);return p||(p=he.instanceFactory(r.constructor),et.set(r.constructor,p)),i.apply(p,[c])};return he.registerCustomQueue(`${r.constructor.name}.${String(s)}`,e,a,t),o}}};function Vr(n,e){return new ge(n,"sqs",e)}function Zr(n,e){return new ge(n,"bullmq",e)}function Jr(n,e){return new ge(n,"pgboss",e)}function Yr(n,e){return new Ie(n,e)}var di=n=>{let e=["bullmq","pgboss","sqs"];n.bullmq&&Ft(n.bullmq),n.pgboss&&Qt(n.pgboss),n.sqs&&Ut(n.sqs);for(let t of Object.keys(n)){let r=t;e.includes(r)||re.setProvider(r,n[r]);}};U();var bt=class{exit(e){switch(T.type){case "bun":case "node":process.exit(e);case "deno":Deno.exit(e);default:throw new Error("Unsupported runtime")}}},St=new bt;var q=class{static commandName=this.name;static calledBy=this.name;static description="";static help=[];static options={keepAlive:false};static args=de().args.slice(1);static flags=de().flags;static logger=b;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(p=>t.includes(p)))return;let s=this.commandName,o=this.description||"No description available",i=this.help||[],a=this.options,c=this.generateHelpOutput({name:s,description:o,helpText:i,options:a,args:this.args,flags:this.flags},this);console.log(c),St.exit(0);}static generateHelpOutput=(e,t)=>{let{name:r,description:s,helpText:o,options:i,args:a,flags:c}=e,p={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"},l=[`${p.title}${r}${p.reset}`,`${p.description}${s}${p.reset}`,"",`${p.subtitle}Usage:${p.reset}`,` ${p.code}${r}${p.reset} [options] [arguments]`,"",`${p.subtitle}Options:${p.reset}`,` ${p.flag}-h, --help${p.reset} Show this help message`,"",`${p.subtitle}Command Options:${p.reset}`,` ${p.flag}keepAlive${p.reset} ${i?.keepAlive??false?p.success+"Enabled"+p.reset:p.error+"Disabled"+p.reset}`,""];if(o){let m=Array.isArray(o)?o:[o];l.push(`${p.subtitle}Help:${p.reset}`),m.forEach(y=>{l.push(` ${p.description}${y}${p.reset}`);}),l.push("");}let d=x.getAll(t),g=Array.from(d.values()).filter(m=>m.type==="arg"),f=Array.from(d.values()).filter(m=>m.type==="flag");return g.length&&(l.push(`${p.subtitle}Available Arguments:${p.reset}`),g.forEach(m=>{let y=m.required?` ${p.error}(required)${p.reset}`:"",S=m.description?` ${p.description}${m.description}${p.reset}`:"";l.push(` ${p.code}${m.name}${p.reset}${y}${S}`);}),l.push("")),f.length&&(l.push(`${p.subtitle}Available Flags:${p.reset}`),f.forEach(m=>{m.aliases&&!Array.isArray(m.aliases)&&(m.aliases=[m.aliases]);let y=m.aliases.length?` ${p.flag}(${m.aliases.join(", ")})${p.reset}`:"",S=m.required?` ${p.error}(required)${p.reset}`:"",v=m.description?` ${p.description}${m.description}${p.reset}`:"";l.push(` ${p.flag}--${m.name}${y}${p.reset}${S}${v}`);}),l.push("")),((a?.length??0)>0||c&&Object.keys(c).length>0)&&(l.push(`${p.subtitle}Current Context:${p.reset}`),a?.length&&l.push(` ${p.info}Provided Arguments:${p.reset} ${p.code}${a.join(" ")}${p.reset}`),c&&Object.keys(c).length>0&&(l.push(` ${p.info}Provided Flags:${p.reset}`),Object.keys(c).forEach(m=>{let y=c[m],S=y!=null?` = ${p.code}${y}${p.reset}`:"";l.push(` ${p.flag}${m}${p.reset}${S}`);})),l.push("")),o&&(Array.isArray(o)?o.some(m=>m.includes("example")):o.includes("example"))&&(l.push(`${p.subtitle}Examples:${p.reset}`),(Array.isArray(o)?o.filter(y=>y.includes("example")):[o.split("example")[1].trim()]).forEach(y=>{l.push(` ${p.code}${y}${p.reset}`);}),l.push("")),l.join(`
4
+ `)};static validateContext=e=>{let t=Array.from(x.get(e,ue)||[]);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((s,o)=>{let i=`${r.info}${o+1}.${r.reset}`,a=`${r.error}${s.type.toUpperCase()}${r.reset}`,c=`${r.code}${s.name}${r.reset}`;console.error(` ${i} ${a} ${c}: ${r.error}${s.message}${r.reset}`);}),console.error(""),console.error(`${r.info}\u{1F4A1} Tip: Use --help for usage information${r.reset}`),St.exit(1);}}};U();var xt=class{async mkdir(e,t){switch(T.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(T.type){case "node":return (await import('fs')).existsSync(e);case "bun":return (await import('fs')).existsSync(e);case "deno":return Deno.stat(e).then(()=>true).catch(()=>false);default:throw new Error("Unsupported runtime")}}async readFile(e,t){switch(T.type){case "node":let s=await(await import('fs/promises')).readFile(e,{encoding:t?.encoding??null});return t?.encoding==="utf8"?s:new Uint8Array(s);case "bun":let o=Bun.file(e);return t?.encoding==="utf8"?o.text():new Uint8Array(await o.arrayBuffer());case "deno":let i=await Deno.readFile(e);return t?.encoding==="utf8"?new TextDecoder().decode(i):new Uint8Array(i)}}async writeFile(e,t){switch(T.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(T.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(await import('fs/promises')).stat(e);return {isDirectory:o.isDirectory(),isFile:o.isFile(),isSymbolicLink:o.isSymbolicLink(),size:o.size};case "deno":let i=await Deno.stat(e);return {isDirectory:i.isDirectory,isFile:i.isFile,isSymbolicLink:false,size:i.size}}}async unlink(e){switch(T.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")}}async streamFile(e){switch(T.type){case "node":let t=await import('fs'),{Readable:r}=await import('stream'),s=t.createReadStream(e);return r.toWeb(s);case "bun":return Bun.file(e).stream();case "deno":return (await Deno.open(e)).readable;default:throw new Error("Unsupported runtime")}}async readdir(e){switch(T.type){case "bun":case "node":return (await import('fs/promises')).readdir(e);case "deno":let r=[];for await(let s of Deno.readDir(e))r.push(s.name);return r;default:throw new Error("Unsupported runtime")}}},u=new xt;var Ee=async n=>{let e=h.join(process.cwd(),"node_modules");if(!await u.exists(e))return n;let r=[];for(let s of n){let o=h.join(e,s);await u.exists(o)||r.push(s);}return r},G=async()=>await u.exists(h.join(process.cwd(),"yarn.lock"))?["yarn","add","-D"]:await u.exists(h.join(process.cwd(),"pnpm-lock.yaml"))?["pnpm","add","-D"]:await u.exists(h.join(process.cwd(),"package-lock.json"))?["npm","install","-D"]:await u.exists(h.join(process.cwd(),"bun.lockb"))?["bun","add","-D"]:await u.exists(h.join(process.cwd(),"deno.lock"))?["deno","add","-D"]:["npm","install","-D"],D=async(n,e,t,r,s=true)=>{let o=zt.createInterface({input:process.stdin,output:process.stdout}),i=t.join(", "),a=`Do you want to install the following ${s?"dev":""} dependencies using ${e}?
5
+ ${i}
6
+ (y/n): `;return new Promise(c=>{o.question(a,p=>{if(o.close(),p.toLowerCase()==="y"||p.toLowerCase()==="yes"){execSync(n,r),c(true);return}c(false);});})};var F=class extends q{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(){if(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)),!await import('esbuild').then(a=>true).catch(()=>false)){let[a,c,p]=await G();await D(`${a} ${c} esbuild ${p}`,a,["esbuild"],{stdio:"inherit"})||(this.logger.warn("User chose to not continue with the installation of esbuild, exiting..."),process.exit(0));}let t=await import('esbuild').catch(a=>{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")}),r=Ze.join(this.output,"assets"),s=[];if(this.assets){let{copy:a}=await import('esbuild-plugin-copy').catch(c=>{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")});tt.existsSync(r)||tt.mkdirSync(r,{recursive:true}),s.push(a({assets:{from:this.assets,to:r}}));}this.clearDist&&tt.existsSync(this.output)&&(this.logger.info("Clearing dist directory..."),tt.rmSync(this.output,{recursive:true})),this.logger.info("Building project...");let o=Ze.join(this.output,"server.js"),i=await t.build({tsconfig:this.tsconfig,entryPoints:[this.entry],bundle:true,platform:"node",outfile:o,minify:true,sourcemap:this.sourcemap,plugins:s,format:this.format,packages:this.packages});i.errors.length&&(this.logger.error(JSON.stringify({message:"Failed to build the project",errors:i.errors},null,2)),process.exit(1)),i.warnings.length&&this.logger.warn(JSON.stringify({message:"Failed to build the project",warnings:i.warnings},null,2)),this.logger.info(JSON.stringify({message:`Project built successfully in ${o}`,output:o,assets:!!this.assets},null,2)),process.exit(0);}};w([R({type:"boolean",aliases:["c"],name:"clear-dist",required:false,defaultValue:false,description:"Whether to clear the dist directory before building the project"})],F,"clearDist"),w([R({type:"string",aliases:["e"],name:"entry",required:false,defaultValue:"./src/index.ts",description:"The entry point of the project, default is ./src/index.ts"})],F,"entry"),w([R({type:"string",aliases:["o"],name:"output",required:false,defaultValue:"./dist",description:"The path to the output directory, default is ./dist"})],F,"output"),w([R({type:"string",aliases:["t"],name:"tsconfig",required:false,defaultValue:"./tsconfig.json",description:"The path to the tsconfig.json file, default is ./tsconfig.json"})],F,"tsconfig"),w([R({type:"string",aliases:["a"],name:"assets",required:false,description:"The path to the assets directory that will be loaded in the production build"})],F,"assets"),w([R({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'"})],F,"format"),w([R({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'"})],F,"packages"),w([R({type:"boolean",aliases:["s"],name:"sourcemap",required:false,defaultValue:true,description:"Whether to generate sourcemaps or not, default is true"})],F,"sourcemap");var Me=class extends q{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(){if(Ae.getCommand(this.name)){let s=Ae.isBuiltInCommand(this.name)?"built-in":"user-defined";this.logger.error({commandName:this.name,type:s},`Command "${this.name}" already exists as a ${s} command. Cannot override existing commands.`);return}let t=this.getCommandTemplate();this.path=h.join(this.path,`${this.name}.ts`),await u.exists(h.join(process.cwd(),this.path))||await u.mkdir(h.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await u.writeFile(this.path,new TextEncoder().encode(t)),this.logger.info(`Command ${this.name} created successfully at ${this.path}`);}static getCommandTemplate(){return `import { Command, CommandOptions } from "balda";
7
7
 
8
8
  export default class extends Command {
9
9
  static commandName = "${this.name}";
@@ -17,9 +17,9 @@ export default class extends Command {
17
17
  static async handle(): Promise<void> {
18
18
  // Implement your command logic here
19
19
  }
20
- }`}};y([A({description:"The name of the command to generate",required:true})],Ee,"name");var me=class extends j{static commandName="generate-controller";static description="Generate a new controller in the specified path";static help=["Generate a new controller in the specified path","Example: npx balda generate-controller user -p src/controllers"];static controllerName;static path;static async handle(){let e=this.getControllerTemplate(),t=`${this.controllerName.toLowerCase()}.ts`;this.path=g.join(this.path,t),await u.exists(g.join(process.cwd(),this.path))||await u.mkdir(g.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await u.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Controller ${this.controllerName} created successfully at ${this.path}`);}static getControllerTemplate(){let e=ze(this.controllerName);return `import { controller, get, post, put, del, Request, Response } from "balda";
20
+ }`}};w([k({description:"The name of the command to generate",required:true})],Me,"name");var fe=class extends q{static commandName="generate-controller";static description="Generate a new controller in the specified path";static help=["Generate a new controller in the specified path","Example: npx balda generate-controller user -p src/controllers"];static controllerName;static path;static async handle(){let e=this.getControllerTemplate(),t=`${this.controllerName.toLowerCase()}.ts`;this.path=h.join(this.path,t),await u.exists(h.join(process.cwd(),this.path))||await u.mkdir(h.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await u.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Controller ${this.controllerName} created successfully at ${this.path}`);}static getControllerTemplate(){let e=Ke(this.controllerName);return `import { controller, get, post, put, del, Request, Response } from "balda";
21
21
 
22
- @controller("/${$t(this.controllerName)}")
22
+ @controller("/${Bt(this.controllerName)}")
23
23
  export default class ${e}Controller {
24
24
  @get("/")
25
25
  async index(req: Request, res: Response) {
@@ -33,19 +33,19 @@ export default class ${e}Controller {
33
33
 
34
34
  @post("/")
35
35
  async create(req: Request, res: Response) {
36
- return { message: \`Create ${this.controllerName.toLowerCase()}\`, data: req.body };
36
+ return { message: \`Create ${this.controllerName.toLowerCase()}\`, data: req.parsedBody };
37
37
  }
38
38
 
39
39
  @put("/:id")
40
40
  async update(req: Request, res: Response) {
41
- return { message: \`Update ${this.controllerName.toLowerCase()} with id \${req.params.id}\`, data: req.body };
41
+ return { message: \`Update ${this.controllerName.toLowerCase()} with id \${req.params.id}\`, data: req.parsedBody };
42
42
  }
43
43
 
44
44
  @del("/:id")
45
45
  async destroy(req: Request, res: Response) {
46
46
  return { message: \`Delete ${this.controllerName.toLowerCase()} with id \${req.params.id}\` };
47
47
  }
48
- }`}};y([A({description:"The name of the controller to generate",required:true})],me,"controllerName"),y([x({description:"The path to the controller to generate, default is src/controllers",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/controllers"})],me,"path");var he=class extends j{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=g.join(this.path,`${this.fileName}.ts`),await u.exists(g.join(process.cwd(),this.path))||await u.mkdir(g.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await u.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Cron job ${this.fileName} created successfully at ${this.path}`);}static getCronTemplate(){return `import { BaseCron, cron } from "balda";
48
+ }`}};w([k({description:"The name of the controller to generate",required:true})],fe,"controllerName"),w([R({description:"The path to the controller to generate, default is src/controllers",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/controllers"})],fe,"path");var ye=class extends q{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=h.join(this.path,`${this.fileName}.ts`),await u.exists(h.join(process.cwd(),this.path))||await u.mkdir(h.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await u.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Cron job ${this.fileName} created successfully at ${this.path}`);}static getCronTemplate(){return `import { BaseCron, cron } from "balda";
49
49
 
50
50
  export default class extends BaseCron {
51
51
  @cron("* * * * *")
@@ -53,7 +53,7 @@ export default class extends BaseCron {
53
53
  this.logger.info("Running cron job");
54
54
  // Implement your cron job logic here
55
55
  }
56
- }`}};y([A({description:"The name of the cron job file to generate",required:true})],he,"fileName"),y([x({description:"The path to the cron job to generate, default is src/cron",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/cron"})],he,"path");var ge=class extends j{static commandName="generate-middleware";static description="Generate a new middleware in the specified path";static help=["Generate a new middleware in the specified path","Example: npx balda generate-middleware auth -p src/middlewares"];static middlewareName;static path;static async handle(){let e=this.getMiddlewareTemplate(),t=`${this.middlewareName.toLowerCase()}.ts`;this.path=g.join(this.path,t),await u.exists(g.join(process.cwd(),this.path))||await u.mkdir(g.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await u.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Middleware ${this.middlewareName} created successfully at ${this.path}`);}static getMiddlewareTemplate(){let e=ze(this.middlewareName);return `import type { Request, Response, NextFunction, ServerRouteMiddleware } from "balda";
56
+ }`}};w([k({description:"The name of the cron job file to generate",required:true})],ye,"fileName"),w([R({description:"The path to the cron job to generate, default is src/cron",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/cron"})],ye,"path");var ve=class extends q{static commandName="generate-middleware";static description="Generate a new middleware in the specified path";static help=["Generate a new middleware in the specified path","Example: npx balda generate-middleware auth -p src/middlewares"];static middlewareName;static path;static async handle(){let e=this.getMiddlewareTemplate(),t=`${this.middlewareName.toLowerCase()}.ts`;this.path=h.join(this.path,t),await u.exists(h.join(process.cwd(),this.path))||await u.mkdir(h.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await u.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Middleware ${this.middlewareName} created successfully at ${this.path}`);}static getMiddlewareTemplate(){let e=Ke(this.middlewareName);return `import type { Request, Response, NextFunction, ServerRouteMiddleware } from "balda";
57
57
 
58
58
  /**
59
59
  * ${e} middleware
@@ -64,7 +64,7 @@ export const ${e}: ServerRouteMiddleware = async () => {
64
64
  // Add your middleware logic here
65
65
  return next();
66
66
  };
67
- };`}};y([A({description:"The name of the middleware to generate",required:true})],ge,"middlewareName"),y([x({description:"The path to the middleware to generate, default is src/middlewares",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/middlewares"})],ge,"path");var fe=class extends j{static commandName="generate-mqtt";static description="Generate a new MQTT handler in the specified path";static help=["Generate a new MQTT handler in the specified path","Example: npx balda generate-mqtt temperature-handler -p src/mqtt"];static path;static topic;static async handle(){let e=this.topic.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/),t=this.getMqttTemplate(!!e);this.path=g.join(this.path,`${Ue(this.topic.replace(/\//g,"_"))}.ts`),await u.exists(g.join(process.cwd(),this.path))||await u.mkdir(g.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await u.writeFile(this.path,new TextEncoder().encode(t)),this.logger.info(`MQTT handler for topic ${this.topic} created successfully at ${this.path}`);}static getMqttTemplate(e){return `import { BaseMqtt, mqtt } from "balda";
67
+ };`}};w([k({description:"The name of the middleware to generate",required:true})],ve,"middlewareName"),w([R({description:"The path to the middleware to generate, default is src/middlewares",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/middlewares"})],ve,"path");var we=class extends q{static commandName="generate-mqtt";static description="Generate a new MQTT handler in the specified path";static help=["Generate a new MQTT handler in the specified path","Example: npx balda generate-mqtt temperature-handler -p src/mqtt"];static path;static topic;static async handle(){let e=this.topic.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/),t=this.getMqttTemplate(!!e);this.path=h.join(this.path,`${We(this.topic.replace(/\//g,"_"))}.ts`),await u.exists(h.join(process.cwd(),this.path))||await u.mkdir(h.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await u.writeFile(this.path,new TextEncoder().encode(t)),this.logger.info(`MQTT handler for topic ${this.topic} created successfully at ${this.path}`);}static getMqttTemplate(e){return `import { BaseMqtt, mqtt } from "balda";
68
68
 
69
69
  /**
70
70
  * Define your MQTT topics interface for type safety
@@ -81,7 +81,7 @@ export default class extends BaseMqtt {
81
81
  this.logger.info({ message }, "Message received");
82
82
  // Implement your MQTT handler logic here
83
83
  }
84
- }`}};y([x({description:"The path to the MQTT handler to generate, default is src/mqtt",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/mqtt"})],fe,"path"),y([A({description:"The MQTT topic to subscribe to",required:true})],fe,"topic");var ye=class extends j{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=g.join(this.pluginPath,`${this.pluginName}.ts`),await u.exists(g.join(process.cwd(),this.pluginPath))||await u.mkdir(g.join(process.cwd(),this.pluginPath.split("/").slice(0,-1).join("/")),{recursive:true}),await u.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";
84
+ }`}};w([R({description:"The path to the MQTT handler to generate, default is src/mqtt",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/mqtt"})],we,"path"),w([k({description:"The MQTT topic to subscribe to",required:true})],we,"topic");var be=class extends q{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=h.join(this.pluginPath,`${this.pluginName}.ts`),await u.exists(h.join(process.cwd(),this.pluginPath))||await u.mkdir(h.join(process.cwd(),this.pluginPath.split("/").slice(0,-1).join("/")),{recursive:true}),await u.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";
85
85
 
86
86
  export default class extends BasePlugin {
87
87
  async handle(): Promise<ServerRouteMiddleware> {
@@ -90,7 +90,7 @@ export default class extends BasePlugin {
90
90
  await next();
91
91
  };
92
92
  }
93
- }`}};y([A({description:"The name of the plugin to generate",required:true})],ye,"pluginName"),y([x({description:"The path to the plugin to generate, default is src/plugins",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/plugins"})],ye,"pluginPath");var oe=class extends j{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=g.join(this.path,`${Ue(this.queueName)}.ts`),await u.exists(g.join(process.cwd(),this.path))||await u.mkdir(g.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await u.writeFile(this.path,new TextEncoder().encode(t)),this.logger.info(`Queue ${this.queueName} created successfully at ${this.path}`);}static getQueueTemplate(e){return `import { BaseQueue, queue } from "balda";
93
+ }`}};w([k({description:"The name of the plugin to generate",required:true})],be,"pluginName"),w([R({description:"The path to the plugin to generate, default is src/plugins",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/plugins"})],be,"pluginPath");var ie=class extends q{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=h.join(this.path,`${We(this.queueName)}.ts`),await u.exists(h.join(process.cwd(),this.path))||await u.mkdir(h.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await u.writeFile(this.path,new TextEncoder().encode(t)),this.logger.info(`Queue ${this.queueName} created successfully at ${this.path}`);}static getQueueTemplate(e){return `import { BaseQueue, queue } from "balda";
94
94
 
95
95
  export type Payload = {
96
96
  // Add your payload here
@@ -109,31 +109,33 @@ export default class extends BaseQueue {
109
109
  this.logger.info({ payload }, 'Payload received');
110
110
  return Promise.resolve();
111
111
  }
112
- }`}};y([A({description:"The name of the queue to generate",required:true})],oe,"queueName"),y([x({description:"The path to the queue to generate, default is src/queues",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/queues"})],oe,"path"),y([x({description:"The provider of the queue to generate, default is bullmq",type:"string",aliases:["pr"],name:"provider",required:false,defaultValue:"bullmq"})],oe,"provider");var H=class extends j{static commandName="generate-sdk";static description="Generate a TypeScript SDK from your server's OpenAPI specification";static help=["Generate a TypeScript SDK from your server's OpenAPI specification","This command imports your server instance, starts it if needed, downloads the OpenAPI spec, and generates an SDK","","Arguments:"," serverPath Path to the server instance file (default: test/server/instance.ts)","","Flags:"," -o, --output <path> Output directory for generated SDK (default: sdk)"," -s, --swagger-path <path> Swagger UI path on your server (default: /docs)"," -c, --client <type> HTTP client to use: axios or fetch (default: fetch)"," --unwrap-response-data Automatically unwrap response data property"," --single-http-client Generate single HTTP client instance"," --type-prefix <prefix> Add prefix to all generated types"," --type-suffix <suffix> Add suffix to all generated types"," --enum-names-as-values Use enum names as values"," --sort-types Sort types alphabetically","","Examples:"," npx balda generate-sdk"," npx balda generate-sdk src/server/index.ts -o ./client-sdk"," npx balda generate-sdk src/server.ts --client axios"," npx balda generate-sdk --unwrap-response-data --single-http-client"," npx balda generate-sdk --type-prefix Api --sort-types"];static serverPath;static outputPath;static swaggerPath;static httpClient;static unwrapResponseData;static singleHttpClient;static typePrefix;static typeSuffix;static enumNamesAsValues;static sortTypes;static async handle(){console.log(`
112
+ }`}};w([k({description:"The name of the queue to generate",required:true})],ie,"queueName"),w([R({description:"The path to the queue to generate, default is src/queues",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/queues"})],ie,"path"),w([R({description:"The provider of the queue to generate, default is bullmq",type:"string",aliases:["pr"],name:"provider",required:false,defaultValue:"bullmq"})],ie,"provider");var H=class extends q{static commandName="generate-sdk";static description="Generate a TypeScript SDK from your server's OpenAPI specification";static help=["Generate a TypeScript SDK from your server's OpenAPI specification","This command imports your server instance, starts it if needed, downloads the OpenAPI spec, and generates an SDK","","Arguments:"," serverPath Path to the server instance file (default: test/server/instance.ts)","","Flags:"," -o, --output <path> Output directory for generated SDK (default: sdk)"," -s, --swagger-path <path> Swagger UI path on your server (default: /docs)"," -c, --client <type> HTTP client to use: axios or fetch (default: fetch)"," --unwrap-response-data Automatically unwrap response data property"," --single-http-client Generate single HTTP client instance"," --type-prefix <prefix> Add prefix to all generated types"," --type-suffix <suffix> Add suffix to all generated types"," --enum-names-as-values Use enum names as values"," --sort-types Sort types alphabetically","","Examples:"," npx balda generate-sdk"," npx balda generate-sdk src/server/index.ts -o ./client-sdk"," npx balda generate-sdk src/server.ts --client axios"," npx balda generate-sdk --unwrap-response-data --single-http-client"," npx balda generate-sdk --type-prefix Api --sort-types"];static serverPath;static outputPath;static swaggerPath;static httpClient;static unwrapResponseData;static singleHttpClient;static typePrefix;static typeSuffix;static enumNamesAsValues;static sortTypes;static async handle(){console.log(`
113
113
  \u{1F680} Starting SDK generation...
114
- `);let e="swagger-typescript-api",t=g.join(process.cwd(),"node_modules"),r=await u.exists(t),s=g.join(t,e);if(!(r?await u.exists(s):false)){console.log(`\u{1F4E6} ${e} not found. Installing as dev dependency...
115
- `);let[S,O,B]=await z();if(!await _(`${S} ${O} ${e} ${B}`,S,[e],{stdio:"inherit"},true)){console.log(`\x1B[33m\u26A0\uFE0F SDK generation cancelled: swagger-typescript-api installation was skipped.\x1B[0m
114
+ `);let e="swagger-typescript-api",t=h.join(process.cwd(),"node_modules"),r=await u.exists(t),s=h.join(t,e);if(!(r?await u.exists(s):false)){console.log(`\u{1F4E6} ${e} not found. Installing as dev dependency...
115
+ `);let[P,E,L]=await G();if(!await D(`${P} ${E} ${e} ${L}`,P,[e],{stdio:"inherit"},true)){console.log(`\x1B[33m\u26A0\uFE0F SDK generation cancelled: swagger-typescript-api installation was skipped.\x1B[0m
116
116
  `);return}console.log(`
117
117
  \x1B[32m\u2705 ${e} installed successfully!\x1B[0m
118
- `);}let n=g.resolve(process.cwd(),this.serverPath);if(!await u.exists(n)){console.error(`\x1B[31m\u274C Error: Server file not found at ${n}\x1B[0m
119
- `);return}console.log(`\u{1F4C2} Loading server from: ${this.serverPath}`);let c;try{c=await import(`file://${n}`);}catch(S){console.error("\x1B[31m\u274C Error importing server module:\x1B[0m",S);return}let p=Object.keys(c),l=null;for(let S of p){let O=c[S];if("default"in O&&O.default&&(O=O.default),O&&"_brand"in O&&O._brand==="BaldaServer"&&typeof O=="object"&&"listen"in O){l=O,console.log(`\u2705 Found server instance in export: "${S}"
118
+ `);}let i=h.resolve(process.cwd(),this.serverPath);if(!await u.exists(i)){console.error(`\x1B[31m\u274C Error: Server file not found at ${i}\x1B[0m
119
+ `);return}console.log(`\u{1F4C2} Loading server from: ${this.serverPath}`);let c;try{c=await import(`file://${i}`);}catch(P){console.error("\x1B[31m\u274C Error importing server module:\x1B[0m",P);return}let p=Object.keys(c),l=null;for(let P of p){let E=c[P];if("default"in E&&E.default&&(E=E.default),E&&"_brand"in E&&E._brand==="BaldaServer"&&typeof E=="object"&&"listen"in E){l=E,console.log(`\u2705 Found server instance in export: "${P}"
120
120
  `);break}}if(!l){console.error(`\x1B[31m\u274C Error: No Server instance found in ${this.serverPath}\x1B[0m`),console.log(`\x1B[90mExpected exports: ${p.join(", ")}\x1B[0m
121
- `);return}let d=false,h="";h="http://localhost:80";try{if(console.log(`\u{1F310} Starting server on ${h}...`),typeof l.listen=="function"&&!l.isListening)await new Promise((S,O)=>{try{l.listen(()=>{d=!0,console.log(`\u2705 Server started successfully!
122
- `),S();});}catch(B){O(B);}}).catch(S=>{console.error("Failed to start the server, continuing...");});else throw new Error("Server instance does not have a listen() method")}catch(S){console.error("\x1B[31m\u274C Error starting server:\x1B[0m",S);return}let b=this.swaggerPath??(typeof l.serverOptions.swagger!="boolean"?l.serverOptions.swagger?.path:"/docs"),q=g.join(h,b??"/docs","/json");console.log(`\u{1F4E5} Downloading OpenAPI spec from: ${q}`);let P;try{let S=await globalThis.fetch(q);if(!S.ok)throw new Error(`Failed to fetch OpenAPI spec: ${S.status} ${S.statusText}`);P=await S.json(),console.log(`\u2705 OpenAPI spec downloaded successfully!
123
- `);}catch(S){if(console.error("\x1B[31m\u274C Error downloading OpenAPI spec:\x1B[0m",S),d){let O=l;try{await O.close?.();}catch{}}return}let E=g.join(process.cwd(),".openapi-spec.json");try{await u.writeFile(E,new TextEncoder().encode(JSON.stringify(P,null,2)));}catch(S){if(console.error("\x1B[31m\u274C Error saving OpenAPI spec to file:\x1B[0m",S),d){let O=l;try{await O.close?.();}catch{}}return}let F=g.resolve(process.cwd(),this.outputPath);console.log(`\u{1F528} Generating SDK...
124
- `);try{await u.exists(F)||await u.mkdir(F,{recursive:!0});let S=["npx swagger-typescript-api generate",`--path="${E}"`,`--output="${this.outputPath}"`,`--http-client ${this.httpClient}`,"--modular","--extract-request-params","--extract-request-body","--extract-response-body","--extract-response-error"];this.unwrapResponseData&&S.push("--unwrap-response-data"),this.singleHttpClient&&S.push("--single-http-client"),this.typePrefix&&S.push(`--type-prefix "${this.typePrefix}"`),this.typeSuffix&&S.push(`--type-suffix "${this.typeSuffix}"`),this.enumNamesAsValues&&S.push("--enum-names-as-values"),this.sortTypes&&S.push("--sort-types");let O=S.join(" ");execSync(O,{stdio:"inherit",cwd:process.cwd()}),console.log(`
125
- \x1B[32m\u2705 SDK generated successfully!\x1B[0m`),console.log(`\x1B[32m\u{1F4C1} SDK location: ${F}\x1B[0m
126
- `);}catch(S){console.error("\x1B[31m\u274C Error generating SDK:\x1B[0m",S);}finally{try{await u.unlink(E);}catch{}if(d){let S=l;try{console.log("\u{1F6D1} Stopping server..."),await S.close?.(),console.log(`\u2705 Server stopped.
121
+ `);return}let d=false,g="";g="http://localhost:80";try{if(console.log(`\u{1F310} Starting server on ${g}...`),typeof l.listen=="function"&&!l.isListening)await new Promise((P,E)=>{try{l.listen(()=>{d=!0,console.log(`\u2705 Server started successfully!
122
+ `),P();});}catch(L){E(L);}}).catch(P=>{console.error("Failed to start the server, continuing...");});else throw new Error("Server instance does not have a listen() method")}catch(P){console.error("\x1B[31m\u274C Error starting server:\x1B[0m",P);return}let y=this.swaggerPath??(typeof l.serverOptions.swagger!="boolean"?l.serverOptions.swagger?.path:"/docs"),S=h.join(g,y??"/docs","/json");console.log(`\u{1F4E5} Downloading OpenAPI spec from: ${S}`);let v;try{let P=await globalThis.fetch(S);if(!P.ok)throw new Error(`Failed to fetch OpenAPI spec: ${P.status} ${P.statusText}`);v=await P.json(),console.log(`\u2705 OpenAPI spec downloaded successfully!
123
+ `);}catch(P){if(console.error("\x1B[31m\u274C Error downloading OpenAPI spec:\x1B[0m",P),d){let E=l;try{await E.close?.();}catch{}}return}let C=h.join(process.cwd(),".openapi-spec.json");try{await u.writeFile(C,new TextEncoder().encode(JSON.stringify(v,null,2)));}catch(P){if(console.error("\x1B[31m\u274C Error saving OpenAPI spec to file:\x1B[0m",P),d){let E=l;try{await E.close?.();}catch{}}return}let M=h.resolve(process.cwd(),this.outputPath);console.log(`\u{1F528} Generating SDK...
124
+ `);try{await u.exists(M)||await u.mkdir(M,{recursive:!0});let P=["npx swagger-typescript-api generate",`--path="${C}"`,`--output="${this.outputPath}"`,`--http-client ${this.httpClient}`,"--modular","--extract-request-params","--extract-request-body","--extract-response-body","--extract-response-error"];this.unwrapResponseData&&P.push("--unwrap-response-data"),this.singleHttpClient&&P.push("--single-http-client"),this.typePrefix&&P.push(`--type-prefix "${this.typePrefix}"`),this.typeSuffix&&P.push(`--type-suffix "${this.typeSuffix}"`),this.enumNamesAsValues&&P.push("--enum-names-as-values"),this.sortTypes&&P.push("--sort-types");let E=P.join(" ");execSync(E,{stdio:"inherit",cwd:process.cwd()}),console.log(`
125
+ \x1B[32m\u2705 SDK generated successfully!\x1B[0m`),console.log(`\x1B[32m\u{1F4C1} SDK location: ${M}\x1B[0m
126
+ `);}catch(P){console.error("\x1B[31m\u274C Error generating SDK:\x1B[0m",P);}finally{try{await u.unlink(C);}catch{}if(d){let P=l;try{console.log("\u{1F6D1} Stopping server..."),await P.close?.(),console.log(`\u2705 Server stopped.
127
127
  `);}catch{console.log(`\x1B[33m\u26A0\uFE0F Could not stop server gracefully.\x1B[0m
128
128
  `);}}}console.log(`\x1B[32m\u2728 SDK generation complete!\x1B[0m
129
- `);}};y([A({description:"Path to the server instance file (should export a Server instance)",required:false,defaultValue:"test/server/instance.ts"})],H,"serverPath"),y([x({description:"Output directory for generated SDK",type:"string",aliases:["o"],name:"output",required:false,defaultValue:"sdk"})],H,"outputPath"),y([x({description:"Swagger UI path on your server",type:"string",aliases:["s"],name:"swagger-path",required:false})],H,"swaggerPath"),y([x({description:"HTTP client to use (axios or fetch)",type:"string",aliases:["c"],name:"client",required:false,defaultValue:"fetch"})],H,"httpClient"),y([x({description:"Unwrap response data automatically",type:"boolean",name:"unwrap-response-data",required:false,defaultValue:false})],H,"unwrapResponseData"),y([x({description:"Generate single HTTP client instance",type:"boolean",name:"single-http-client",required:false,defaultValue:false})],H,"singleHttpClient"),y([x({description:"Add prefix to all generated types",type:"string",name:"type-prefix",required:false})],H,"typePrefix"),y([x({description:"Add suffix to all generated types",type:"string",name:"type-suffix",required:false})],H,"typeSuffix"),y([x({description:"Use enum names as values",type:"boolean",name:"enum-names-as-values",required:false,defaultValue:false})],H,"enumNamesAsValues"),y([x({description:"Sort types alphabetically",type:"boolean",name:"sort-types",required:false,defaultValue:false})],H,"sortTypes");var te=class extends j{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 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 mqtt;static cron;static devDependencies=["esbuild","esbuild-plugin-copy","tsx","typescript"];static async handle(){this.logger.info("Initializing project...");let[e,t,r]=await z();if(["npm","yarn","pnpm"].includes(e)){let a=await je(this.devDependencies);if(a.length&&(this.logger.info(`Found ${a.length} missing dev dependencies`),!await _(`${e} ${t} ${a.join(" ")} -${r}`,e,a,{stdio:"inherit"}))){this.logger.info("Installation cancelled by user. Project initialization aborted.");return}a.length||this.logger.info("All dev dependencies are already installed");}if(this.mqtt&&["npm","yarn","pnpm"].includes(e)){let a=await je(["mqtt"]);a.length&&(await _(`${e} ${t} mqtt`,e,["mqtt"],{stdio:"inherit"},false)||(this.logger.info("MQTT installation cancelled by user. Skipping MQTT scaffolding."),this.mqtt=false)),a.length||this.logger.info("MQTT package is already installed");}if(this.cron&&["npm","yarn","pnpm"].includes(e)){let a=await je(["node-cron"]);a.length>0&&(await _(`${e} ${t} node-cron`,e,["node-cron"],{stdio:"inherit"},false)||(this.logger.info("node-cron installation cancelled by user. Skipping Cron scaffolding."),this.cron=false)),a.length||this.logger.info("node-cron package is already installed");}let s=this.typescript?"ts":"js",o=this.getServerTemplate(),n=this.getIndexTemplate();if(u.exists(this.srcPath)||await u.mkdir(this.srcPath,{recursive:true}),this.logger.info(`Creating server.${s} file...`),await u.writeFile(`${this.srcPath}/server.${s}`,new TextEncoder().encode(o)),this.logger.info(`Creating index.${s} file...`),await u.writeFile(`${this.srcPath}/index.${s}`,new TextEncoder().encode(n)),this.mqtt){let a=g.join(this.srcPath,"mqtt");await u.exists(a)||await u.mkdir(a,{recursive:true});let c=this.getMqttConfigTemplate();this.logger.info(`Creating mqtt/mqtt.config.${s} file...`),await u.writeFile(g.join(a,`mqtt.config.${s}`),new TextEncoder().encode(c));}if(this.cron){let a=g.join(this.srcPath,"cron");await u.exists(a)||await u.mkdir(a,{recursive:true});let c=this.getCronConfigTemplate();this.logger.info(`Creating cron/cron.config.${s} file...`),await u.writeFile(g.join(a,`cron.config.${s}`),new TextEncoder().encode(c));}this.logger.info("Project initialized successfully!");}static getServerTemplate(){return `import { Server } from "balda";
129
+ `);}};w([k({description:"Path to the server instance file (should export a Server instance)",required:false,defaultValue:"test/server/instance.ts"})],H,"serverPath"),w([R({description:"Output directory for generated SDK",type:"string",aliases:["o"],name:"output",required:false,defaultValue:"sdk"})],H,"outputPath"),w([R({description:"Swagger UI path on your server",type:"string",aliases:["s"],name:"swagger-path",required:false})],H,"swaggerPath"),w([R({description:"HTTP client to use (axios or fetch)",type:"string",aliases:["c"],name:"client",required:false,defaultValue:"fetch"})],H,"httpClient"),w([R({description:"Unwrap response data automatically",type:"boolean",name:"unwrap-response-data",required:false,defaultValue:false})],H,"unwrapResponseData"),w([R({description:"Generate single HTTP client instance",type:"boolean",name:"single-http-client",required:false,defaultValue:false})],H,"singleHttpClient"),w([R({description:"Add prefix to all generated types",type:"string",name:"type-prefix",required:false})],H,"typePrefix"),w([R({description:"Add suffix to all generated types",type:"string",name:"type-suffix",required:false})],H,"typeSuffix"),w([R({description:"Use enum names as values",type:"boolean",name:"enum-names-as-values",required:false,defaultValue:false})],H,"enumNamesAsValues"),w([R({description:"Sort types alphabetically",type:"boolean",name:"sort-types",required:false,defaultValue:false})],H,"sortTypes");var se=class extends q{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 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 mqtt;static cron;static devDependencies=["esbuild","esbuild-plugin-copy","tsx","typescript"];static async handle(){this.logger.info("Initializing project...");let[e,t,r]=await G();if(["npm","yarn","pnpm"].includes(e)){let a=await Ee(this.devDependencies);if(a.length&&(this.logger.info(`Found ${a.length} missing dev dependencies`),!await D(`${e} ${t} ${a.join(" ")} -${r}`,e,a,{stdio:"inherit"}))){this.logger.info("Installation cancelled by user. Project initialization aborted.");return}a.length||this.logger.info("All dev dependencies are already installed");}if(this.mqtt&&["npm","yarn","pnpm"].includes(e)){let a=await Ee(["mqtt"]);a.length&&(await D(`${e} ${t} mqtt`,e,["mqtt"],{stdio:"inherit"},false)||(this.logger.info("MQTT installation cancelled by user. Skipping MQTT scaffolding."),this.mqtt=false)),a.length||this.logger.info("MQTT package is already installed");}if(this.cron&&["npm","yarn","pnpm"].includes(e)){let a=await Ee(["node-cron"]);a.length>0&&(await D(`${e} ${t} node-cron`,e,["node-cron"],{stdio:"inherit"},false)||(this.logger.info("node-cron installation cancelled by user. Skipping Cron scaffolding."),this.cron=false)),a.length||this.logger.info("node-cron package is already installed");}let s=this.typescript?"ts":"js",o=this.getServerTemplate(),i=this.getIndexTemplate();if(u.exists(this.srcPath)||await u.mkdir(this.srcPath,{recursive:true}),this.logger.info(`Creating server.${s} file...`),await u.writeFile(`${this.srcPath}/server.${s}`,new TextEncoder().encode(o)),this.logger.info(`Creating index.${s} file...`),await u.writeFile(`${this.srcPath}/index.${s}`,new TextEncoder().encode(i)),this.mqtt){let a=h.join(this.srcPath,"mqtt");await u.exists(a)||await u.mkdir(a,{recursive:true});let c=this.getMqttConfigTemplate();this.logger.info(`Creating mqtt/mqtt.config.${s} file...`),await u.writeFile(h.join(a,`mqtt.config.${s}`),new TextEncoder().encode(c));}if(this.cron){let a=h.join(this.srcPath,"cron");await u.exists(a)||await u.mkdir(a,{recursive:true});let c=this.getCronConfigTemplate();this.logger.info(`Creating cron/cron.config.${s} file...`),await u.writeFile(h.join(a,`cron.config.${s}`),new TextEncoder().encode(c));}this.logger.info("Project initialized successfully!");}static getServerTemplate(){return `import { Server } from "balda";
130
130
 
131
131
  const serverInstance = new Server({
132
132
  port: 80,
133
133
  host: "0.0.0.0",
134
134
  plugins: {
135
- json: {
136
- sizeLimit: "100kb",
135
+ bodyParser: {
136
+ json: {
137
+ sizeLimit: "100kb",
138
+ }
137
139
  },
138
140
  },
139
141
  });
@@ -166,7 +168,7 @@ server.listen(({ url }) => {
166
168
  // This file is imported to set up Cron jobs
167
169
  // Add your cron jobs in separate files within this directory
168
170
  // Use: npx balda generate-cron <job-name> to create new cron jobs
169
- `}};y([x.string({description:"The path to the project, default is the current directory /src",aliases:"p",name:"path",required:false,defaultValue:"./src"})],te,"srcPath"),y([x.boolean({description:"Whether to use typescript, default is true",aliases:"t",name:"typescript",required:false,defaultValue:true})],te,"typescript"),y([x.boolean({description:"Initialize MQTT service connection",aliases:"m",name:"mqtt",required:false,defaultValue:false})],te,"mqtt"),y([x.boolean({description:"Initialize Cron service",aliases:"c",name:"cron",required:false,defaultValue:false})],te,"cron");var ve=class extends j{static commandName="init-queue";static description="Initialize queue provider configuration with required dependencies";static help=["Initialize a queue provider configuration file with basic credentials","Automatically installs required packages for the selected provider","Only scaffolds the connection, handlers should be created with generate-queue command","Example: npx balda init-queue -t bullmq -o src/queue"];static queueType;static outputPath;static queueDependencies={bullmq:["bullmq","ioredis"],sqs:["@aws-sdk/client-sqs","sqs-consumer"],pgboss:["pg-boss","pg"]};static async handle(){if(this.logger.info(`Initializing ${this.queueType} queue provider...`),!["bullmq","sqs","pgboss"].includes(this.queueType)){this.logger.error(`Invalid queue type: ${this.queueType}. Must be one of: bullmq, sqs, pgboss`);return}let[e,t]=await z();if(["npm","yarn","pnpm"].includes(e)){let n=this.queueDependencies[this.queueType],a=await je(n);if(a.length>0&&(this.logger.info(`Found ${a.length} missing dependencies for ${this.queueType}`),!await _(`${e} ${t} ${a.join(" ")}`,e,a,{stdio:"inherit"},false))){this.logger.info("Installation cancelled by user. Queue initialization aborted.");return}a.length===0&&this.logger.info(`All ${this.queueType} dependencies are already installed`);}let r=this.getConfigTemplate(),s=`${this.queueType}.config.ts`,o=g.join(this.outputPath,s);await u.exists(this.outputPath)||await u.mkdir(this.outputPath,{recursive:true}),this.logger.info(`Creating ${s} file at ${this.outputPath}...`),await u.writeFile(o,new TextEncoder().encode(r)),this.logger.info(`Queue configuration initialized successfully at ${o}`),this.logger.info("Remember to update the configuration with your actual credentials"),this.logger.info("Use 'npx balda generate-queue' to create queue handlers");}static getConfigTemplate(){return this.queueType==="bullmq"?this.getBullMQTemplate():this.queueType==="sqs"?this.getSQSTemplate():this.queueType==="pgboss"?this.getPGBossTemplate():""}static getBullMQTemplate(){return `import { defineBullMQConfiguration } from "balda";
171
+ `}};w([R.string({description:"The path to the project, default is the current directory /src",aliases:"p",name:"path",required:false,defaultValue:"./src"})],se,"srcPath"),w([R.boolean({description:"Whether to use typescript, default is true",aliases:"t",name:"typescript",required:false,defaultValue:true})],se,"typescript"),w([R.boolean({description:"Initialize MQTT service connection",aliases:"m",name:"mqtt",required:false,defaultValue:false})],se,"mqtt"),w([R.boolean({description:"Initialize Cron service",aliases:"c",name:"cron",required:false,defaultValue:false})],se,"cron");var Se=class extends q{static commandName="init-queue";static description="Initialize queue provider configuration with required dependencies";static help=["Initialize a queue provider configuration file with basic credentials","Automatically installs required packages for the selected provider","Only scaffolds the connection, handlers should be created with generate-queue command","Example: npx balda init-queue -t bullmq -o src/queue"];static queueType;static outputPath;static queueDependencies={bullmq:["bullmq","ioredis"],sqs:["@aws-sdk/client-sqs","sqs-consumer"],pgboss:["pg-boss","pg"]};static async handle(){if(this.logger.info(`Initializing ${this.queueType} queue provider...`),!["bullmq","sqs","pgboss"].includes(this.queueType)){this.logger.error(`Invalid queue type: ${this.queueType}. Must be one of: bullmq, sqs, pgboss`);return}let[e,t]=await G();if(["npm","yarn","pnpm"].includes(e)){let i=this.queueDependencies[this.queueType],a=await Ee(i);if(a.length>0&&(this.logger.info(`Found ${a.length} missing dependencies for ${this.queueType}`),!await D(`${e} ${t} ${a.join(" ")}`,e,a,{stdio:"inherit"},false))){this.logger.info("Installation cancelled by user. Queue initialization aborted.");return}a.length===0&&this.logger.info(`All ${this.queueType} dependencies are already installed`);}let r=this.getConfigTemplate(),s=`${this.queueType}.config.ts`,o=h.join(this.outputPath,s);await u.exists(this.outputPath)||await u.mkdir(this.outputPath,{recursive:true}),this.logger.info(`Creating ${s} file at ${this.outputPath}...`),await u.writeFile(o,new TextEncoder().encode(r)),this.logger.info(`Queue configuration initialized successfully at ${o}`),this.logger.info("Remember to update the configuration with your actual credentials"),this.logger.info("Use 'npx balda generate-queue' to create queue handlers");}static getConfigTemplate(){return this.queueType==="bullmq"?this.getBullMQTemplate():this.queueType==="sqs"?this.getSQSTemplate():this.queueType==="pgboss"?this.getPGBossTemplate():""}static getBullMQTemplate(){return `import { defineBullMQConfiguration } from "balda";
170
172
 
171
173
  // Configure BullMQ connection and default options
172
174
  defineBullMQConfiguration({
@@ -335,22 +337,22 @@ definePGBossConfiguration({
335
337
  * console.log("Processing:", payload);
336
338
  * });
337
339
  */
338
- `}};y([x.string({description:"Queue provider type (bullmq, sqs, pgboss) - required",aliases:"t",name:"type",required:true})],ve,"queueType"),y([x.string({description:"Output directory for queue configuration, default is src/queue",aliases:"o",name:"output",required:false,defaultValue:"src/queue"})],ve,"outputPath");var De=class extends j{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=qe.getBuiltInCommands(),t=qe.getUserDefinedCommands();if(console.log(`
340
+ `}};w([R.string({description:"Queue provider type (bullmq, sqs, pgboss) - required",aliases:"t",name:"type",required:true})],Se,"queueType"),w([R.string({description:"Output directory for queue configuration, default is src/queue",aliases:"o",name:"output",required:false,defaultValue:"src/queue"})],Se,"outputPath");var Fe=class extends q{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=Ae.getBuiltInCommands(),t=Ae.getUserDefinedCommands();if(console.log(`
339
341
  \u2728 Available Balda Commands:
340
342
  `),t.length>0){console.log(`\x1B[1;33mUser Commands:\x1B[0m
341
343
  `);let r=this.groupByCategory(t);this.displayCategorizedCommands(r);}if(e.length>0){console.log(`\x1B[1;32mBuilt-in Commands:\x1B[0m
342
- `);let r=Math.max(...e.map(s=>s.commandName.length));for(let s of e){let o=s.commandName.padEnd(r+2),n=s.description||"No description available",a="";s.options?.deprecated&&(a=" \x1B[33m[deprecated]\x1B[0m"),console.log(` \x1B[36m${o}\x1B[0m ${n}${a}`);}console.log("");}console.log(`\x1B[90mRun 'npx balda <command> -h' for more information on a specific command.\x1B[0m
343
- `);}static groupByCategory(e){let t=new Map;for(let r of e){let s=r.options?.category||"other";t.has(s)||t.set(s,[]),t.get(s).push(r);}return t}static displayCategorizedCommands(e){let t=Array.from(e.keys()).sort();for(let r of t){let s=e.get(r).filter(c=>c&&c.commandName);if(s.length===0)continue;let n={generator:"\x1B[35m",setup:"\x1B[34m",production:"\x1B[32m",utility:"\x1B[36m",other:"\x1B[37m"}[r]||"\x1B[37m";console.log(` ${n}${r.toUpperCase()}:\x1B[0m`);let a=Math.max(...s.map(c=>c.commandName.length));for(let c of s){let p=c.commandName.padEnd(a+2),l=c.description||"No description available",d="";c.options?.deprecated&&(d=" \x1B[33m[deprecated]\x1B[0m"),console.log(` \x1B[36m${p}\x1B[0m ${l}${d}`);}console.log("");}}};Q();var we=class extends j{static commandName="serve";static description="Run the server in dev mode with hot reload";static help=["This command is intended to be run from the root of the project","Bun and Deno have native dev hot reload","Runtime is automatically inferred","Node.js requires tsx to be installed for both typescript and javascript files","Node.js dev dependencies (tsx) are installed automatically if not detected"];static runtime=R.type;static options={keepAlive:true};static entry;static denoImportMap;static async handle(){if(this.runtime==="bun"){execSync(`bun run --watch ${this.entry}`,{stdio:"inherit",cwd:$.getCwd()});return}if(this.runtime==="deno"){let e="deno run --watch --unstable-sloppy-imports --allow-all";this.denoImportMap&&(e=`${e} --import-map ${this.denoImportMap}`),execSync(`${e} ${this.entry}`,{stdio:"inherit",cwd:$.getCwd()});return}this.handleNodeHotReload();}static async handleNodeHotReload(){if(!Ye.existsSync("node_modules/.bin/tsx")){let[r,s,o]=await z();if(!await _(`${r} ${s} tsx ${o}`,r,["tsx"],{stdio:"inherit"})){this.logger.info("Installation cancelled by user. Cannot start dev server without tsx.");return}}let t=this.calledBy!=="node"?this.calledBy:"npx";execSync(`${t} tsx watch ${this.entry}`,{stdio:"inherit",cwd:process.cwd()});}};y([A({required:false,defaultValue:"src/index.ts",description:"The entry point of the project, default is src/index.ts"})],we,"entry"),y([x.string({aliases:["d"],name:"deno-import-map",required:false,description:"Path to deno import map"})],we,"denoImportMap");var be=class extends j{static commandName="setup-storage";static description="Setup storage provider with required dependencies";static help=["Install dependencies and create storage configuration for a specific provider","Flags:"," -t, --type <provider> Storage provider type (s3, azure, local)"," -o, --output <path> Output directory for storage setup (default: src/storage/)","","Examples:"," npx balda setup:storage -t s3"," npx balda setup:storage --type azure --output src/config/"];static storageType;static outputPath;static async handle(){if(!this.storageType){console.error("\x1B[31m\u274C Error: Storage type is required. Use -t or --type flag.\x1B[0m"),console.log(`\x1B[90mExample: npx balda setup:storage -t s3\x1B[0m
344
- `);return}this.outputPath||await u.mkdir(g.join(process.cwd(),this.outputPath),{recursive:true});let e=["s3","azure","local"];if(!e.includes(this.storageType)){console.error(`\x1B[31m\u274C Error: Invalid storage type '${this.storageType}'. Valid types: ${e.join(", ")}\x1B[0m
344
+ `);let r=Math.max(...e.map(s=>s.commandName.length));for(let s of e){let o=s.commandName.padEnd(r+2),i=s.description||"No description available",a="";s.options?.deprecated&&(a=" \x1B[33m[deprecated]\x1B[0m"),console.log(` \x1B[36m${o}\x1B[0m ${i}${a}`);}console.log("");}console.log(`\x1B[90mRun 'npx balda <command> -h' for more information on a specific command.\x1B[0m
345
+ `);}static groupByCategory(e){let t=new Map;for(let r of e){let s=r.options?.category||"other";t.has(s)||t.set(s,[]),t.get(s).push(r);}return t}static displayCategorizedCommands(e){let t=Array.from(e.keys()).sort();for(let r of t){let s=e.get(r).filter(c=>c&&c.commandName);if(s.length===0)continue;let i={generator:"\x1B[35m",setup:"\x1B[34m",production:"\x1B[32m",utility:"\x1B[36m",other:"\x1B[37m"}[r]||"\x1B[37m";console.log(` ${i}${r.toUpperCase()}:\x1B[0m`);let a=Math.max(...s.map(c=>c.commandName.length));for(let c of s){let p=c.commandName.padEnd(a+2),l=c.description||"No description available",d="";c.options?.deprecated&&(d=" \x1B[33m[deprecated]\x1B[0m"),console.log(` \x1B[36m${p}\x1B[0m ${l}${d}`);}console.log("");}}};U();var xe=class extends q{static commandName="serve";static description="Run the server in dev mode with hot reload";static help=["This command is intended to be run from the root of the project","Bun and Deno have native dev hot reload","Runtime is automatically inferred","Node.js requires tsx to be installed for both typescript and javascript files","Node.js dev dependencies (tsx) are installed automatically if not detected"];static runtime=T.type;static options={keepAlive:true};static entry;static denoImportMap;static async handle(){if(this.runtime==="bun"){execSync(`bun run --watch ${this.entry}`,{stdio:"inherit",cwd:B.getCwd()});return}if(this.runtime==="deno"){let e="deno run --watch --unstable-sloppy-imports --allow-all";this.denoImportMap&&(e=`${e} --import-map ${this.denoImportMap}`),execSync(`${e} ${this.entry}`,{stdio:"inherit",cwd:B.getCwd()});return}this.handleNodeHotReload();}static async handleNodeHotReload(){if(!tt.existsSync("node_modules/.bin/tsx")){let[r,s,o]=await G();if(!await D(`${r} ${s} tsx ${o}`,r,["tsx"],{stdio:"inherit"})){this.logger.info("Installation cancelled by user. Cannot start dev server without tsx.");return}}let t=this.calledBy!=="node"?this.calledBy:"npx";execSync(`${t} tsx watch ${this.entry}`,{stdio:"inherit",cwd:process.cwd()});}};w([k({required:false,defaultValue:"src/index.ts",description:"The entry point of the project, default is src/index.ts"})],xe,"entry"),w([R.string({aliases:["d"],name:"deno-import-map",required:false,description:"Path to deno import map"})],xe,"denoImportMap");var Re=class extends q{static commandName="setup-storage";static description="Setup storage provider with required dependencies";static help=["Install dependencies and create storage configuration for a specific provider","Flags:"," -t, --type <provider> Storage provider type (s3, azure, local)"," -o, --output <path> Output directory for storage setup (default: src/storage/)","","Examples:"," npx balda setup:storage -t s3"," npx balda setup:storage --type azure --output src/config/"];static storageType;static outputPath;static async handle(){if(!this.storageType){console.error("\x1B[31m\u274C Error: Storage type is required. Use -t or --type flag.\x1B[0m"),console.log(`\x1B[90mExample: npx balda setup:storage -t s3\x1B[0m
346
+ `);return}this.outputPath||await u.mkdir(h.join(process.cwd(),this.outputPath),{recursive:true});let e=["s3","azure","local"];if(!e.includes(this.storageType)){console.error(`\x1B[31m\u274C Error: Invalid storage type '${this.storageType}'. Valid types: ${e.join(", ")}\x1B[0m
345
347
  `);return}console.log(`
346
348
  \u{1F680} Setting up ${this.storageType.toUpperCase()} storage provider...
347
349
  `);let t=this.getDependencies(this.storageType);if(t.length===0&&console.log(`\x1B[32m\u2705 ${this.storageType.toUpperCase()} storage doesn't require additional dependencies.\x1B[0m
348
350
  `),t.length){let r=await this.checkMissingDependencies(t);if(r.length===0&&console.log(`\x1B[32m\u2705 All required dependencies are already installed.\x1B[0m
349
- `),r.length){let[s,o]=await z(),n=`${s} ${o} ${r.join(" ")}`;if(!await _(n,s,r,{stdio:"inherit"},false)){console.log(`\x1B[33m\u26A0\uFE0F Dependency installation skipped by user.\x1B[0m
351
+ `),r.length){let[s,o]=await G(),i=`${s} ${o} ${r.join(" ")}`;if(!await D(i,s,r,{stdio:"inherit"},false)){console.log(`\x1B[33m\u26A0\uFE0F Dependency installation skipped by user.\x1B[0m
350
352
  `);return}console.log(`
351
353
  \x1B[32m\u2705 Dependencies installed successfully!\x1B[0m
352
354
  `);}}await this.createStorageSetup(this.storageType,this.outputPath),console.log(`\x1B[32m\u2728 ${this.storageType.toUpperCase()} storage setup complete!\x1B[0m
353
- `);}static getDependencies(e){return {s3:["@aws-sdk/client-s3","@aws-sdk/s3-request-presigner","@aws-sdk/cloudfront-signer"],azure:["@azure/storage-blob"],local:[]}[e]||[]}static async checkMissingDependencies(e){let t=g.join(process.cwd(),"package.json");if(!await u.exists(t))return e;let s=g.join(process.cwd(),"node_modules");if(!await u.exists(s))return e;let n=[];for(let a of e){let c=g.join(s,a);await u.exists(c)||n.push(a);}return n}static async createStorageSetup(e,t){let r=g.join(process.cwd(),t);await u.exists(r)||await u.mkdir(r,{recursive:true});let o=g.join(r,"storage.ts");if(await u.exists(o)){console.log(`\x1B[33m\u26A0\uFE0F Configuration file already exists: ${o}\x1B[0m`);return}let a=this.getConfigTemplate(e);await u.writeFile(o,new TextEncoder().encode(a)),console.log(`\x1B[32m\u2705 Created configuration file: ${o}\x1B[0m`);}static getConfigTemplate(e){return {s3:`import { Storage, S3StorageProvider } from "balda";
355
+ `);}static getDependencies(e){return {s3:["@aws-sdk/client-s3","@aws-sdk/s3-request-presigner","@aws-sdk/cloudfront-signer"],azure:["@azure/storage-blob"],local:[]}[e]||[]}static async checkMissingDependencies(e){let t=h.join(process.cwd(),"package.json");if(!await u.exists(t))return e;let s=h.join(process.cwd(),"node_modules");if(!await u.exists(s))return e;let i=[];for(let a of e){let c=h.join(s,a);await u.exists(c)||i.push(a);}return i}static async createStorageSetup(e,t){let r=h.join(process.cwd(),t);await u.exists(r)||await u.mkdir(r,{recursive:true});let o=h.join(r,"storage.ts");if(await u.exists(o)){console.log(`\x1B[33m\u26A0\uFE0F Configuration file already exists: ${o}\x1B[0m`);return}let a=this.getConfigTemplate(e);await u.writeFile(o,new TextEncoder().encode(a)),console.log(`\x1B[32m\u2705 Created configuration file: ${o}\x1B[0m`);}static getConfigTemplate(e){return {s3:`import { Storage, S3StorageProvider } from "balda";
354
356
 
355
357
  /**
356
358
  * S3 Storage Configuration
@@ -430,23 +432,21 @@ export const storage = new Storage(
430
432
  defaultProvider: "local",
431
433
  },
432
434
  );
433
- `}[e]||""}};y([x({description:"Storage provider type (s3, azure, local)",type:"string",aliases:["t"],name:"type",required:true})],be,"storageType"),y([x({description:"Output directory for storage setup",type:"string",aliases:["o"],name:"output",required:false,defaultValue:"src/storage/"})],be,"outputPath");var rs=[ye,Ee,he,fe,oe,me,ge,H,te,ve,De,I,we,be],Rt=class i{commands;builtInCommands;static commandsPattern="src/commands/**/*.{ts,js}";static logger=v;constructor(){this.commands=new Map,this.builtInCommands=new Set;}static getInstance(){return new i}static setCommandsPattern(e){this.commandsPattern=e;}getCommand(e){return this.commands.get(e)??null}getCommands(){return Array.from(this.commands.values())}getBuiltInCommands(){return Array.from(this.commands.values()).filter(e=>this.builtInCommands.has(e.commandName))}getUserDefinedCommands(){return Array.from(this.commands.values()).filter(e=>!this.builtInCommands.has(e.commandName))}isBuiltInCommand(e){return this.builtInCommands.has(e)}async loadCommands(e){i.logger.info(`Loading commands from ${e}`);let t=await glob(e,{absolute:true,cwd:$.getCwd()});if(t.some(r=>r.endsWith(".ts")))try{let{register:r}=await import('module');r("ts-node/esm",import.meta.url);}catch{i.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 r of t){let s=await import(r).then(o=>o.default?o.default:o).catch(o=>(i.logger.error(`Error loading command ${r}: ${o}`),null));s&&this.commands.set(s.commandName,s);}for(let r of rs)this.commands.set(r.commandName,r),this.builtInCommands.add(r.commandName);}},qe=Rt.getInstance();var Xe=class extends Request{};var Me=new WeakMap,K=class i extends Xe{static fromRequest(e){return new i(e.url,{method:e.method,body:e.body,headers:e.headers})}static compileAndValidate(e,t,r){let s,o;if(Y.isZodSchema(e)){let p=e,l=Me.get(p);l||(l=Symbol("zod_schema"),Me.set(p,l));let d=k.get(l);if(d)return L(d,t,r);s=p.toJSONSchema();let h=N.ajv.compile(s);return k.set(l,h),L(h,t,r)}if(Te.isTypeBoxSchema(e)){let p=e,l=Me.get(p);l||(l=Symbol("typebox_schema"),Me.set(p,l));let d=k.get(l);if(d)return L(d,t,r);let h=N.ajv.compile(p);return k.set(l,h),L(h,t,r)}let n=e;if(typeof n=="object"&&n!==null){let p=Me.get(n);p||(p=Symbol("json_schema"),Me.set(n,p));let l=k.get(p);if(l)return L(l,t,r);let d=N.ajv.compile(n);return k.set(p,d),L(d,t,r)}o=JSON.stringify(n);let a=k.get(o);if(a)return L(a,t,r);let c=N.ajv.compile(n);return k.set(o,c),L(c,t,r)}static enrichRequest(e){return e.validate=(t,r=false)=>i.compileAndValidate(t,e.body||{},r),e.validateQuery=(t,r=false)=>i.compileAndValidate(t,e.query||{},r),e.validateAll=(t,r=false)=>i.compileAndValidate(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}ctx={};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=X.randomUUID()),this._id}set id(e){this._id=e;}body;validate(e,t=false){return i.compileAndValidate(e,this.body||{},t)}validateQuery(e,t=false){return i.compileAndValidate(e,this.query||{},t)}validateAll(e,t=false){return i.compileAndValidate(e,{...this.body??{},...this.query??{}},t)}};Q();var Ae=class{get(e){switch(R.type){case "node":case "bun":case "deno":return process.env[e]??"";default:throw new Error(`Unsupported runtime: ${R.type}`)}}getEnvironment(){switch(R.type){case "node":case "deno":case "bun":return Object.fromEntries(Object.entries(process.env).filter(([e,t])=>t!==void 0))}}};var ss=new Ae,M=i=>{let e=ss.get("NODE_ENV")!=="production";return {code:i.name||"INTERNAL_ERROR",message:i.message,...e&&{stack:i.stack,cause:i.cause}}};var ke=class extends T{constructor(e,t){super(`METHOD_NOT_ALLOWED: Cannot ${t} ${e}`);}};var D=class extends T{constructor(e,t){super(`ROUTE_NOT_FOUND: Cannot ${t} ${e}`);}};Q();var Tt=class{file(e,t){switch(R.type){case "bun":case "node":return Ye.readFileSync(e,t);case "deno":return Deno.readFileSync(e);default:throw new Error("Unsupported runtime")}}},et=new Tt;var Gt=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 Wt=(i,e)=>{let{source:t,path:r}=i,s=r;return s.startsWith("/")||(s="/"+s),s!=="/"&&s.endsWith("/")&&(s=s.slice(0,-1)),C.addOrUpdate("GET",`${s}/*`,[],async(o,n)=>is(o,n,t),{service:"StaticFiles",...e}),async(o,n,a)=>a()};async function is(i,e,t){if(i.method!=="GET"&&i.method!=="HEAD")return e.status(405).json({...M(new ke(i.url,i.method))});let r=i.params["*"]||"",s=g.join(t,r),o=g.resolve($.getCwd(),s),n=g.resolve($.getCwd(),t);if(!o.startsWith(n))return e.notFound({...M(new D(i.url,i.method))});try{if(!(await u.stat(o)).isFile)return e.notFound({...M(new D(i.url,i.method))})}catch(p){if(p.code==="ENOENT")return e.notFound({...M(new D(i.url,i.method))});throw p}let a=Ct(g.extName(o));e.setHeader("Content-Type",a);let c=et.file(o);e.raw(c);}function Ct(i){return Gt.get(i)||"application/octet-stream"}var re=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=g.extName(e),s=Ct(r);this.body=et.file(e,t),this.headers={...this.headers,"Content-Type":s};}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 s of e)r.enqueue(new TextEncoder().encode(s));r.close();}});}getBody(){return this.body}};var V=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,s=r[e];if(s&&typeof s=="object"){r[e]={...s,...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 $e=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 s in t){let o=r===""?s:`${r}.${s}`,n=e[s],a=t[s];if(!(s in e))throw new Error(`Expected ${r} to have key ${s}, but it was not found`);if(this.isObject(a)&&this.isObject(n))this.assertSubset(n,a,o);else if(Array.isArray(a)&&Array.isArray(n))this.assertArraySubset(n,a,o);else if(n!==a)throw new Error(`Expected ${o} to be ${a}, but got ${n}`)}}assertDeepEqual(e,t,r){if(this.isObject(e)&&this.isObject(t)){let s=Object.keys(e),o=Object.keys(t);if(s.length!==o.length)throw new Error(`Expected ${r} to have ${o.length} keys, but got ${s.length}`);for(let n of o){let a=r==="body"?n:`${r}.${n}`;this.assertDeepEqual(e[n],t[n],a);}}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(s){if(s instanceof Error&&s.message.includes("Expected"))return;throw s}}assertNotDeepEqual(e,t,r){try{throw this.assertDeepEqual(e,t,r),new Error(`Expected ${r} to NOT be deeply equal, but it is`)}catch(s){if(s instanceof Error&&s.message.includes("Expected"))return;throw s}}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 s=0;s<t.length;s++){let o=`${r}[${s}]`,n=e[s],a=t[s];if(this.isObject(a)&&this.isObject(n))this.assertSubset(n,a,o);else if(Array.isArray(a)&&Array.isArray(n))this.assertArraySubset(n,a,o);else if(n!==a)throw new Error(`Expected ${o} to be ${a}, but got ${n}`)}}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 s=0;s<t.length;s++){let o=`${r}[${s}]`;this.assertDeepEqual(e[s],t[s],o);}}isObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}};var ie=async(i,e,t,r=new re)=>{let s=0;if(!i.length)return await e(t,r),r;let o=async()=>{if(s++,s>=i.length){await e(t,r);return}let a=i[s];await a(t,r,o);},n=i[0];return await n(t,r,o),r},ne=i=>i?["post","put","patch","delete"].includes(i.toLowerCase()):true,He=i=>{let e=null,t=false,r=async()=>{for(;t;)await new Promise(o=>setTimeout(o,10));},s=async()=>{try{let{createYoga:o,createSchema:n}=await import('graphql-yoga'),a=i.getSchema(n),c=i.getYogaOptions();return o({graphqlEndpoint:"/graphql",...c,schema:a})}catch(o){throw o instanceof Error&&(o.message.includes("Cannot find module")||o.message.includes("Cannot find package"))?new Error("GraphQL is enabled but 'graphql-yoga' is not installed. Install it with: npm install graphql graphql-yoga"):o}};return async()=>{if(!i.isEnabled)return null;if(e!==null)return e;if(t)return await r(),e;t=true;try{return e=s(),await e}catch(c){throw e=null,c}finally{t=false;}}};var tt=class{server;constructor(e){this.server=e;}async request(e,t,r={}){let{headers:s={},query:o={},cookies:n={},ip:a}=r;this.validateOptions(r);let c=C.find(e.toUpperCase(),t);if(!c){let m=new re(404);return m.json({caller:"MockServer",error:"Route not found",path:t,method:e}),new $e(m)}let p=r.body,l="application/json";if(p&&typeof p=="object"&&!(p instanceof Uint8Array)&&!(p instanceof ArrayBuffer)&&(p=JSON.stringify(p)),r.formData){let m=`----WebKitFormBoundary${Math.random().toString(36).substring(2)}`;l=`multipart/form-data; boundary=${m}`,p=await this.formDataToMultipart(r.formData,m);}r.urlencoded&&(l="application/x-www-form-urlencoded",p=new URLSearchParams(r.urlencoded).toString());let d=new URL(`http://${this.server.host}:${this.server.port}${t}`);d.search=new URLSearchParams(o).toString();let h=new K(d.toString(),{method:e.toUpperCase(),body:ne(e)?p:void 0,headers:{"content-type":l,...s}});h.query={...Object.fromEntries(d.searchParams.entries()),...o},h.params=c.params,h.cookies=n,h.ip=a;try{let m=await ie(c.middleware,c.handler,h);return new $e(m)}catch(m){v.error({error:m},`Error processing mock request ${e} ${t}:`);let f=new re(500);return f.json({error:"Internal server error",message:m instanceof Error?m.message:String(m)}),new $e(f)}}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,s=[];for(let[c,p]of e.entries()){s.push(r.encode(`--${t}\r
435
+ `}[e]||""}};w([R({description:"Storage provider type (s3, azure, local)",type:"string",aliases:["t"],name:"type",required:true})],Re,"storageType"),w([R({description:"Output directory for storage setup",type:"string",aliases:["o"],name:"output",required:false,defaultValue:"src/storage/"})],Re,"outputPath");var ss=[be,Me,ye,we,ie,fe,ve,H,se,Se,Fe,F,xe,Re],Pt=class n{commands;builtInCommands;static commandsPattern="src/commands/**/*.{ts,js}";static logger=b;constructor(){this.commands=new Map,this.builtInCommands=new Set;}static getInstance(){return new n}static setCommandsPattern(e){this.commandsPattern=e;}getCommand(e){return this.commands.get(e)??null}getCommands(){return Array.from(this.commands.values())}getBuiltInCommands(){return Array.from(this.commands.values()).filter(e=>this.builtInCommands.has(e.commandName))}getUserDefinedCommands(){return Array.from(this.commands.values()).filter(e=>!this.builtInCommands.has(e.commandName))}isBuiltInCommand(e){return this.builtInCommands.has(e)}async loadCommands(e){n.logger.info(`Loading commands from ${e}`);let t=await glob(e,{absolute:true,cwd:B.getCwd()});if(t.some(r=>r.endsWith(".ts")))try{let{register:r}=await import('module');r("ts-node/esm",import.meta.url);}catch{n.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 r of t){let s=await import(r).then(o=>o.default?o.default:o).catch(o=>(n.logger.error(`Error loading command ${r}: ${o}`),null));s&&this.commands.set(s.commandName,s);}for(let r of ss)this.commands.set(r.commandName,r),this.builtInCommands.add(r.commandName);}},Ae=Pt.getInstance();var ke=new WeakMap,W=class n extends globalThis.Request{static fromRequest(e){return new n(e.url,{method:e.method,body:e.body,headers:e.headers,signal:e.signal,referrer:e.referrer,referrerPolicy:e.referrerPolicy,mode:e.mode,credentials:e.credentials,cache:e.cache,redirect:e.redirect,integrity:e.integrity,keepalive:e.keepalive})}static compileAndValidate(e,t,r){let s,o;if(ee.isZodSchema(e)){let p=e,l=ke.get(p);l||(l=Symbol("zod_schema"),ke.set(p,l));let d=$.get(l);if(d)return _(d,t,r);s=p.toJSONSchema();let g=N.ajv.compile(s);return $.set(l,g),_(g,t,r)}if(Ce.isTypeBoxSchema(e)){let p=e,l=ke.get(p);l||(l=Symbol("typebox_schema"),ke.set(p,l));let d=$.get(l);if(d)return _(d,t,r);let g=N.ajv.compile(p);return $.set(l,g),_(g,t,r)}let i=e;if(typeof i=="object"&&i!==null){let p=ke.get(i);p||(p=Symbol("json_schema"),ke.set(i,p));let l=$.get(p);if(l)return _(l,t,r);let d=N.ajv.compile(i);return $.set(p,d),_(d,t,r)}o=JSON.stringify(i);let a=$.get(o);if(a)return _(a,t,r);let c=N.ajv.compile(i);return $.set(o,c),_(c,t,r)}ctx={};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=te.randomUUID()),this._id}set id(e){this._id=e;}validate(e,t=false){return n.compileAndValidate(e,this.parsedBody||{},t)}validateQuery(e,t=false){return n.compileAndValidate(e,this.query||{},t)}validateAll(e,t=false){return n.compileAndValidate(e,{...this.parsedBody??{},...this.query??{}},t)}};U();var $e=class{get(e){switch(T.type){case "node":case "bun":case "deno":return process.env[e]??"";default:throw new Error(`Unsupported runtime: ${T.type}`)}}getEnvironment(){switch(T.type){case "node":case "deno":case "bun":return Object.fromEntries(Object.entries(process.env).filter(([e,t])=>t!==void 0))}}};var os=new $e,A=n=>{let e=os.get("NODE_ENV")!=="production";return {code:n.name||"INTERNAL_ERROR",message:n.message,...e&&{stack:n.stack,cause:n.cause}}};var Be=class extends O{constructor(e,t){super(`METHOD_NOT_ALLOWED: Cannot ${t} ${e}`);}};var I=class extends O{constructor(e,t){super(`ROUTE_NOT_FOUND: Cannot ${t} ${e}`);}};U();var Tt=class{file(e,t){switch(T.type){case "bun":case "node":return tt.readFileSync(e,t);case "deno":return Deno.readFileSync(e);default:throw new Error("Unsupported runtime")}}},rt=new Tt;var Wt=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 Kt=(n,e)=>{let{source:t,path:r}=n,s=r;return s.startsWith("/")||(s="/"+s),s!=="/"&&s.endsWith("/")&&(s=s.slice(0,-1)),j.addOrUpdate("GET",`${s}/*`,[],async(o,i)=>is(o,i,t),{service:"StaticFiles",...e}),async(o,i,a)=>a()};async function is(n,e,t){if(n.method!=="GET"&&n.method!=="HEAD")return e.status(405).json({...A(new Be(n.url,n.method))});let r=n.params["*"]||"",s=h.join(t,r),o=h.resolve(B.getCwd(),s),i=h.resolve(B.getCwd(),t);if(!o.startsWith(i))return e.notFound({...A(new I(n.url,n.method))});try{if(!(await u.stat(o)).isFile)return e.notFound({...A(new I(n.url,n.method))})}catch(p){if(p.code==="ENOENT")return e.notFound({...A(new I(n.url,n.method))});throw p}let a=Ot(h.extName(o));e.setHeader("Content-Type",a);let c=rt.file(o);e.raw(c);}function Ot(n){return Wt.get(n)||"application/octet-stream"}var oe=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["Content-Type"]="text/plain";}json(e){this.body=e,this.headers["Content-Type"]="application/json";}html(e){this.body=e,this.headers["Content-Type"]="text/html";}xml(e){this.body=e,this.headers["Content-Type"]="application/xml";}download(e){this.body=e,this.headers["Content-Type"]="application/octet-stream";}file(e,t){let r=h.extName(e),s=Ot(r);this.body=rt.file(e,t),this.headers["Content-Type"]=s;}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["Content-Type"]="text/event-stream",this.headers["Cache-Control"]="no-cache",this.headers.Connection="keep-alive",t?.customHeaders)for(let r in t.customHeaders)this.headers[r]=t.customHeaders[r];if(e instanceof ReadableStream){this.body=e;return}this.body=new ReadableStream({async start(r){for await(let s of e)r.enqueue(new TextEncoder().encode(s));r.close();}});}getBody(){return this.body}};var Z=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,s=r[e];if(s&&typeof s=="object"){r[e]={...s,...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 He=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 s in t){let o=r===""?s:`${r}.${s}`,i=e[s],a=t[s];if(!(s in e))throw new Error(`Expected ${r} to have key ${s}, but it was not found`);if(this.isObject(a)&&this.isObject(i))this.assertSubset(i,a,o);else if(Array.isArray(a)&&Array.isArray(i))this.assertArraySubset(i,a,o);else if(i!==a)throw new Error(`Expected ${o} to be ${a}, but got ${i}`)}}assertDeepEqual(e,t,r){if(this.isObject(e)&&this.isObject(t)){let s=Object.keys(e),o=Object.keys(t);if(s.length!==o.length)throw new Error(`Expected ${r} to have ${o.length} keys, but got ${s.length}`);for(let i of o){let a=r==="body"?i:`${r}.${i}`;this.assertDeepEqual(e[i],t[i],a);}}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(s){if(s instanceof Error&&s.message.includes("Expected"))return;throw s}}assertNotDeepEqual(e,t,r){try{throw this.assertDeepEqual(e,t,r),new Error(`Expected ${r} to NOT be deeply equal, but it is`)}catch(s){if(s instanceof Error&&s.message.includes("Expected"))return;throw s}}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 s=0;s<t.length;s++){let o=`${r}[${s}]`,i=e[s],a=t[s];if(this.isObject(a)&&this.isObject(i))this.assertSubset(i,a,o);else if(Array.isArray(a)&&Array.isArray(i))this.assertArraySubset(i,a,o);else if(i!==a)throw new Error(`Expected ${o} to be ${a}, 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 s=0;s<t.length;s++){let o=`${r}[${s}]`;this.assertDeepEqual(e[s],t[s],o);}}isObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}};var ae=async(n,e,t,r=new oe)=>{let s=0;if(!n.length)return await e(t,r),r;let o=async()=>{if(s++,s>=n.length){await e(t,r);return}let a=n[s];await a(t,r,o);},i=n[0];return await i(t,r,o),r},ce=n=>n?["post","put","patch"].includes(n.toLowerCase()):true,Le=n=>{let e=null,t=false,r=async()=>{for(;t;)await new Promise(o=>setTimeout(o,10));},s=async()=>{try{let{createYoga:o,createSchema:i}=await import('graphql-yoga'),a=n.getSchema(i),c=n.getYogaOptions();return o({graphqlEndpoint:"/graphql",...c,schema:a})}catch(o){throw o instanceof Error&&(o.message.includes("Cannot find module")||o.message.includes("Cannot find package"))?new Error("GraphQL is enabled but 'graphql-yoga' is not installed. Install it with: npm install graphql graphql-yoga"):o}};return async()=>{if(!n.isEnabled)return null;if(e!==null)return e;if(t)return await r(),e;t=true;try{return e=s(),await e}catch(c){throw e=null,c}finally{t=false;}}};var st=class{server;constructor(e){this.server=e;}async request(e,t,r={}){let{headers:s={},query:o={},cookies:i={},ip:a}=r;this.validateOptions(r);let c=j.find(e.toUpperCase(),t);if(!c){let f=new oe(404);return f.json({caller:"MockServer",error:"Route not found",path:t,method:e}),new He(f)}let p=r.body,l="application/json";if(p&&typeof p=="object"&&!(p instanceof Uint8Array)&&!(p instanceof ArrayBuffer)&&(p=JSON.stringify(p)),r.formData){let f=`----WebKitFormBoundary${Math.random().toString(36).substring(2)}`;l=`multipart/form-data; boundary=${f}`,p=await this.formDataToMultipart(r.formData,f);}r.urlencoded&&(l="application/x-www-form-urlencoded",p=new URLSearchParams(r.urlencoded).toString());let d=new URL(`http://${this.server.host}:${this.server.port}${t}`);d.search=new URLSearchParams(o).toString();let g=new W(d.toString(),{method:e.toUpperCase(),body:ce(e)?p:void 0,headers:{"content-type":l,...s}});g.query={...Object.fromEntries(d.searchParams.entries()),...o},g.params=c.params,g.cookies=i,g.ip=a;try{let f=await ae(c.middleware,c.handler,g);return new He(f)}catch(f){b.error({error:f},`Error processing mock request ${e} ${t}:`);let m=new oe(500);return m.json({error:"Internal server error",message:f instanceof Error?f.message:String(f)}),new He(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,s=[];for(let[c,p]of e.entries()){s.push(r.encode(`--${t}\r
434
436
  `));let l=`Content-Disposition: form-data; name="${c}"`,d="";if(p instanceof File&&(l+=`; filename="${p.name}"`,d=`Content-Type: ${p.type||"application/octet-stream"}\r
435
437
  `),s.push(r.encode(`${l}\r
436
438
  ${d}\r
437
- `)),p instanceof File){let h=await p.arrayBuffer();s.push(new Uint8Array(h)),s.push(r.encode(`\r
439
+ `)),p instanceof File){let g=await p.arrayBuffer();s.push(new Uint8Array(g)),s.push(r.encode(`\r
438
440
  `));}else s.push(r.encode(`${String(p)}\r
439
441
  `));}s.push(r.encode(`--${t}--\r
440
- `));let o=s.reduce((c,p)=>c+p.byteLength,0),n=new Uint8Array(o),a=0;for(let c of s)n.set(c,a),a+=c.byteLength;return n}validateOptions(e){let{body:t,formData:r,urlencoded:s}=e;if(t&&(r||s))throw new Error("Only one of body, formData, urlencoded can be provided");if(r&&(s||t))throw new Error("Only one of formData, urlencoded can be provided");if(s&&(t||r))throw new Error("Only one of urlencoded, body can be provided")}};var Be=new AsyncLocalStorage,Ot=i=>async(e,t,r)=>{let s={};for(let[o,n]of Object.entries(i))s[o]=n(e);Be.run(s,()=>{e.ctx=new Proxy({},{get(o,n){return Be.getStore()?.[n]},set(o,n,a){let c=Be.getStore();return c?(c[n]=a,true):false},ownKeys(){let o=Be.getStore();return o?Object.keys(o):[]},has(o,n){let a=Be.getStore();return a?n in a:false}}),r();});};var Kt=()=>async(i,e,t)=>(!ne(i.method)||i.bodyUsed||i.rawBody!==void 0||(i.rawBody=await i.arrayBuffer(),Object.defineProperty(i,"body",{value:void 0,writable:true,configurable:true,enumerable:true})),t());var cs=1024,ps=6,ls=[/text\/.+/,/application\/json/,/application\/javascript/,/application\/xml/,/application\/.*\+json/,/application\/.*\+xml/],Vt=i=>{let e=i?.threshold??cs,t=Math.max(0,Math.min(9,i?.level??ps)),r=i?.filter??ls;return async(s,o,n)=>{if(!(s.headers.get("accept-encoding")||"").includes("gzip"))return n();let p=o.send.bind(o),l=o.json.bind(o),d=o.text.bind(o),h=(m,f)=>{if(!ds(m,f,e,r))return m;let b=Zt(m);if(!b||b.length<e)return m;let q=gzipSync(b,{level:t});return o.setHeader("Content-Encoding","gzip"),o.setHeader("Content-Length",q.length.toString()),q};o.send=function(m){let f=o.headers["content-type"],b=h(m,f);return p(b)},o.json=function(m){let f=JSON.stringify(m),b=h(f,"application/json");return b!==f?(o.setHeader("Content-Type","application/json"),p(b)):l(m)},o.text=function(m){let f=h(m,"text/plain");return f!==m?(o.setHeader("Content-Type","text/plain"),p(f)):d(m)},await n();}},ds=(i,e,t,r)=>{if(!i||!e)return false;let s=Zt(i);return !s||s.length<t?false:r.some(o=>o.test(e))},Zt=i=>typeof i=="string"?Buffer.from(i,"utf-8"):Buffer.isBuffer(i)?i:i instanceof Uint8Array?Buffer.from(i):typeof i=="object"?Buffer.from(JSON.stringify(i),"utf-8"):null;var Jt=i=>{let e={secret:i?.secret??"",defaults:{path:"/",httpOnly:true,secure:true,sameSite:"Lax",...i?.defaults},parse:i?.parse??true,sign:i?.sign??false};return async(t,r,s)=>{if(e.parse){let o=us(t.headers.get("cookie")||"");t.cookies={};for(let[n,a]of Object.entries(o)){if(e.sign&&e.secret){let c=await gs(a,e.secret);c!==false&&(t.cookies[n]=c);continue}t.cookies[n]=a;}}r.cookie=(o,n,a)=>{Yt(r,o,n,{...e.defaults,...a},e);},r.clearCookie=(o,n)=>{ms(r,o,{...e.defaults,...n});},await s();}};function us(i){let e={};if(!i)return e;let t=i.split(";");for(let r of t){let[s,o]=r.trim().split("=");s&&o&&(e[decodeURIComponent(s)]=decodeURIComponent(o));}return e}async function Yt(i,e,t,r,s){let o=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;r.domain&&(o+=`; Domain=${r.domain}`),r.path&&(o+=`; Path=${r.path}`),r.expires&&(o+=`; Expires=${r.expires.toUTCString()}`),r.maxAge&&(o+=`; Max-Age=${r.maxAge}`),r.secure&&(o+="; Secure"),r.httpOnly&&(o+="; HttpOnly"),r.sameSite&&(o+=`; SameSite=${r.sameSite}`),r.priority&&(o+=`; Priority=${r.priority}`),s.sign&&s.secret&&(o=await hs(o,s.secret));let n=i.headers["set-cookie"]||"",a=n?`${n}, ${o}`:o;i.setHeader("Set-Cookie",a);}function ms(i,e,t){let r={...t,expires:new Date(0),maxAge:0};Yt(i,e,"",r,{secret:"",sign:false});}async function hs(i,e){let t=new TextEncoder,r=t.encode(e),s=t.encode(i),o=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},false,["sign"]),n=await crypto.subtle.sign("HMAC",o,s),a=new Uint8Array(n),c=Array.from(a).map(p=>p.toString(16).padStart(2,"0")).join("");return `${i}.${c}`}async function gs(i,e){let t=i.split(".");if(t.length!==2)return false;let[r,s]=t,o=new TextEncoder,n=o.encode(e),a=o.encode(r),c=await crypto.subtle.importKey("raw",n,{name:"HMAC",hash:"SHA-256"},false,["sign"]),p=await crypto.subtle.sign("HMAC",c,a),l=new Uint8Array(p),d=Array.from(l).map(h=>h.toString(16).padStart(2,"0")).join("");return s===d?r:false}var Xt=i=>{let e={origin:"*",methods:["GET","HEAD","PUT","PATCH","POST","DELETE"],allowedHeaders:"",exposedHeaders:"",credentials:false,maxAge:void 0,preflightContinue:false,optionsSuccessStatus:204,...i};return async(t,r,s)=>{let o=t.headers.get("origin")||"";if(t.method==="OPTIONS")return fs(t,r,e,o,s);ys(t,r,e,o),await s();}};function fs(i,e,t,r,s){let o=er(t,r);if(!o){e.forbidden("CORS origin not allowed");return}if(tr(e,t,o),t.preflightContinue){s();return}e.status(t.optionsSuccessStatus||204),e.send("");}function ys(i,e,t,r){let s=er(t,r);s&&tr(e,t,s);}function er(i,e){if(typeof i.origin=="string")return i.origin;if(Array.isArray(i.origin)){let t=i.origin.find(r=>typeof r=="string"?r===e:r instanceof RegExp&&r.test(e));return typeof t=="string"?t:false}return "*"}function tr(i,e,t){if(i.setHeader("Access-Control-Allow-Origin",t),e.credentials&&i.setHeader("Access-Control-Allow-Credentials","true"),e.exposedHeaders&&e.exposedHeaders!==""){let s=Array.isArray(e.exposedHeaders)?e.exposedHeaders.join(","):e.exposedHeaders;i.setHeader("Access-Control-Expose-Headers",s);}if(e.allowedHeaders&&e.allowedHeaders!==""){let s=Array.isArray(e.allowedHeaders)?e.allowedHeaders.join(","):e.allowedHeaders;i.setHeader("Access-Control-Allow-Headers",s);}let r=Array.isArray(e.methods)?e.methods.join(","):e.methods;i.setHeader("Access-Control-Allow-Methods",String(r||"")),typeof e.maxAge=="number"&&i.setHeader("Access-Control-Max-Age",e.maxAge.toString());}function rr(i,e=""){let t=new URL(i.url),r=Object.fromEntries(i.headers.entries());return {body:i.body,query:i.query,params:i.params,cookies:i.cookies,session:i.session,originalUrl:t.pathname+t.search,baseUrl:e,path:t.pathname.replace(e,"")||"/",method:i.method,ip:i.ip,headers:r,url:t.pathname,get(o){return i.headers.get(o.toLowerCase())??void 0},header(o){return i.headers.get(o.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:o=>i.params[o]??i.query[o],files:i.files,file:i.file,rawBody:i.rawBody}}function sr(i){return {locals:{},headersSent:false,statusCode:i.responseStatus,status(t){return i.status(t),this.statusCode=t,this},sendStatus(t){return this.status(t).send(String(t)),this},send(t){if(this.headersSent=true,!!!i.headers["Content-Type"]&&typeof t=="string"){let s=t.trim();if(s.startsWith("<!DOCTYPE")||s.startsWith("<html")||s.startsWith("<HTML"))return i.html(t),this}return i.send(t),this},json(t){return this.headersSent=true,i.json(t),this},redirect(t,r){this.headersSent=true;let s=typeof t=="string"?t:r,o=typeof t=="number"?t:302;return i.status(o).setHeader("Location",s),i.send(""),this},setHeader(t,r){let s=Array.isArray(r)?r.join(", "):String(r);return i.setHeader(t,s),this},set(t,r){if(typeof t=="object")for(let[s,o]of Object.entries(t))i.setHeader(s,o);else r!==void 0&&i.setHeader(t,r);return this},header(t,r){return this.set(t,r)},type(t){return i.setHeader("Content-Type",t),this},contentType(t){return this.type(t)},end(t){return this.headersSent=true,i.send(t??""),this},write(t){return true},get(t){return i.headers[t]},getHeader(t){return i.headers[t]},removeHeader(t){return delete i.headers[t],this},append(t,r){let s=i.headers[t],o=Array.isArray(r)?r.join(", "):r;return i.setHeader(t,s?`${s}, ${o}`:o),this},cookie(t,r,s){return i.cookie?.(t,r,s),this},clearCookie(t,r){return i.clearCookie?.(t,r),this},render(t,r,s){throw new Error("render() is not supported in Express compatibility layer")},format(t){return this},attachment(t){return t?i.setHeader("Content-Disposition",`attachment; filename="${t}"`):i.setHeader("Content-Disposition","attachment"),this},sendFile(t,r,s){i.file(t);},download(t,r,s,o){let n=typeof r=="string"?r:t.split("/").pop();this.attachment(n),i.file(t);},links(t){let r=Object.entries(t).map(([s,o])=>`<${o}>; rel="${s}"`).join(", ");return i.setHeader("Link",r),this},location(t){return i.setHeader("Location",t),this},vary(t){return i.setHeader("Vary",t),this},app:{},req:null}}function Ne(i,e=""){return async(t,r,s)=>{let o=rr(t,e),n=sr(r);await new Promise((a,c)=>{let p=l=>{if(l){c(l);return}a();};try{let l=i(o,n,p);l instanceof Promise&&l.catch(c);}catch(l){c(l);}}),await s();}}function vs(i,e=""){return async(t,r)=>{let s=rr(t,e),o=sr(r);await i(s,o,()=>{});}}function rt(i,e){let t=jt(i),r=e.stack;if(!r){console.warn("Express router has no stack - routes may not be registered");return}for(let s of r)or(s,t);}function or(i,e){if(i.route){let t=jt(e+i.route.path),r=Object.keys(i.route.methods).filter(s=>i.route.methods[s]);for(let s of r){let o=i.route.stack.map(n=>n.handle);ws(s.toUpperCase(),t,o,e);}return}if(i.handle&&typeof i.handle=="function"){let t=i.path||"",r=jt(e+t),s=i.handle.stack;if(s&&Array.isArray(s)){for(let c of s)or(c,r);return}let o=r==="/"?"/*":`${r}/*`,n=Ne(i.handle,e),a=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];for(let c of a)C.addOrUpdate(c,o,[n],async()=>{},{excludeFromSwagger:true});}}function ws(i,e,t,r){let s=t.slice(0,-1).map(a=>Ne(a,r)),o=t[t.length-1],n=vs(o,r);C.addOrUpdate(i,e,s,n,{excludeFromSwagger:true});}function jt(i){let e=i.replace(/\/+/g,"/");return e.startsWith("/")||(e="/"+e),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function ir(i){return {use(e,t){if(typeof e=="string"){let o=e,n=t,a=n.stack;if(a&&Array.isArray(a)){rt(o,n);return}i.use(Ne(n,o));return}let r=e,s=r.stack;if(s&&Array.isArray(s)){rt("/",r);return}i.use(Ne(r));}}}var st=class extends T{constructor(e,t,r){super(`FILE_TOO_LARGE: "${e}" is too large. Max size is ${r} bytes, but got ${t} bytes`);}};Q();var Et=class{async tmpdir(){switch(R.type){case "node":case "bun":return (await import('os')).tmpdir();case "deno":return Deno.makeTempDir();default:throw new Error("Unsupported runtime")}}},nr=new Et;var ar=1024*1024,pr=i=>async(e,t,r)=>{let s=[];try{let o=e.headers.get("content-type")??e.headers.get("Content-Type");if(!o||!o.startsWith("multipart/form-data")||!e.rawBody)return r();let n=o.match(/boundary=(.*)(;|$)/i);if(!n)return r();let a=n[1].replace(/(^\s*"?|"?\s*$)/g,""),c=new Uint8Array(e.rawBody),p=new TextEncoder().encode(`--${a}`),l=new Uint8Array([13,10,13,10]),d=[],h=(P,E,F=0)=>{e:for(let S=F;S<=P.length-E.length;S++){for(let O=0;O<E.length;O++)if(P[S+O]!==E[O])continue e;return S}return -1},m=h(c,p);for(;m!==-1&&(m+=p.length,!(c[m]===45&&c[m+1]===45));){c[m]===13&&c[m+1]===10&&(m+=2);let P=h(c,l,m);if(P===-1)break;let E=c.subarray(m,P),F=new TextDecoder().decode(E),S=P+l.length,O=h(c,p,S);if(O===-1)break;let B=O-1;c[B]===10&&B--,c[B]===13&&B--;let lt=c.subarray(S,B+1);d.push({headers:F,data:lt}),m=O;}let f=[],b={},q=Pe(i?.maxFileSize,ar)??ar;for(let P of d){let E=P.headers.split(`\r
441
- `).find(Qe=>Qe.toLowerCase().startsWith("content-disposition:"));if(!E)continue;let F=E.match(/name="([^"]+)"/);if(!F)continue;let S=F[1],O=E.match(/filename="([^"]*)"/),B=O?O[1]:"";if(!!B){if(i?.maxFiles&&f.length>=i.maxFiles)return t.badRequest({...M(new T(`Too many files: Maximum ${i.maxFiles} files allowed`))});if(q&&P.data.length>q)return t.badRequest({...M(new st(B,P.data.length,q))});let Qe=P.headers.split(`\r
442
- `).find(Hr=>Hr.toLowerCase().startsWith("content-type:")),dt=Qe?Qe.split(":")[1].trim():"application/octet-stream";if(i?.allowedMimeTypes&&!i.allowedMimeTypes.includes(dt))return t.badRequest({...M(new T(`Invalid file type: "${dt}" is not allowed. Allowed types: ${i.allowedMimeTypes.join(", ")}`))});let kr=bs(B),$r=g.extName(kr),ut=g.join(await nr.tmpdir(),`${X.randomUUID()}${$r}`);await u.writeFile(ut,P.data),s.push(ut),f.push({formName:S,mimeType:dt,size:P.data.length,tmpPath:ut,originalName:B});}else b[S]=new TextDecoder().decode(P.data);}e.files=f,e.body=b,await r(),await cr(s);}catch(o){throw await cr(s),o}},cr=async i=>{await Promise.allSettled(i.map(e=>u.unlink(e)));},bs=i=>i.replace(/\.\./g,"").replace(/[\/\\]/g,"").replace(/\0/g,"").replace(/[\x00-\x1f\x80-\x9f]/g,"").trim();var lr=i=>{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,...i};return async(t,r,s)=>{if(e.dnsPrefetchControl&&r.setHeader("X-DNS-Prefetch-Control","off"),e.frameguard){let o="SAMEORIGIN";typeof e.frameguard=="object"&&(o=e.frameguard.action),r.setHeader("X-Frame-Options",o);}if(e.hsts){let o={};typeof e.hsts=="object"&&(o=e.hsts);let n=o.maxAge!==void 0?o.maxAge:15552e3,a=o.includeSubDomains!==void 0?o.includeSubDomains:true,c=o.preload!==void 0?o.preload:false,p=`max-age=${n}`;a!==false&&(p+="; includeSubDomains"),c&&(p+="; preload"),r.setHeader("Strict-Transport-Security",p);}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 s();}};var Ie=class extends T{constructor(e){super(`JSON_NOT_VALID: "${JSON.stringify(e)}" is not a valid JSON`);}};var dr=100*1024,ur=i=>async(e,t,r)=>{if(!Ss(e)||!ne(e.method))return r();let s=Pe(i?.sizeLimit,dr)??dr,o=e.rawBody;if(!o)return i?.parseEmptyBodyAsObject&&(e.body={}),r();let n=o.byteLength;if(!n)return i?.parseEmptyBodyAsObject&&(e.body={}),r();if(n>s){let a={status:413,message:"ERR_REQUEST_BODY_TOO_LARGE",...i?.customErrorMessage};return t.status(a.status).json({error:a.message})}try{let a=i?.encoding??"utf-8",c=new TextDecoder(a).decode(o);e.body=JSON.parse(c);}catch(a){return a instanceof SyntaxError?t.badRequest({...M(new Ie("Invalid JSON syntax"))}):t.badRequest({...M(new Ie("Invalid request body encoding"))})}await r();};function Ss(i){let e=xs(i);return e?Ps(e)==="application/json":false}function xs(i){let e=i.headers.get("content-type")??i.headers.get("Content-Type");return e?Array.isArray(e)?e[0]||null:e:null}function Ps(i){let e=i.trim(),t=e.indexOf(";");return t===-1?e.toLowerCase():e.substring(0,t).trim().toLowerCase()}var hr=i=>async(e,t,r)=>{try{let s=e.body;(i?.logRequest??!0)&&v.info({type:"request",requestId:e.id,method:i?.requestPayload?.method??!0?e.method:void 0,url:i?.requestPayload?.url??!0?e.url:void 0,ip:i?.requestPayload?.ip??!0?e.ip:void 0,headers:i?.requestPayload?.headers??!0?e.headers:void 0,body:i?.requestPayload?.body??!1?mr(s):void 0});let o=performance.now();await r();let a=performance.now()-o;(i?.logResponse??!0)&&v.info({type:"response",requestId:e.id,status:i?.responsePayload?.status??t.responseStatus,duration:`${a.toFixed(2)}ms`,body:i?.responsePayload?.body??!1?mr(t.getBody()):void 0,headers:i?.responsePayload?.headers??!1?t.headers:void 0});}catch(s){throw v.error(s),s}};function mr(i){if(typeof i=="string"||i&&typeof i=="object"&&i.constructor===Object)return i}var Rs=["POST"],Ts="X-HTTP-Method-Override",Cs=["GET","POST","PUT","PATCH","DELETE"],gr=i=>{let e=(i?.methods??Rs).map(r=>r.toUpperCase()),t=i?.header??Ts;return async(r,s,o)=>{let n=r.method.toUpperCase();if(!e.includes(n))return o();let a=r.headers.get(t);if(!a)return o();let c=a.toUpperCase();if(!Cs.includes(c))return o();r.method=c,await o();}};var ot=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 fr=(i,e)=>{let t={type:"ip",limit:100,message:"ERR_RATE_LIMIT_EXCEEDED",statusCode:429,...i},r={type:"memory",...e};r.type==="memory"&&!r.windowMs&&(r.windowMs=6e4);let s=r.type==="memory"?new ot(r.windowMs):{get:r.get,set:r.set};return async(o,n,a)=>{let c=t.type==="ip"?o.ip:t.key(o),p=await s.get(c);return p>=t.limit?n.status(t.statusCode).json({message:t.message}):(await s.set(c,p+1),a())}};var it=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 s=r?Date.now()+r*1e3:void 0;this.store.set(e,{value:t,exp:s});}async destroy(e){this.store.delete(e);}};var yr=i=>{let e=i?.name??"sid",t=i?.ttl??3600*24,r=i?.store??new it,s={path:"/",httpOnly:true,secure:false,sameSite:"Lax",...i?.cookie??{}};return async(o,n,a)=>{let p=o.cookies&&o.cookies[e],l=p?await r.get(p):void 0;(!p||!l)&&(p||=X.randomUUID(),l||={},await r.set(p,l,t),n.cookie?.(e,p,s)),o.session=l,o.saveSession=async()=>r.set(p,l,t),o.destroySession=async()=>{await r.destroy(p),n.clearCookie?.(e,s);},await a(),await r.set(p,l,t);}};var wr=i=>{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:{}};i&&typeof i!="boolean"&&(e={...e,...i});let t=Os(e),r=`${e.path}`,s=`${r}/json`,o;e.type==="rapidoc"?o=Es(s,e):e.type==="scalar"?o=qs(s,e):e.type==="elements"?o=Ms(s,e):e.type==="custom"?o=e.customUIGenerator(s,e):o=js(s,e),C.addOrUpdate("GET",r,[],(n,a)=>{a.html(o);}),C.addOrUpdate("GET",s,[],(n,a)=>{a.json(t);});},ae=i=>i?i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;"):"";function Se(i){return !i||typeof i!="object"?{type:"string"}:i}function Os(i){let e=C.getRoutes(),t={},r;if(i.models)if(Array.isArray(i.models))r=i.models.reduce((o,n,a)=>{let c=Se(n),p=c.$id||c.title||`Model${a}`;return o[p]=c,o},{});else {r={};for(let[o,n]of Object.entries(i.models))r[o]=Se(n);}let s={...i.components,securitySchemes:i.securitySchemes||{},schemas:r?{...i.components?.schemas||{},...r}:i.components?.schemas?{...i.components.schemas}:void 0};for(let o of e){let n=o.swaggerOptions;if(n?.excludeFromSwagger)continue;t[o.path]||(t[o.path]={});let a=o.method.toLowerCase(),c={summary:n?.name||`${a.toUpperCase()} ${o.path}`,description:n?.description||"",tags:n?.service?[n.service]:[],deprecated:n?.deprecated||false},p=[];if(n?.query&&n.query.type==="object"&&n.query.shape)for(let[l,d]of Object.entries(n.query.shape))!d||typeof d!="object"||p.push({name:l,in:"query",required:Array.isArray(n.query.shape[l].required)?n.query.shape[l].required.includes(l):false,schema:Se(d)});if(n&&n.params?p=p.concat(vr(o.path,n.params)):p=p.concat(vr(o.path)),p.length>0&&(c.parameters=p),n?.requestBody){let l="application/json";n.bodyType==="form-data"?l="multipart/form-data":n.bodyType==="urlencoded"&&(l="application/x-www-form-urlencoded"),c.requestBody={content:{[l]:{schema:Se(n.requestBody)}},required:true};}else n?.bodyType&&(n.bodyType.includes("form-data")||n.bodyType.includes("urlencoded"))&&(c.requestBody={content:{[n.bodyType]:{schema:{type:"object"}}},required:true});if(c.responses={},n?.responses)for(let[l,d]of Object.entries(n.responses))c.responses[l]={description:`Response for ${l}`,content:{"application/json":{schema:Se(d)}}};if(n?.errors)for(let[l,d]of Object.entries(n.errors))c.responses[l]={description:`Error response for ${l}`,content:{"application/json":{schema:Se(d)}}};if(Object.keys(c.responses).length===0&&(c.responses[200]={description:"Successful response",content:{"application/json":{schema:{type:"object"}}}}),n?.security){let l=[];Array.isArray(n.security)||(n.security=[n.security]);for(let d of n.security)if(d.type==="bearer")s.securitySchemes.bearer||(s.securitySchemes.bearer={type:"http",scheme:"bearer",bearerFormat:d.bearerFormat||"JWT",description:d.description}),l.push({bearer:[]});else if(d.type==="apiKey")s.securitySchemes[d.name]||(s.securitySchemes[d.name]={type:"apiKey",name:d.name,in:d.in,description:d.description}),l.push({[d.name]:[]});else if(d.type==="oauth2"){let h=d.name||"oauth2";s.securitySchemes[h]||(s.securitySchemes[h]={type:"oauth2",flows:d.flows,description:d.description}),l.push({[h]:[]});}else if(d.type==="openIdConnect"){let h=d.name||"openIdConnect";s.securitySchemes[h]||(s.securitySchemes[h]={type:"openIdConnect",openIdConnectUrl:d.openIdConnectUrl,description:d.description}),l.push({[h]:[]});}l.length&&(c.security=l);}else i.security&&(c.security=i.security);t[o.path][a]=c;}return {openapi:"3.0.0",info:{title:i.title,description:i.description,version:i.version,...i.info},servers:i.servers?.map(o=>({url:o}))||[{url:"/"}],paths:t,components:s,security:i.security||[],tags:i.tags?Object.entries(i.tags).map(([o,n])=>({name:o,...n})):[]}}function js(i,e){return `
442
+ `));let o=s.reduce((c,p)=>c+p.byteLength,0),i=new Uint8Array(o),a=0;for(let c of s)i.set(c,a),a+=c.byteLength;return i}validateOptions(e){let{body:t,formData:r,urlencoded:s}=e;if(t&&(r||s))throw new Error("Only one of body, formData, urlencoded can be provided");if(r&&(s||t))throw new Error("Only one of formData, urlencoded can be provided");if(s&&(t||r))throw new Error("Only one of urlencoded, body can be provided")}};var Ne=new AsyncLocalStorage,Ct=n=>async(e,t,r)=>{let s={};for(let[o,i]of Object.entries(n))s[o]=i(e);Ne.run(s,()=>{e.ctx=new Proxy({},{get(o,i){return Ne.getStore()?.[i]},set(o,i,a){let c=Ne.getStore();return c?(c[i]=a,true):false},ownKeys(){let o=Ne.getStore();return o?Object.keys(o):[]},has(o,i){let a=Ne.getStore();return a?i in a:false}}),r();});};var ps=1024,ls=6,ds=[/text\/.+/,/application\/json/,/application\/javascript/,/application\/xml/,/application\/.*\+json/,/application\/.*\+xml/],Vt=n=>{let e=n?.threshold??ps,t=Math.max(0,Math.min(9,n?.level??ls)),r=n?.filter??ds;return async(s,o,i)=>{if(!(s.headers.get("accept-encoding")||"").includes("gzip"))return i();let p=o.send.bind(o),l=o.json.bind(o),d=o.text.bind(o),g=(f,m)=>{if(!us(f,m,e,r))return f;let y=Zt(f);if(!y||y.length<e)return f;let S=gzipSync(y,{level:t});return o.setHeader("Content-Encoding","gzip"),o.setHeader("Content-Length",S.length.toString()),S};o.send=function(f){let m=o.headers["content-type"],y=g(f,m);return p(y)},o.json=function(f){let m=JSON.stringify(f),y=g(m,"application/json");return y!==m?(o.setHeader("Content-Type","application/json"),p(y)):l(f)},o.text=function(f){let m=g(f,"text/plain");return m!==f?(o.setHeader("Content-Type","text/plain"),p(m)):d(f)},await i();}},us=(n,e,t,r)=>{if(!n||!e)return false;let s=Zt(n);return !s||s.length<t?false:r.some(o=>o.test(e))},Zt=n=>typeof n=="string"?Buffer.from(n,"utf-8"):Buffer.isBuffer(n)?n:n instanceof Uint8Array?Buffer.from(n):typeof n=="object"?Buffer.from(JSON.stringify(n),"utf-8"):null;var Jt=n=>{let e={secret:n?.secret??"",defaults:{path:"/",httpOnly:true,secure:true,sameSite:"Lax",...n?.defaults},parse:n?.parse??true,sign:n?.sign??false};return async(t,r,s)=>{if(e.parse){let o=ms(t.headers.get("cookie")||"");t.cookies={};for(let[i,a]of Object.entries(o)){if(e.sign&&e.secret){let c=await fs(a,e.secret);c!==false&&(t.cookies[i]=c);continue}t.cookies[i]=a;}}r.cookie=(o,i,a)=>{Yt(r,o,i,{...e.defaults,...a},e);},r.clearCookie=(o,i)=>{hs(r,o,{...e.defaults,...i});},await s();}};function ms(n){let e={};if(!n)return e;let t=n.split(";");for(let r of t){let[s,o]=r.trim().split("=");s&&o&&(e[decodeURIComponent(s)]=decodeURIComponent(o));}return e}async function Yt(n,e,t,r,s){let o=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;r.domain&&(o+=`; Domain=${r.domain}`),r.path&&(o+=`; Path=${r.path}`),r.expires&&(o+=`; Expires=${r.expires.toUTCString()}`),r.maxAge&&(o+=`; Max-Age=${r.maxAge}`),r.secure&&(o+="; Secure"),r.httpOnly&&(o+="; HttpOnly"),r.sameSite&&(o+=`; SameSite=${r.sameSite}`),r.priority&&(o+=`; Priority=${r.priority}`),s.sign&&s.secret&&(o=await gs(o,s.secret));let i=n.headers["set-cookie"]||"",a=i?`${i}, ${o}`:o;n.setHeader("Set-Cookie",a);}function hs(n,e,t){let r={...t,expires:new Date(0),maxAge:0};Yt(n,e,"",r,{secret:"",sign:false});}async function gs(n,e){let t=new TextEncoder,r=t.encode(e),s=t.encode(n),o=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},false,["sign"]),i=await crypto.subtle.sign("HMAC",o,s),a=new Uint8Array(i),c=Array.from(a).map(p=>p.toString(16).padStart(2,"0")).join("");return `${n}.${c}`}async function fs(n,e){let t=n.split(".");if(t.length!==2)return false;let[r,s]=t,o=new TextEncoder,i=o.encode(e),a=o.encode(r),c=await crypto.subtle.importKey("raw",i,{name:"HMAC",hash:"SHA-256"},false,["sign"]),p=await crypto.subtle.sign("HMAC",c,a),l=new Uint8Array(p),d=Array.from(l).map(g=>g.toString(16).padStart(2,"0")).join("");return s===d?r:false}var Xt=n=>{let e={origin:"*",methods:["GET","HEAD","PUT","PATCH","POST","DELETE"],allowedHeaders:"",exposedHeaders:"",credentials:false,maxAge:void 0,preflightContinue:false,optionsSuccessStatus:204,...n};return async(t,r,s)=>{let o=t.headers.get("origin")||"";if(t.method==="OPTIONS")return ys(t,r,e,o,s);vs(t,r,e,o),await s();}};function ys(n,e,t,r,s){let o=er(t,r);if(!o){e.forbidden("CORS origin not allowed");return}if(tr(e,t,o),t.preflightContinue){s();return}e.status(t.optionsSuccessStatus||204),e.send("");}function vs(n,e,t,r){let s=er(t,r);s&&tr(e,t,s);}function er(n,e){if(typeof n.origin=="string")return n.origin;if(Array.isArray(n.origin)){let t=n.origin.find(r=>typeof r=="string"?r===e:r instanceof RegExp&&r.test(e));return typeof t=="string"?t:false}return "*"}function tr(n,e,t){if(n.setHeader("Access-Control-Allow-Origin",t),e.credentials&&n.setHeader("Access-Control-Allow-Credentials","true"),e.exposedHeaders&&e.exposedHeaders!==""){let s=Array.isArray(e.exposedHeaders)?e.exposedHeaders.join(","):e.exposedHeaders;n.setHeader("Access-Control-Expose-Headers",s);}if(e.allowedHeaders&&e.allowedHeaders!==""){let s=Array.isArray(e.allowedHeaders)?e.allowedHeaders.join(","):e.allowedHeaders;n.setHeader("Access-Control-Allow-Headers",s);}let r=Array.isArray(e.methods)?e.methods.join(","):e.methods;n.setHeader("Access-Control-Allow-Methods",String(r||"")),typeof e.maxAge=="number"&&n.setHeader("Access-Control-Max-Age",e.maxAge.toString());}function rr(n,e=""){let t=new URL(n.url),r=Object.fromEntries(n.headers.entries());return {body:n.parsedBody,query:n.query,params:n.params,cookies:n.cookies,session:n.session,originalUrl:t.pathname+t.search,baseUrl:e,path:t.pathname.replace(e,"")||"/",method:n.method,ip:n.ip,headers:r,url:t.pathname,get(o){return n.headers.get(o.toLowerCase())??void 0},header(o){return n.headers.get(o.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:o=>n.params[o]??n.query[o],files:n.files,file:n.file,rawBody:n.parsedBody}}function sr(n){return {locals:{},headersSent:false,statusCode:n.responseStatus,status(t){return n.status(t),this.statusCode=t,this},sendStatus(t){return this.status(t).send(String(t)),this},send(t){if(this.headersSent=true,!!!n.headers["Content-Type"]&&typeof t=="string"){let s=t.trim();if(s.startsWith("<!DOCTYPE")||s.startsWith("<html")||s.startsWith("<HTML"))return n.html(t),this}return n.send(t),this},json(t){return this.headersSent=true,n.json(t),this},redirect(t,r){this.headersSent=true;let s=typeof t=="string"?t:r,o=typeof t=="number"?t:302;return n.status(o).setHeader("Location",s),n.send(""),this},setHeader(t,r){let s=Array.isArray(r)?r.join(", "):String(r);return n.setHeader(t,s),this},set(t,r){if(typeof t=="object")for(let[s,o]of Object.entries(t))n.setHeader(s,o);else r!==void 0&&n.setHeader(t,r);return this},header(t,r){return this.set(t,r)},type(t){return n.setHeader("Content-Type",t),this},contentType(t){return this.type(t)},end(t){return this.headersSent=true,n.send(t??""),this},write(t){return true},get(t){return n.headers[t]},getHeader(t){return n.headers[t]},removeHeader(t){return delete n.headers[t],this},append(t,r){let s=n.headers[t],o=Array.isArray(r)?r.join(", "):r;return n.setHeader(t,s?`${s}, ${o}`:o),this},cookie(t,r,s){return n.cookie?.(t,r,s),this},clearCookie(t,r){return n.clearCookie?.(t,r),this},render(t,r,s){throw new Error("render() is not supported in Express compatibility layer")},format(t){return this},attachment(t){return t?n.setHeader("Content-Disposition",`attachment; filename="${t}"`):n.setHeader("Content-Disposition","attachment"),this},sendFile(t,r,s){n.file(t);},download(t,r,s,o){let i=typeof r=="string"?r:t.split("/").pop();this.attachment(i),n.file(t);},links(t){let r=Object.entries(t).map(([s,o])=>`<${o}>; rel="${s}"`).join(", ");return n.setHeader("Link",r),this},location(t){return n.setHeader("Location",t),this},vary(t){return n.setHeader("Vary",t),this},app:{},req:null}}function _e(n,e=""){return async(t,r,s)=>{let o=rr(t,e),i=sr(r);await new Promise((a,c)=>{let p=l=>{if(l){c(l);return}a();};try{let l=n(o,i,p);l instanceof Promise&&l.catch(c);}catch(l){c(l);}}),await s();}}function ws(n,e=""){return async(t,r)=>{let s=rr(t,e),o=sr(r);await n(s,o,()=>{});}}function ot(n,e){let t=jt(n),r=e.stack;if(!r){console.warn("Express router has no stack - routes may not be registered");return}for(let s of r)or(s,t);}function or(n,e){if(n.route){let t=jt(e+n.route.path),r=Object.keys(n.route.methods).filter(s=>n.route.methods[s]);for(let s of r){let o=n.route.stack.map(i=>i.handle);bs(s.toUpperCase(),t,o,e);}return}if(n.handle&&typeof n.handle=="function"){let t=n.path||"",r=jt(e+t),s=n.handle.stack;if(s&&Array.isArray(s)){for(let c of s)or(c,r);return}let o=r==="/"?"/*":`${r}/*`,i=_e(n.handle,e),a=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];for(let c of a)j.addOrUpdate(c,o,[i],async()=>{},{excludeFromSwagger:true});}}function bs(n,e,t,r){let s=t.slice(0,-1).map(a=>_e(a,r)),o=t[t.length-1],i=ws(o,r);j.addOrUpdate(n,e,s,i,{excludeFromSwagger:true});}function jt(n){let e=n.replace(/\/+/g,"/");return e.startsWith("/")||(e="/"+e),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function nr(n){return {use(e,t){if(typeof e=="string"){let o=e,i=t,a=i.stack;if(a&&Array.isArray(a)){ot(o,i);return}n.use(_e(i,o));return}let r=e,s=r.stack;if(s&&Array.isArray(s)){ot("/",r);return}n.use(_e(r));}}}var ir=n=>{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,...n};return async(t,r,s)=>{if(e.dnsPrefetchControl&&r.setHeader("X-DNS-Prefetch-Control","off"),e.frameguard){let o="SAMEORIGIN";typeof e.frameguard=="object"&&(o=e.frameguard.action),r.setHeader("X-Frame-Options",o);}if(e.hsts){let o={};typeof e.hsts=="object"&&(o=e.hsts);let i=o.maxAge!==void 0?o.maxAge:15552e3,a=o.includeSubDomains!==void 0?o.includeSubDomains:true,c=o.preload!==void 0?o.preload:false,p=`max-age=${i}`;a!==false&&(p+="; includeSubDomains"),c&&(p+="; preload"),r.setHeader("Strict-Transport-Security",p);}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 s();}};var cr=n=>async(e,t,r)=>{try{let s=e.parsedBody;(n?.logRequest??!0)&&b.info({type:"request",requestId:e.id,method:n?.requestPayload?.method??!0?e.method:void 0,url:n?.requestPayload?.url??!0?e.url:void 0,ip:n?.requestPayload?.ip??!0?e.ip:void 0,headers:n?.requestPayload?.headers??!0?e.headers:void 0,body:n?.requestPayload?.body??!1?ar(s):void 0});let o=performance.now();await r();let a=performance.now()-o;(n?.logResponse??!0)&&b.info({type:"response",requestId:e.id,status:n?.responsePayload?.status??t.responseStatus,duration:`${a.toFixed(2)}ms`,body:n?.responsePayload?.body??!1?ar(t.getBody()):void 0,headers:n?.responsePayload?.headers??!1?t.headers:void 0});}catch(s){throw b.error(s),s}};function ar(n){if(typeof n=="string"||n&&typeof n=="object"&&n.constructor===Object)return n}var Ss=["POST"],xs="X-HTTP-Method-Override",Rs=["GET","POST","PUT","PATCH","DELETE"],pr=n=>{let e=(n?.methods??Ss).map(r=>r.toUpperCase()),t=n?.header??xs;return async(r,s,o)=>{let i=r.method.toUpperCase();if(!e.includes(i))return o();let a=r.headers.get(t);if(!a)return o();let c=a.toUpperCase();if(!Rs.includes(c))return o();r.method=c,await o();}};var nt=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 lr=(n,e)=>{let t={type:"ip",limit:100,message:"ERR_RATE_LIMIT_EXCEEDED",statusCode:429,...n},r={type:"memory",...e};r.type==="memory"&&!r.windowMs&&(r.windowMs=6e4);let s=r.type==="memory"?new nt(r.windowMs):{get:r.get,set:r.set};return async(o,i,a)=>{let c=t.type==="ip"?o.ip:t.key(o),p=await s.get(c);return p>=t.limit?i.status(t.statusCode).json({message:t.message}):(await s.set(c,p+1),a())}};var it=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 s=r?Date.now()+r*1e3:void 0;this.store.set(e,{value:t,exp:s});}async destroy(e){this.store.delete(e);}};var dr=n=>{let e=n?.name??"sid",t=n?.ttl??3600*24,r=n?.store??new it,s={path:"/",httpOnly:true,secure:false,sameSite:"Lax",...n?.cookie??{}};return async(o,i,a)=>{let p=o.cookies&&o.cookies[e],l=p?await r.get(p):void 0;(!p||!l)&&(p||=te.randomUUID(),l||={},await r.set(p,l,t),i.cookie?.(e,p,s)),o.session=l,o.saveSession=async()=>r.set(p,l,t),o.destroySession=async()=>{await r.destroy(p),i.clearCookie?.(e,s);},await a(),await r.set(p,l,t);}};var mr=n=>{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:{}};n&&typeof n!="boolean"&&(e={...e,...n});let t=Ps(e),r=`${e.path}`,s=`${r}/json`,o;e.type==="rapidoc"?o=Os(s,e):e.type==="scalar"?o=Cs(s,e):e.type==="elements"?o=js(s,e):e.type==="custom"?o=e.customUIGenerator(s,e):o=Ts(s,e),j.addOrUpdate("GET",r,[],(i,a)=>{a.html(o);}),j.addOrUpdate("GET",s,[],(i,a)=>{a.json(t);});},pe=n=>n?n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;"):"";function Pe(n){return !n||typeof n!="object"?{type:"string"}:n}function Ps(n){let e=j.getRoutes(),t={},r;if(n.models)if(Array.isArray(n.models))r=n.models.reduce((o,i,a)=>{let c=Pe(i),p=c.$id||c.title||`Model${a}`;return o[p]=c,o},{});else {r={};for(let[o,i]of Object.entries(n.models))r[o]=Pe(i);}let s={...n.components,securitySchemes:n.securitySchemes||{},schemas:r?{...n.components?.schemas||{},...r}:n.components?.schemas?{...n.components.schemas}:void 0};for(let o of e){let i=o.swaggerOptions;if(i?.excludeFromSwagger)continue;t[o.path]||(t[o.path]={});let a=o.method.toLowerCase(),c={summary:i?.name||`${a.toUpperCase()} ${o.path}`,description:i?.description||"",tags:i?.service?[i.service]:[],deprecated:i?.deprecated||false},p=[];if(i?.query&&i.query.type==="object"&&i.query.shape)for(let[l,d]of Object.entries(i.query.shape))!d||typeof d!="object"||p.push({name:l,in:"query",required:Array.isArray(i.query.shape[l].required)?i.query.shape[l].required.includes(l):false,schema:Pe(d)});if(i&&i.params?p=p.concat(ur(o.path,i.params)):p=p.concat(ur(o.path)),p.length>0&&(c.parameters=p),i?.requestBody){let l="application/json";i.bodyType==="form-data"?l="multipart/form-data":i.bodyType==="urlencoded"&&(l="application/x-www-form-urlencoded"),c.requestBody={content:{[l]:{schema:Pe(i.requestBody)}},required:true};}else i?.bodyType&&(i.bodyType.includes("form-data")||i.bodyType.includes("urlencoded"))&&(c.requestBody={content:{[i.bodyType]:{schema:{type:"object"}}},required:true});if(c.responses={},i?.responses)for(let[l,d]of Object.entries(i.responses))c.responses[l]={description:`Response for ${l}`,content:{"application/json":{schema:Pe(d)}}};if(i?.errors)for(let[l,d]of Object.entries(i.errors))c.responses[l]={description:`Error response for ${l}`,content:{"application/json":{schema:Pe(d)}}};if(Object.keys(c.responses).length===0&&(c.responses[200]={description:"Successful response",content:{"application/json":{schema:{type:"object"}}}}),i?.security){let l=[];Array.isArray(i.security)||(i.security=[i.security]);for(let d of i.security)if(d.type==="bearer")s.securitySchemes.bearer||(s.securitySchemes.bearer={type:"http",scheme:"bearer",bearerFormat:d.bearerFormat||"JWT",description:d.description}),l.push({bearer:[]});else if(d.type==="apiKey")s.securitySchemes[d.name]||(s.securitySchemes[d.name]={type:"apiKey",name:d.name,in:d.in,description:d.description}),l.push({[d.name]:[]});else if(d.type==="oauth2"){let g=d.name||"oauth2";s.securitySchemes[g]||(s.securitySchemes[g]={type:"oauth2",flows:d.flows,description:d.description}),l.push({[g]:[]});}else if(d.type==="openIdConnect"){let g=d.name||"openIdConnect";s.securitySchemes[g]||(s.securitySchemes[g]={type:"openIdConnect",openIdConnectUrl:d.openIdConnectUrl,description:d.description}),l.push({[g]:[]});}l.length&&(c.security=l);}else n.security&&(c.security=n.security);t[o.path][a]=c;}return {openapi:"3.0.0",info:{title:n.title,description:n.description,version:n.version,...n.info},servers:n.servers?.map(o=>({url:o}))||[{url:"/"}],paths:t,components:s,security:n.security||[],tags:n.tags?Object.entries(n.tags).map(([o,i])=>({name:o,...i})):[]}}function Ts(n,e){return `
443
443
  <!DOCTYPE html>
444
444
  <html lang="en">
445
445
  <head>
446
446
  <meta charset="utf-8" />
447
447
  <meta name="viewport" content="width=device-width, initial-scale=1" />
448
- <meta name="description" content="${ae(e.description)}" />
449
- <title>${ae(e.title)}</title>
448
+ <meta name="description" content="${pe(e.description)}" />
449
+ <title>${pe(e.title)}</title>
450
450
  <link rel="stylesheet" type="text/css" href="https://unpkg.com/swagger-ui-dist@5.9.0/swagger-ui.css" />
451
451
  <style>
452
452
  html {
@@ -470,7 +470,7 @@ ${d}\r
470
470
  <script>
471
471
  window.onload = function() {
472
472
  const ui = SwaggerUIBundle({
473
- url: '${i}',
473
+ url: '${n}',
474
474
  dom_id: '#swagger-ui',
475
475
  deepLinking: true,
476
476
  presets: [
@@ -487,14 +487,14 @@ ${d}\r
487
487
  };
488
488
  </script>
489
489
  </body>
490
- </html>`}function Es(i,e){return `
490
+ </html>`}function Os(n,e){return `
491
491
  <!DOCTYPE html>
492
492
  <html>
493
493
  <head>
494
- <title>${ae(e.title)}</title>
494
+ <title>${pe(e.title)}</title>
495
495
  <meta charset="utf-8"/>
496
496
  <meta name="viewport" content="width=device-width, initial-scale=1">
497
- <meta name="description" content="${ae(e.description)}" />
497
+ <meta name="description" content="${pe(e.description)}" />
498
498
  <link rel="icon" type="image/png" href="https://mrin9.github.io/RapiDoc/images/favicon.png">
499
499
  <style>
500
500
  body { margin: 0; padding: 0; }
@@ -502,7 +502,7 @@ ${d}\r
502
502
  </head>
503
503
  <body>
504
504
  <rapi-doc
505
- spec-url="${i}"
505
+ spec-url="${n}"
506
506
  render-style="read"
507
507
  layout="column"
508
508
  show-header="true"
@@ -518,14 +518,14 @@ ${d}\r
518
518
  <script type="module" src="https://unpkg.com/rapidoc/dist/rapidoc-min.js"></script>
519
519
  </body>
520
520
  </html>
521
- `}function qs(i,e){return `
521
+ `}function Cs(n,e){return `
522
522
  <!DOCTYPE html>
523
523
  <html lang="en">
524
524
  <head>
525
525
  <meta charset="utf-8" />
526
526
  <meta name="viewport" content="width=device-width, initial-scale=1" />
527
- <meta name="description" content="${ae(e.description)}" />
528
- <title>${ae(e.title)}</title>
527
+ <meta name="description" content="${pe(e.description)}" />
528
+ <title>${pe(e.title)}</title>
529
529
  <style>
530
530
  body {
531
531
  margin: 0;
@@ -537,19 +537,19 @@ ${d}\r
537
537
  <script
538
538
  id="api-reference"
539
539
  type="application/json"
540
- data-configuration='{"spec":{"url":"${i}"},"theme":"default"}'
540
+ data-configuration='{"spec":{"url":"${n}"},"theme":"default"}'
541
541
  ></script>
542
542
  <script src="https://unpkg.com/@scalar/api-reference@latest/dist/browser/standalone.js"></script>
543
543
  </body>
544
544
  </html>
545
- `}function Ms(i,e){return `
545
+ `}function js(n,e){return `
546
546
  <!DOCTYPE html>
547
547
  <html lang="en">
548
548
  <head>
549
549
  <meta charset="utf-8" />
550
550
  <meta name="viewport" content="width=device-width, initial-scale=1" />
551
- <meta name="description" content="${ae(e.description)}" />
552
- <title>${ae(e.title)}</title>
551
+ <meta name="description" content="${pe(e.description)}" />
552
+ <title>${pe(e.title)}</title>
553
553
  <link rel="stylesheet" href="https://unpkg.com/@stoplight/elements@7.7.9/styles.min.css">
554
554
  <style>
555
555
  body {
@@ -562,13 +562,15 @@ ${d}\r
562
562
  </head>
563
563
  <body>
564
564
  <elements-api
565
- apiDescriptionUrl="${i}"
565
+ apiDescriptionUrl="${n}"
566
566
  router="hash"
567
567
  layout="sidebar"
568
568
  />
569
569
  <script src="https://unpkg.com/@stoplight/elements@7.7.9/web-components.min.js"></script>
570
570
  </body>
571
571
  </html>
572
- `}function vr(i,e){let t=[],r=/:([a-zA-Z0-9_]+)/g,s;for(;(s=r.exec(i))!==null;){let o=s[1],n={type:"string"};e&&e.shape&&e.shape[o]&&(n=Se(e.shape[o])||{type:"string"}),t.push({name:o,in:"path",required:true,schema:n});}return t}var br=i=>async(e,t,r)=>{e.timeout=false;let s=setTimeout(()=>{e.timeout=true;},i.ms);try{await r();}finally{clearTimeout(s);}};var Sr=i=>{let e=i?.header??"x-forwarded-for",t=i?.trust??true,r=i?.hop??"first";return async(s,o,n)=>{if(!t)return n();let a=s.headers.get(e);if(a&&typeof a=="string"){let c=a.split(",").map(p=>p.trim()).filter(Boolean);c.length&&(s.ip=r==="first"?c[0]:c[c.length-1]);}return n()}};var xr=1024*1024,Pr=i=>{let t={limit:Pe(i?.limit,xr)??xr,extended:i?.extended??false,charset:i?.charset??"utf8",allowEmpty:i?.allowEmpty??true,parameterLimit:i?.parameterLimit??1e3};return async(r,s,o)=>{if(!(r.headers.get("content-type")||"").includes("application/x-www-form-urlencoded"))return o();try{await As(r,t),await o();}catch(a){if(a instanceof Error&&a.message.includes("limit")){s.status(413).json({error:"Payload too large",message:"Request body exceeds the size limit"});return}throw a}}};async function As(i,e){let t=i.rawBody;if(t.byteLength>e.limit)throw new Error(`Body size ${t.byteLength} exceeds limit ${e.limit}`);let s=new TextDecoder(e.charset).decode(t),o=ks(s,e);i.body=o;}function ks(i,e){let t={},r=new URLSearchParams(i);if(r.size>e.parameterLimit)throw new Error(`Too many parameters: ${r.size} exceeds limit ${e.parameterLimit}`);for(let[s,o]of r.entries())!e.allowEmpty&&o===""||(e.extended?$s(t,s,o):t[s]=o);return t}function $s(i,e,t){let r=["__proto__","constructor","prototype"];if(r.includes(e))return;let s=e.match(/\[([^\]]*)\]/g);if(!s){r.includes(e)||(i[e]=t);return}let o=i,n=e.split("[")[0];if(r.includes(n))return;for(let c=0;c<s.length-1;c++){let p=s[c].slice(1,-1);if(r.includes(p))return;if(o[n]||(o[n]={}),p===""){Array.isArray(o[n])||(o[n]=[]),o=o[n];continue}o[n][p]||(o[n][p]={}),o=o[n][p];}let a=s[s.length-1].slice(1,-1);if(!r.includes(a)){if(a===""){Array.isArray(o)||(o=[]),o.push(t);return}o[a]=t;}}var qt=class{ITERATIONS=6e5;SALT_LENGTH=16;KEY_LENGTH=256;configure(e){if(e.iterations!==void 0){if(e.iterations<1)throw new Error("Iterations must be at least 1");this.ITERATIONS=e.iterations;}if(e.saltLength!==void 0){if(e.saltLength<8)throw new Error("Salt length must be at least 8 bytes");this.SALT_LENGTH=e.saltLength;}if(e.keyLength!==void 0){if(e.keyLength<128)throw new Error("Key length must be at least 128 bits");this.KEY_LENGTH=e.keyLength;}}async hash(e){if(!e)throw new Error("Data to hash cannot be empty");let r=new TextEncoder().encode(e),s=crypto.getRandomValues(new Uint8Array(this.SALT_LENGTH)),o=await crypto.subtle.importKey("raw",r,{name:"PBKDF2"},false,["deriveBits"]),n=await crypto.subtle.deriveBits({name:"PBKDF2",salt:s,iterations:this.ITERATIONS,hash:"SHA-256"},o,this.KEY_LENGTH),a=this.encodeBase64(s),c=this.encodeBase64(new Uint8Array(n));return `${a}:${c}`}async compare(e,t){if(!e||!t)return false;try{let s=new TextEncoder().encode(t),o=e.split(":");if(o.length!==2)throw new Error("Invalid hash format");let[n,a]=o,c=this.decodeBase64(n),p=this.decodeBase64(a),l=await crypto.subtle.importKey("raw",s,{name:"PBKDF2"},!1,["deriveBits"]),d=await crypto.subtle.deriveBits({name:"PBKDF2",salt:c,iterations:this.ITERATIONS,hash:"SHA-256"},l,this.KEY_LENGTH),h=new Uint8Array(d);if(h.length!==p.length)return !1;let m=0;for(let f=0;f<h.length;f++)m|=h[f]^p[f];return m===0}catch{return false}}encodeBase64(e){let t="",r=e.byteLength;for(let s=0;s<r;s++)t+=String.fromCharCode(e[s]);return btoa(t)}decodeBase64(e){let t=atob(e),r=t.length,s=new Uint8Array(r);for(let o=0;o<r;o++)s[o]=t.charCodeAt(o);return s}},Fe=new qt;var nt=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 V,this.ensureGraphQLHandler=He(this.graphql);}listen(){let e=this.tapOptions?.bun,{fetch:t,websocket:r,...s}=e??{};this.runtimeServer=Bun.serve({port:this.port,hostname:this.hostname,fetch:async(o,n)=>{let a=new URL(o.url),c=C.find(o.method,a.pathname);if(K.enrichRequest(o),o.params=c?.params??{},o.query=Object.fromEntries(a.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&&a.pathname.startsWith(this.graphql.getYogaOptions().graphqlEndpoint??"/graphql")){let d=await this.ensureGraphQLHandler();if(d)return d.fetch(o,{server:n})}if(r&&o.headers.get("upgrade")==="websocket"&&n.upgrade(o,{data:{}}))return;let p=await ie(c?.middleware??[],c?.handler??((d,h)=>{h.notFound({...M(new D(d.url,d.method))});}),o);return p.headers["Content-Type"]==="application/json"?Response.json(p.getBody(),{status:p.responseStatus,headers:p.headers}):new Response(p.getBody(),{status:p.responseStatus,headers:p.headers})},...r?{websocket:r}:{},...s}),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 at=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 V,this.ensureGraphQLHandler=He(this.graphql);}listen(){let e=this.tapOptions?.deno,{handler:t,...r}=e??{};this.runtimeServer=Deno.serve({port:this.port,hostname:this.hostname,handler:async(s,o)=>{let n=new URL(s.url),a=C.find(s.method,n.pathname);if(K.enrichRequest(s),s.params=a?.params??{},s.query=Object.fromEntries(n.searchParams.entries()),s.ip=s.headers.get("x-forwarded-for")?.split(",")[0]??o.remoteAddr?.hostname,await t?.(s,o))return new Response(null,{status:426});if(this.graphql.isEnabled&&n.pathname.startsWith(this.graphql.getYogaOptions().graphqlEndpoint??"/graphql")){let d=await this.ensureGraphQLHandler();if(d)return d.fetch(s,{info:o})}if(s.headers.get("upgrade")==="websocket"&&this.tapOptions?.deno?.websocket){let{socket:d,response:h}=Deno.upgradeWebSocket(s);return this.tapOptions?.deno?.websocket?.open&&(d.onopen=()=>this.tapOptions?.deno?.websocket?.open?.(d)),this.tapOptions?.deno?.websocket?.message&&(d.onmessage=m=>{this.tapOptions?.deno?.websocket?.message?.(d,m.data);}),this.tapOptions?.deno?.websocket?.close&&(d.onclose=()=>this.tapOptions?.deno?.websocket?.close?.(d)),h}let p=await ie(a?.middleware??[],a?.handler??((d,h)=>{h.notFound({...M(new D(d.url,d.method))});}),s);return p.headers["Content-Type"]==="application/json"?Response.json(p.getBody(),{status:p.responseStatus,headers:p.headers}):new Response(p.getBody(),{status:p.responseStatus,headers:p.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 _s(i,e){let t=i.getReader();try{for(;;){let{done:r,value:s}=await t.read();if(r){e.end();break}e.write(s);}}catch(r){e.destroy(r);}}var ct=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 V,this.ensureGraphQLHandler=He(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,s)=>{if(this.tapOptions&&this.tapOptions.node){let f=this.tapOptions.node;await f?.(r);}if(this.graphql.isEnabled&&r.url?.startsWith(this.graphql.getYogaOptions().graphqlEndpoint??"/graphql")){let f=await this.ensureGraphQLHandler();if(f){f(r,s);return}}let o=C.find(r.method,r.url),n={};for(let f of Object.keys(r.headers)){if(f.startsWith(":"))continue;let b=r.headers[f];b!==void 0&&(n[f]=Array.isArray(b)?b.join(", "):b);}let a=new K(`${this.url}${r.url}`,{method:r.method,body:ne(r.method)?await this.readRequestBody(r):void 0,headers:n}),c=r.headers["x-forwarded-for"];Array.isArray(c)&&(c=c[0]),a.ip=c??r.socket.remoteAddress;let[p,l=""]=r.url?.split("?",2)??[];a.query=Object.fromEntries(new URLSearchParams(l)),a.params=o?.params??{};let d=new re;d.nodeResponse=s;let h=await ie(o?.middleware??[],o?.handler??((f,b)=>{b.notFound({...M(new D(f.url,f.method))});}),a,d);if(s.headersSent||s.writableEnded)return;let m=h.getBody();if(m instanceof ReadableStream){_s(m,s);return}m instanceof Buffer||m instanceof Uint8Array||typeof m=="string"?m=m:h.headers["Content-Type"]==="application/json"&&typeof m!="string"?m=JSON.stringify(m):m=String(m),s.writeHead(h.responseStatus,h.headers),s.end(m);});}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 s=[];e.on("data",o=>s.push(Buffer.from(o))),e.on("error",r),e.on("end",()=>t(Buffer.concat(s).toString()));})}createServer(e){if(this.nodeHttpClient==="http")return createServer(e);if(this.nodeHttpClient==="http2")return createServer$1(e);if(this.nodeHttpClient==="http2-secure"){if(!this.httpsOptions)throw new Error("httpsOptions (key, cert) are required when using http2-secure client");return createSecureServer(this.httpsOptions,e)}if(!this.httpsOptions)throw new Error("httpsOptions (key, cert) are required when using https client");return createServer$2(this.httpsOptions,e)}};var pt=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 nt(e);if(e?.runtime==="node")return new ct(e);if(e?.runtime==="deno")return new at(e);throw new Error("No server implementation found for runtime: "+e?.runtime)}};Q();var Rr=["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 Tr=class{_brand="BaldaServer";isListening;isProduction;graphql;serverOptions;router=C;wasInitialized;serverConnector;globalMiddlewares=[];controllerImportBlacklistedPaths=["node_modules"];notFoundHandler;nativeEnv=new Ae;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},e?.ajvInstance&&N.setGlobalInstance(e.ajvInstance),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 V(this.serverOptions.graphql),this.serverConnector=new pt({routes:[],port:this.serverOptions.port,host:this.serverOptions.host,tapOptions:this.serverOptions.tapOptions,runtime:R.type,nodeHttpClient:this.serverOptions.nodeHttpClient,httpsOptions:this.httpsOptions,graphql:this.graphql}),this.serverOptions.useBodyParser&&this.use(Kt());}get url(){return this.serverConnector.url}get port(){return this.serverConnector.port}get host(){return this.serverConnector.host}get routes(){return C.getRoutes()||[]}async hash(e){return Fe.hash(e)}async compareHash(e,t){return Fe.compare(e,t)}getEnvironment(){return this.nativeEnv.getEnvironment()}tmpDir(...e){return g.join("tmp",...e)}async mkdir(e,t){await u.mkdir(e,t);}get(e,t,r){let{middlewares:s,handler:o,swaggerOptions:n}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);C.addOrUpdate("GET",e,s,o,n);}post(e,t,r){let{middlewares:s,handler:o,swaggerOptions:n}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);C.addOrUpdate("POST",e,s,o,n);}patch(e,t,r){let{middlewares:s,handler:o,swaggerOptions:n}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);C.addOrUpdate("PATCH",e,s,o,n);}put(e,t,r){let{middlewares:s,handler:o,swaggerOptions:n}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);C.addOrUpdate("PUT",e,s,o,n);}delete(e,t,r){let{middlewares:s,handler:o,swaggerOptions:n}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);C.addOrUpdate("DELETE",e,s,o,n);}options(e,t,r){let{middlewares:s,handler:o,swaggerOptions:n}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);C.addOrUpdate("OPTIONS",e,s,o,n);}head(e,t,r){let{middlewares:s,handler:o,swaggerOptions:n}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);C.addOrUpdate("HEAD",e,s,o,n);}group(e,t,r){this.router.group(e,t,r);}getNodeServer(){if(R.type!=="node")throw new Error("Server is not using node runtime, you can't call `.getNodeServer()`");return this.serverConnector.getServer("node")}getBunServer(){if(R.type!=="bun")throw new Error("Server is not using bun runtime, you can't call `.getBunServer()`");return this.serverConnector.getServer("bun")}getDenoServer(){if(R.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(Rr.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(R.type){case "bun":case "node":process.exit(e);case "deno":Deno.exit(e);default:throw new Error(`Unsupported runtime: ${R.type}`)}}on(e,t){switch(R.type){case "bun":case "node":process.on(e,t);break;case "deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${R.type}, only node, bun and deno are supported`)}}once(e,t){switch(R.type){case "bun":case "node":process.once(e,t);break;case "deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${R.type}, only node, bun and deno are supported`)}}use(...e){this.globalMiddlewares.push(...e);}useExpress(e,t){ir(this).use(e,t);}expressMiddleware(e){return Ne(e)}mountExpressRouter(e,t){rt(e,t);}setErrorHandler(e){this.globalMiddlewares.unshift(async(t,r,s)=>{try{await s();}catch(o){await e?.(t,r,s,o);}});}setNotFoundHandler(e){this.notFoundHandler=e?.bind(this);}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&&wr(this.serverOptions.swagger),e?.({port:this.port,host:this.host,url:this.url});});}async waitUntilListening(){return new Promise((e,t)=>{try{this.listen(()=>{e();});}catch(r){t(r);}})}async close(){await this.disconnect();}async disconnect(){await this.serverConnector.close(),this.isListening=false;}configureHash(e){Fe.configure(e);}async getMockServer(e){return await this.bootstrap(e),new tt(this)}async importControllers(e){let t=e??this.serverOptions.controllerPatterns,r=await Promise.all(t.map(async s=>glob(s,{absolute:true,cwd:$.getCwd()}))).then(s=>s.flat());r=r.flat(),r=r.filter(s=>!this.controllerImportBlacklistedPaths.some(o=>s.includes(o))),v.debug(`Found ${r.length} controllers to import`),await Promise.all(r.map(async s=>{v.debug(`Importing controller ${s}`),await import(s).catch(o=>{v.error(`Error importing controller ${s}: ${o}`);});}));}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(Xt(r));break;case "json":this.use(ur(r));break;case "static":this.use(Wt(r));break;case "fileParser":this.use(pr(r));break;case "helmet":this.use(lr(r));break;case "cookie":this.use(Jt(r));break;case "methodOverride":this.use(gr(r));break;case "compression":this.use(Vt(r));break;case "log":this.use(hr(r));break;case "rateLimiter":let{keyOptions:s,storageOptions:o}=r;this.use(fr(s,o));break;case "urlencoded":this.use(Pr(r));break;case "trustProxy":this.use(Sr(r));break;case "timeout":this.use(br(r));break;case "session":this.use(yr(r));break;case "asyncLocalStorage":this.use(Ot(r));break;default:v.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&&C.applyGlobalMiddlewaresToAllRoutes(this.globalMiddlewares),this.wasInitialized=true);}handleNotFound=(e,t)=>{if(this.notFoundHandler){this.notFoundHandler(e,t);return}let r=new URL(e.url).pathname,s=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"],o=[];for(let a of s){if(a===e.method.toUpperCase())continue;let c=C.find(a,r);c&&c.handler!==this.handleNotFound&&o.push(a);}if(o.length){t.setHeader("Allow",o.join(", "));let a=new ke(r,e.method);t.methodNotAllowed({...M(a)});return}let n=new D(r,e.method);t.notFound({...M(n)});};registerNotFoundRoutes(){let e=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];for(let t of e)C.addOrUpdate(t,"*",[],this.handleNotFound,{excludeFromSwagger:true});}};var Z=class extends T{constructor(e){super(`File not found: ${e}`);}};var Cr=class{constructor(e){this.options=e;}async getDownloadUrl(e,t=3600){await this.ensureClient();let r=this.containerClient.getBlockBlobClient(e),s=new Date(Date.now()-300*1e3),o=new Date(Date.now()+t*1e3),n=this.azureBlobLib.BlobSASPermissions.parse("r"),a=this.azureBlobLib.generateBlobSASQueryParameters({containerName:this.options.containerName,blobName:e,permissions:n,startsOn:s,expiresOn:o},this.sharedKeyCredential).toString();return `${r.url}?${a}`}async getUploadUrl(e,t=3600){await this.ensureClient();let r=this.containerClient.getBlockBlobClient(e),s=new Date(Date.now()-300*1e3),o=new Date(Date.now()+t*1e3),n=this.azureBlobLib.BlobSASPermissions.parse("w"),a=this.azureBlobLib.generateBlobSASQueryParameters({containerName:this.options.containerName,blobName:e,permissions:n,startsOn:s,expiresOn:o},this.sharedKeyCredential).toString();return `${r.url}?${a}`}async getPublicUrl(e){return await this.ensureClient(),this.containerClient.getBlockBlobClient(e).url}async listObjects(e){await this.ensureClient();let t=[],r=e?e.endsWith("/")?e:`${e}/`:void 0;for await(let s of this.containerClient.listBlobsFlat({prefix:r}))t.push(s.name);return t}async getObject(e,t="raw"){await this.ensureClient();try{let s=await this.containerClient.getBlockBlobClient(e).download();if(!s.readableStreamBody)throw new Z(e);let o=t;if(o==="stream")return Readable.toWeb(s.readableStreamBody);let n=[];for await(let c of s.readableStreamBody)n.push(Buffer.isBuffer(c)?c:Buffer.from(c));let a=Buffer.concat(n);switch(o){case "raw":return new Uint8Array(a);case "text":return a.toString();default:throw new T("Invalid return type")}}catch(r){throw r.statusCode===404?new Z(e):r}}async putObject(e,t,r){await this.ensureClient();let s=this.containerClient.getBlockBlobClient(e),o=t;await s.upload(o,o.length,{blobHTTPHeaders:{blobContentType:r||"application/octet-stream"}});}async deleteObject(e){await this.ensureClient();let t=this.containerClient.getBlockBlobClient(e);try{await t.delete();}catch(r){if(r&&typeof r=="object"&&"statusCode"in r&&r.statusCode===404)return;throw r}}async ensureClient(){if(this.azureBlobLib)return;this.azureBlobLib=await import('@azure/storage-blob').catch(()=>{throw new T("Library not installed: @azure/storage-blob, try run npm install @azure/storage-blob")}),this.blobServiceClient=this.azureBlobLib.BlobServiceClient.fromConnectionString(this.options.connectionString),this.containerClient=this.blobServiceClient.getContainerClient(this.options.containerName);let e=this.blobServiceClient.credential;if(!(e instanceof this.azureBlobLib.StorageSharedKeyCredential))throw new T("BlobStorage requires a shared key credential to generate SAS URLs");this.sharedKeyCredential=e;}};var Or=class{constructor(e){this.options=e;}wasDirectoryEnsured=false;async getDownloadUrl(e,t=3600){throw new T("LocalStorageProvider does not support getDownloadUrl. Use S3 or Azure Blob storage for signed URLs.")}async getUploadUrl(e,t=3600){throw new T("LocalStorageProvider does not support getUploadUrl. Use S3 or Azure Blob storage for signed URLs.")}async getPublicUrl(e){throw new T("`getPublicUrl` is not available in local storage provider")}async listObjects(e){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let t=g.resolve(this.options.directory),r=e?g.join(t,e):t;if(!await u.exists(r))return [];let o=[];return await this.listFilesRecursively(r,t,o),o}async getObject(e,t="raw"){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let r=g.join(this.options.directory,e);if(!await u.exists(r))throw new Z(e);switch(t){case "raw":return await u.readFile(r);case "text":return await u.readFile(r,{encoding:"utf8"});case "stream":return await u.streamFile(r);default:throw new T("Invalid return type")}}async putObject(e,t,r){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let s=g.join(this.options.directory,e),o=g.join(s,"..");await u.mkdir(o,{recursive:true}),await u.writeFile(s,t);}async deleteObject(e){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let t=g.join(this.options.directory,e);await u.exists(t)&&await u.unlink(t);}async listFilesRecursively(e,t,r){let s=await u.stat(e);if(s.isFile){let n=e.replace(t,"").replace(/^\//,"");r.push(n);return}if(!s.isDirectory)return;let o=await this.readDirectory(e);for(let n of o){let a=g.join(e,n);await this.listFilesRecursively(a,t,r);}}async readDirectory(e){let{runtime:t}=await Promise.resolve().then(()=>(Q(),kt));switch(t.type){case "node":return await(await import('fs/promises')).readdir(e);case "bun":return await(await import('fs/promises')).readdir(e);case "deno":{let r=[];for await(let s of Deno.readDir(e))r.push(s.name);return r}default:throw new T("Unsupported runtime")}}async ensureDirectoryExists(){if(await u.exists(this.options.directory)){this.wasDirectoryEnsured=true;return}await u.mkdir(this.options.directory,{recursive:true}),this.wasDirectoryEnsured=true;}};var jr=class{options;constructor(e){this.options=e;}async getDownloadUrl(e,t=3600){if(await this.ensureClient(),!this.options.cloudfrontOptions)throw new T("getDownloadUrl requires CloudFront configuration");let{domainName:r,keyPairId:s,privateKey:o}=this.options.cloudfrontOptions,n=`https://${r}/${e}`,a=new Date(Date.now()+t*1e3).toISOString();return this.cloudfrontSignerLib.getSignedUrl({url:n,keyPairId:s,privateKey:o,dateLessThan:a})}async getUploadUrl(e,t=3600){await this.ensureClient();let r=new this.s3Lib.PutObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});return this.s3PresignerLib.getSignedUrl(this.s3Client,r,{expiresIn:t})}async getPublicUrl(e){await this.ensureClient();let{region:t,endpoint:r}=this.options.s3ClientConfig,s=this.options.s3ClientConfig.bucketName;return r?`${typeof r=="string"?r:r.toString()}/${s}/${e}`:`https://${s}.s3.${t}.amazonaws.com/${e}`}async listObjects(e){await this.ensureClient();let t=new this.s3Lib.ListObjectsV2Command({Bucket:this.options.s3ClientConfig.bucketName,Prefix:e});return (await this.s3Client.send(t)).Contents?.map(s=>s.Key).filter(Boolean)??[]}async getObject(e,t="raw"){await this.ensureClient();let r=new this.s3Lib.GetObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});try{let s=await this.s3Client.send(r);if(!s.Body)throw new Z(e);switch(t){case "raw":return await s.Body.transformToByteArray();case "text":return await s.Body.transformToString();case "stream":return s.Body.transformToWebStream();default:throw new T("Invalid return type")}}catch(s){throw s.name==="NoSuchKey"?new Z(e):s}}async putObject(e,t,r){await this.ensureClient();let s=new this.s3Lib.PutObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e,Body:t,ContentType:r});await this.s3Client.send(s);}async deleteObject(e){await this.ensureClient();let t=new this.s3Lib.DeleteObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});await this.s3Client.send(t);}async ensureClient(){this.s3Lib||(this.s3Lib=await import('@aws-sdk/client-s3').then(e=>e.default).catch(()=>{throw new T("Library not installed: @aws-sdk/client-s3, try run npm install @aws-sdk/client-s3")}),this.s3PresignerLib=await import('@aws-sdk/s3-request-presigner').then(e=>e.default).catch(()=>{throw new T("Library not installed: @aws-sdk/s3-request-presigner, try run npm install @aws-sdk/s3-request-presigner")}),this.options.cloudfrontOptions&&(this.cloudfrontSignerLib=await import('@aws-sdk/cloudfront-signer').then(e=>e.default).catch(()=>{throw new T("Library not installed: @aws-sdk/cloudfront-signer, try run npm install @aws-sdk/cloudfront-signer")})),this.s3Client=new this.s3Lib.S3Client(this.options.s3ClientConfig??{}));}};var Er=class{providerOptions;defaultProvider;providerMap;constructor(e,t){this.providerOptions=e,this.defaultProvider=t.defaultProvider,this.providerMap=new Map(Object.entries(e).map(([r,s])=>[r,s]));}use(e){let t=this.providerMap.get(e);if(!t)throw new Error(`[Storage] Provider ${String(e)} not found`);return t}async getDownloadUrl(e,t){return this.providerOptions[this.defaultProvider].getDownloadUrl(e,t)}async getUploadUrl(e,t){return this.providerOptions[this.defaultProvider].getUploadUrl(e,t)}async getPublicUrl(e){return this.providerOptions[this.defaultProvider].getPublicUrl(e)}async listObjects(e){return this.providerOptions[this.defaultProvider].listObjects(e)}async getObject(e,t="raw"){return this.providerOptions[this.defaultProvider].getObject(e,t)}async putObject(e,t,r){return this.providerOptions[this.defaultProvider].putObject(e,t,r)}async deleteObject(e){return this.providerOptions[this.defaultProvider].deleteObject(e)}};var qr=class{};var Mr=i=>(e,t)=>(r,s,o)=>{let n={scope:e,handler:t,manager:i};if(typeof s>"u"){let c=w.get(r.prototype,"__class__");return c||(c={policies:[]}),c.policies||(c.policies=[]),c.policies.push(n),w.set(r.prototype,"__class__",c),r}let a=w.get(r,s);return a||(a={policies:[]}),a.policies||(a.policies=[]),a.policies.push(n),w.set(r,s,a),o};var Ar=class{providers;constructor(e){this.providers=e;}createDecorator(){return Mr(this)}canAccess(e,t,...r){let s=this.providers[e];if(!s)throw new T(`Policy provider for ${String(e)} not found`);return s[t](...r)}};var ou=C;
573
- export{go as ARG_SYMBOL,Cr as AzureBlobStorageProvider,Lt as BaseCron,_t as BaseMqtt,qr as BasePlugin,Dt as BaseQueue,Ke as BullMQPubSub,j as Command,Rt as CommandRegistry,xe as CronService,_e as CustomTypedQueue,V as GraphQL,Or as LocalStorageProvider,Le as MqttService,Ve as PGBossPubSub,Ar as PolicyManager,ee as QueueManager,de as QueueService,K as Request,re as Response,jr as S3StorageProvider,Ze as SQSPubSub,Tr as Server,Er as Storage,ue as TypedQueue,pe as VALIDATION_ERROR_SYMBOL,A as arg,Ot as asyncLocalStorage,Be as asyncStorage,rs as baseCommands,Vr as bullmqQueue,qe as commandRegistry,Vt as compression,jo as controller,Jt as cookie,Xt as cors,ir as createExpressAdapter,Mr as createPolicyDecorator,Jr as createQueue,ro as cron,zs as defineLoggerConfig,Zi as defineQueueConfiguration,Mo as del,vs as expressHandler,Ne as expressMiddleware,pr as fileParser,x as flag,$o as get,Ct as getContentType,Fe as hash,lr as helmet,ur as json,hr as log,v as logger,gr as methodOverride,Go as middleware,rt as mountExpressRouter,xi as mqtt,No as patch,Zr as pgbossQueue,Do as post,Qo as put,fr as rateLimiter,ou as router,ai as serialize,Wt as serveStatic,yr as session,Xs as setCronGlobalErrorHandler,Si as setMqttGlobalErrorHandler,Kr as sqsQueue,br as timeout,Sr as trustProxy,Pr as urlencoded,di as validate};//# sourceMappingURL=index.js.map
572
+ `}function ur(n,e){let t=[],r=/:([a-zA-Z0-9_]+)/g,s;for(;(s=r.exec(n))!==null;){let o=s[1],i={type:"string"};e&&e.shape&&e.shape[o]&&(i=Pe(e.shape[o])||{type:"string"}),t.push({name:o,in:"path",required:true,schema:i});}return t}var hr=n=>async(e,t,r)=>{e.timeout=false;let s=setTimeout(()=>{e.timeout=true;},n.ms);try{await r();}finally{clearTimeout(s);}};var gr=n=>{let e=n?.header??"x-forwarded-for",t=n?.trust??true,r=n?.hop??"first";return async(s,o,i)=>{if(!t)return i();let a=s.headers.get(e);if(a&&typeof a=="string"){let c=a.split(",").map(p=>p.trim()).filter(Boolean);c.length&&(s.ip=r==="first"?c[0]:c[c.length-1]);}return i()}};var qt=class{ITERATIONS=6e5;SALT_LENGTH=16;KEY_LENGTH=256;configure(e){if(e.iterations!==void 0){if(e.iterations<1)throw new Error("Iterations must be at least 1");this.ITERATIONS=e.iterations;}if(e.saltLength!==void 0){if(e.saltLength<8)throw new Error("Salt length must be at least 8 bytes");this.SALT_LENGTH=e.saltLength;}if(e.keyLength!==void 0){if(e.keyLength<128)throw new Error("Key length must be at least 128 bits");this.KEY_LENGTH=e.keyLength;}}async hash(e){if(!e)throw new Error("Data to hash cannot be empty");let r=new TextEncoder().encode(e),s=crypto.getRandomValues(new Uint8Array(this.SALT_LENGTH)),o=await crypto.subtle.importKey("raw",r,{name:"PBKDF2"},false,["deriveBits"]),i=await crypto.subtle.deriveBits({name:"PBKDF2",salt:s,iterations:this.ITERATIONS,hash:"SHA-256"},o,this.KEY_LENGTH),a=this.encodeBase64(s),c=this.encodeBase64(new Uint8Array(i));return `${a}:${c}`}async compare(e,t){if(!e||!t)return false;try{let s=new TextEncoder().encode(t),o=e.split(":");if(o.length!==2)throw new Error("Invalid hash format");let[i,a]=o,c=this.decodeBase64(i),p=this.decodeBase64(a),l=await crypto.subtle.importKey("raw",s,{name:"PBKDF2"},!1,["deriveBits"]),d=await crypto.subtle.deriveBits({name:"PBKDF2",salt:c,iterations:this.ITERATIONS,hash:"SHA-256"},l,this.KEY_LENGTH),g=new Uint8Array(d);if(g.length!==p.length)return !1;let f=0;for(let m=0;m<g.length;m++)f|=g[m]^p[m];return f===0}catch{return false}}encodeBase64(e){let t="",r=e.byteLength;for(let s=0;s<r;s++)t+=String.fromCharCode(e[s]);return btoa(t)}decodeBase64(e){let t=atob(e),r=t.length,s=new Uint8Array(r);for(let o=0;o<r;o++)s[o]=t.charCodeAt(o);return s}},Qe=new qt;var at=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 Z,this.ensureGraphQLHandler=Le(this.graphql);}listen(){let e=this.tapOptions?.bun,{fetch:t,websocket:r,...s}=e??{};this.runtimeServer=Bun.serve({port:this.port,hostname:this.hostname,fetch:async(o,i)=>{let a=o.url,c=a.indexOf("://")+3,p=a.indexOf("/",c),l=p===-1?"/":a.slice(p),d=l.indexOf("?"),g=d===-1?l:l.slice(0,d),f=d===-1?"":l.slice(d+1);if(this.graphql.isEnabled&&g.startsWith(this.graphql.getYogaOptions().graphqlEndpoint??"/graphql")){let v=W.fromRequest(o),C=await this.ensureGraphQLHandler();if(C)return C.fetch(v,{server:i})}let m=j.find(o.method,g),y=W.fromRequest(o);if(y.params=m?.params??{},y.query=f?Object.fromEntries(new URLSearchParams(f)):{},y.ip=o.headers.get("x-forwarded-for")?.split(",")[0]??i.requestIP(o)?.address,await t?.call(this,y,i),r&&y.headers.get("upgrade")==="websocket"&&i.upgrade(y,{data:{}}))return;let S=await ae(m?.middleware??[],m?.handler??((v,C)=>{C.notFound({...A(new I(v.url,v.method))});}),y);return S.headers["Content-Type"]==="application/json"?Response.json(S.getBody(),{status:S.responseStatus,headers:S.headers}):new Response(S.getBody(),{status:S.responseStatus,headers:S.headers})},...r?{websocket:r}:{},...s}),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 ct=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 Z,this.ensureGraphQLHandler=Le(this.graphql);}listen(){let e=this.tapOptions?.deno,{handler:t,...r}=e??{};this.runtimeServer=Deno.serve({port:this.port,hostname:this.hostname,handler:async(s,o)=>{let i=s.url,a=i.indexOf("://")+3,c=i.indexOf("/",a),p=c===-1?"/":i.slice(c),l=p.indexOf("?"),d=l===-1?p:p.slice(0,l),g=l===-1?"":p.slice(l+1);if(this.graphql.isEnabled&&d.startsWith(this.graphql.getYogaOptions().graphqlEndpoint??"/graphql")){let v=W.fromRequest(s),C=await this.ensureGraphQLHandler();if(C)return C.fetch(v,{info:o})}let f=j.find(s.method,d),m=W.fromRequest(s);if(m.params=f?.params??{},m.query=g?Object.fromEntries(new URLSearchParams(g)):{},m.ip=s.headers.get("x-forwarded-for")?.split(",")[0]??o.remoteAddr?.hostname,await t?.(m,o))return new Response(null,{status:426});if(m.headers.get("upgrade")==="websocket"&&this.tapOptions?.deno?.websocket){let{socket:v,response:C}=Deno.upgradeWebSocket(m);return this.tapOptions?.deno?.websocket?.open&&(v.onopen=()=>this.tapOptions?.deno?.websocket?.open?.(v)),this.tapOptions?.deno?.websocket?.message&&(v.onmessage=M=>{this.tapOptions?.deno?.websocket?.message?.(v,M.data);}),this.tapOptions?.deno?.websocket?.close&&(v.onclose=()=>this.tapOptions?.deno?.websocket?.close?.(v)),C}let S=await ae(f?.middleware??[],f?.handler??((v,C)=>{C.notFound({...A(new I(v.url,v.method))});}),m);return S.headers["Content-Type"]==="application/json"?Response.json(S.getBody(),{status:S.responseStatus,headers:S.headers}):new Response(S.getBody(),{status:S.responseStatus,headers:S.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();}};var Bs=async(n,e)=>{let t=Readable.fromWeb(n);return pipeline(t,e)},pt=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 Z,this.ensureGraphQLHandler=Le(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,s)=>{if(this.tapOptions&&this.tapOptions.node){let S=this.tapOptions.node;await S?.(r);}let o=r.url,i=o.indexOf("?"),a=i===-1?o:o.slice(0,i),c=i===-1?"":o.slice(i+1);if(this.graphql.isEnabled&&a.startsWith(this.graphql.getYogaOptions().graphqlEndpoint??"/graphql")){let S=await this.ensureGraphQLHandler();if(S){S(r,s);return}}let p=j.find(r.method,a),l={};for(let S in r.headers){if(S.charCodeAt(0)===58)continue;let v=r.headers[S];v!==void 0&&(l[S]=Array.isArray(v)?v.join(", "):v);}let d=new W(`${this.url}${o}`,{method:r.method,body:ce(r.method)?await this.readRequestBody(r):void 0,headers:l}),g=r.headers["x-forwarded-for"];d.ip=(Array.isArray(g)?g[0]:g)??r.socket.remoteAddress,d.query=c?Object.fromEntries(new URLSearchParams(c)):{},d.params=p?.params??{};let f=new oe;f.nodeResponse=s;let m=await ae(p?.middleware??[],p?.handler??((S,v)=>{v.notFound({...A(new I(S.url,S.method))});}),d,f);if(s.headersSent||s.writableEnded)return;let y=m.getBody();if(y instanceof ReadableStream){s.writeHead(m.responseStatus,m.headers),Bs(y,s);return}s.writeHead(m.responseStatus,m.headers),y instanceof Buffer||y instanceof Uint8Array||typeof y=="string"?s.end(y):m.headers["Content-Type"]==="application/json"?s.end(JSON.stringify(y)):s.end(y!=null?String(y):void 0);});}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 s=[];e.on("data",o=>s.push(Buffer.from(o))),e.on("error",r),e.on("end",()=>t(Buffer.concat(s).toString()));})}createServer(e){if(this.nodeHttpClient==="http")return createServer(e);if(this.nodeHttpClient==="http2")return createServer$1(e);if(this.nodeHttpClient==="http2-secure"){if(!this.httpsOptions)throw new Error("httpsOptions (key, cert) are required when using http2-secure client");return createSecureServer(this.httpsOptions,e)}if(!this.httpsOptions)throw new Error("httpsOptions (key, cert) are required when using https client");return createServer$2(this.httpsOptions,e)}};var lt=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 at(e);if(e?.runtime==="node")return new pt(e);if(e?.runtime==="deno")return new ct(e);throw new Error("No server implementation found for runtime: "+e?.runtime)}};U();var fr=["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 dt=class extends O{constructor(e,t,r){super(`FILE_TOO_LARGE: "${e}" is too large. Max size is ${r} bytes, but got ${t} bytes`);}};U();var Et=class{async tmpdir(){switch(T.type){case "node":case "bun":return (await import('os')).tmpdir();case "deno":return Deno.makeTempDir();default:throw new Error("Unsupported runtime")}}},yr=new Et;var vr=1024*1024,wr=10*1024*1024,Sr=n=>async(e,t,r)=>{let s=[];try{let o=e.headers.get("content-type")??e.headers.get("Content-Type");if(!o||!o.startsWith("multipart/form-data")||e.parsedBody||e.bodyUsed)return r();let i=e.headers.get("content-length"),a=le(n?.maxFileSize,wr)??wr;if(i&&parseInt(i)>a)return t.status(413).json({error:"Payload too large",message:`Total request size exceeds ${a} bytes`});let c=o.match(/boundary=(.*)(;|$)/i);if(!c)return r();let p=c[1].replace(/(^\s*"?|"?\s*$)/g,""),l=new Uint8Array(await e.arrayBuffer());if(l.length>a)return t.status(413).json({error:"Payload too large",message:`Total request size exceeds ${a} bytes`});let d=new TextEncoder().encode(`--${p}`),g=new Uint8Array([13,10,13,10]),f=[],m=(M,P,E=0)=>{e:for(let L=E;L<=M.length-P.length;L++){for(let Q=0;Q<P.length;Q++)if(M[L+Q]!==P[Q])continue e;return L}return -1},y=m(l,d);for(;y!==-1&&(y+=d.length,!(l[y]===45&&l[y+1]===45));){l[y]===13&&l[y+1]===10&&(y+=2);let M=m(l,g,y);if(M===-1)break;let P=l.subarray(y,M),E=new TextDecoder().decode(P),L=M+g.length,Q=m(l,d,L);if(Q===-1)break;let Y=Q-1;l[Y]===10&&Y--,l[Y]===13&&Y--;let Mt=l.subarray(L,Y+1);f.push({headers:E,data:Mt}),y=Q;}let S=[],v={},C=le(n?.maxFileSize,vr)??vr;for(let M of f){let P=M.headers.split(`\r
573
+ `).find(ze=>ze.toLowerCase().startsWith("content-disposition:"));if(!P)continue;let E=P.match(/name="([^"]+)"/);if(!E)continue;let L=E[1],Q=P.match(/filename="([^"]*)"/),Y=Q?Q[1]:"";if(!!Y){if(n?.maxFiles&&S.length>=n.maxFiles)return t.badRequest({...A(new O(`Too many files: Maximum ${n.maxFiles} files allowed`))});if(C&&M.data.length>C)return t.badRequest({...A(new dt(Y,M.data.length,C))});let ze=M.headers.split(`\r
574
+ `).find(Hr=>Hr.toLowerCase().startsWith("content-type:")),Ge=ze?ze.split(":")[1].trim():"application/octet-stream";if(n?.allowedMimeTypes&&!n.allowedMimeTypes.includes(Ge))return t.badRequest({...A(new O(`Invalid file type: "${Ge}" is not allowed. Allowed types: ${n.allowedMimeTypes.join(", ")}`))});let Br=Hs(Ge),ut=h.join(await yr.tmpdir(),`${te.randomUUID()}${Br}`);await u.writeFile(ut,M.data),s.push(ut),S.push({formName:L,mimeType:Ge,size:M.data.length,tmpPath:ut,originalName:Y});}else v[L]=new TextDecoder().decode(M.data);}e.files=S,e.parsedBody=v,await r(),await br(s);}catch(o){throw await br(s),o}},br=async n=>{await Promise.allSettled(n.map(e=>u.unlink(e)));};var Hs=n=>({"image/jpeg":".jpg","image/png":".png","image/gif":".gif","image/webp":".webp","application/pdf":".pdf","text/plain":".txt","application/json":".json","text/csv":".csv","application/octet-stream":".bin","application/x-www-form-urlencoded":".urlencoded","application/xml":".xml","application/yaml":".yaml","application/yml":".yml","application/csv":".csv","application/txt":".txt","application/markdown":".markdown"})[n.toLowerCase()]||".bin";var Ue=class extends O{constructor(e){super(`JSON_NOT_VALID: "${JSON.stringify(e)}" is not a valid JSON`);}};var xr=100*1024,Rr=n=>async(e,t,r)=>{if(!Ls(e)||!ce(e.method)||e.bodyUsed)return r();let s=le(n?.sizeLimit,xr)??xr,o=e.headers.get("content-length");if(o&&Number.parseInt(o)>s){let i={status:413,message:"ERR_REQUEST_BODY_TOO_LARGE",...n?.customErrorMessage};return t.status(i.status).json({error:i.message})}if(e.parsedBody)return r();try{e.parsedBody=await e.json();}catch(i){return i instanceof SyntaxError?t.badRequest({...A(new Ue("Invalid JSON syntax"))}):t.badRequest({...A(new Ue("Invalid request body encoding"))})}await r();};function Ls(n){let e=Ns(n);return e?_s(e)==="application/json":false}function Ns(n){let e=n.headers.get("content-type")??n.headers.get("Content-Type");return e?Array.isArray(e)?e[0]||null:e:null}function _s(n){let e=n.trim(),t=e.indexOf(";");return t===-1?e.toLowerCase():e.substring(0,t).trim().toLowerCase()}var Pr=1024*1024,Tr=n=>{let t={limit:le(n?.limit,Pr)??Pr,extended:n?.extended??false,charset:n?.charset??"utf8",allowEmpty:n?.allowEmpty??true,parameterLimit:n?.parameterLimit??1e3};return async(r,s,o)=>{if(!(r.headers.get("content-type")||"").includes("application/x-www-form-urlencoded"))return o();let a=r.headers.get("content-length");if(a&&parseInt(a)>t.limit){s.status(413).json({error:"Payload too large",message:"Request body exceeds the size limit"});return}try{await Ds(r,t),await o();}catch(c){if(c instanceof Error&&c.message.includes("limit")){s.status(413).json({error:"Payload too large",message:"Request body exceeds the size limit"});return}throw c}}};async function Ds(n,e){if(n.parsedBody||n.bodyUsed)return;let t=await n.arrayBuffer();if(t.byteLength>e.limit)throw new Error(`Body size ${t.byteLength} exceeds limit ${e.limit}`);let s=new TextDecoder(e.charset).decode(t),o=Is(s,e);n.parsedBody=o;}function Is(n,e){let t={},r=new URLSearchParams(n);if(r.size>e.parameterLimit)throw new Error(`Too many parameters: ${r.size} exceeds limit ${e.parameterLimit}`);for(let[s,o]of r.entries())!e.allowEmpty&&o===""||(e.extended?Fs(t,s,o):t[s]=o);return t}function Fs(n,e,t){let r=["__proto__","constructor","prototype"];if(r.includes(e))return;let s=e.match(/\[([^\]]*)\]/g);if(!s){r.includes(e)||(n[e]=t);return}let o=n,i=e.split("[")[0];if(r.includes(i))return;for(let c=0;c<s.length-1;c++){let p=s[c].slice(1,-1);if(r.includes(p))return;if(o[i]||(o[i]={}),p===""){Array.isArray(o[i])||(o[i]=[]),o=o[i];continue}o[i][p]||(o[i][p]={}),o=o[i][p];}let a=s[s.length-1].slice(1,-1);if(!r.includes(a)){if(a===""){Array.isArray(o)||(o=[]),o.push(t);return}o[a]=t;}}var Qs=n=>(n.headers.get("content-type")??n.headers.get("Content-Type"))?.split(";")[0]??null,Or=n=>{let e=n.json,t=n.urlencoded,r=n.fileParser;return async(s,o,i)=>{if(!ce(s.method)||s.bodyUsed)return i();let a=Qs(s);if(a==="application/json")return Rr(e)(s,o,i);if(a==="multipart/form-data")return Sr(r)(s,o,i);if(a==="application/x-www-form-urlencoded")return Tr(t)(s,o,i);if(a?.includes("text/")){let c=new TextDecoder;s.parsedBody=c.decode(await s.arrayBuffer());}return i()}};var Cr=class{_brand="BaldaServer";isListening;isProduction;graphql;serverOptions;router=j;wasInitialized;serverConnector;globalMiddlewares=[];controllerImportBlacklistedPaths=["node_modules"];notFoundHandler;nativeEnv=new $e;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,graphql:e?.graphql??void 0},e?.ajvInstance&&N.setGlobalInstance(e.ajvInstance),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 Z(this.serverOptions.graphql),this.serverConnector=new lt({routes:[],port:this.serverOptions.port,host:this.serverOptions.host,tapOptions:this.serverOptions.tapOptions,runtime:T.type,nodeHttpClient:this.serverOptions.nodeHttpClient,httpsOptions:this.httpsOptions,graphql:this.graphql});}get url(){return this.serverConnector.url}get port(){return this.serverConnector.port}get host(){return this.serverConnector.host}get routes(){return j.getRoutes()||[]}async hash(e){return Qe.hash(e)}async compareHash(e,t){return Qe.compare(e,t)}getEnvironment(){return this.nativeEnv.getEnvironment()}tmpDir(...e){return h.join("tmp",...e)}async mkdir(e,t){await u.mkdir(e,t);}get(e,t,r){let{middlewares:s,handler:o,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);j.addOrUpdate("GET",e,s,o,i);}post(e,t,r){let{middlewares:s,handler:o,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);j.addOrUpdate("POST",e,s,o,i);}patch(e,t,r){let{middlewares:s,handler:o,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);j.addOrUpdate("PATCH",e,s,o,i);}put(e,t,r){let{middlewares:s,handler:o,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);j.addOrUpdate("PUT",e,s,o,i);}delete(e,t,r){let{middlewares:s,handler:o,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);j.addOrUpdate("DELETE",e,s,o,i);}options(e,t,r){let{middlewares:s,handler:o,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);j.addOrUpdate("OPTIONS",e,s,o,i);}head(e,t,r){let{middlewares:s,handler:o,swaggerOptions:i}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);j.addOrUpdate("HEAD",e,s,o,i);}group(e,t,r){this.router.group(e,t,r);}getNodeServer(){if(T.type!=="node")throw new Error("Server is not using node runtime, you can't call `.getNodeServer()`");return this.serverConnector.getServer("node")}getBunServer(){if(T.type!=="bun")throw new Error("Server is not using bun runtime, you can't call `.getBunServer()`");return this.serverConnector.getServer("bun")}getDenoServer(){if(T.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(fr.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(T.type){case "bun":case "node":process.exit(e);case "deno":Deno.exit(e);default:throw new Error(`Unsupported runtime: ${T.type}`)}}on(e,t){switch(T.type){case "bun":case "node":process.on(e,t);break;case "deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${T.type}, only node, bun and deno are supported`)}}once(e,t){switch(T.type){case "bun":case "node":process.once(e,t);break;case "deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${T.type}, only node, bun and deno are supported`)}}use(...e){this.globalMiddlewares.push(...e);}useExpress(e,t){nr(this).use(e,t);}expressMiddleware(e){return _e(e)}mountExpressRouter(e,t){ot(e,t);}setErrorHandler(e){this.globalMiddlewares.unshift(async(t,r,s)=>{try{await s();}catch(o){await e?.(t,r,s,o);}});}setNotFoundHandler(e){this.notFoundHandler=e?.bind(this);}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&&mr(this.serverOptions.swagger),e?.({port:this.port,host:this.host,url:this.url});});}async waitUntilListening(){return new Promise((e,t)=>{try{this.listen(()=>{e();});}catch(r){t(r);}})}async close(){await this.disconnect();}async disconnect(){await this.serverConnector.close(),this.isListening=false;}configureHash(e){Qe.configure(e);}async getMockServer(e){return await this.bootstrap(e),new st(this)}async importControllers(e){let t=e??this.serverOptions.controllerPatterns,r=await Promise.all(t.map(async s=>glob(s,{absolute:true,cwd:B.getCwd()}))).then(s=>s.flat());r=r.flat(),r=r.filter(s=>!this.controllerImportBlacklistedPaths.some(o=>s.includes(o))),b.debug(`Found ${r.length} controllers to import`),await Promise.all(r.map(async s=>{b.debug(`Importing controller ${s}`),await import(s).catch(o=>{b.error(`Error importing controller ${s}: ${o}`);});}));}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 "bodyParser":this.use(Or(r));break;case "cors":this.use(Xt(r));break;case "static":this.use(Kt(r));break;case "helmet":this.use(ir(r));break;case "cookie":this.use(Jt(r));break;case "methodOverride":this.use(pr(r));break;case "compression":this.use(Vt(r));break;case "log":this.use(cr(r));break;case "rateLimiter":let{keyOptions:s,storageOptions:o}=r;this.use(lr(s,o));break;case "trustProxy":this.use(gr(r));break;case "timeout":this.use(hr(r));break;case "session":this.use(dr(r));break;case "asyncLocalStorage":this.use(Ct(r));break;default:b.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&&j.applyGlobalMiddlewaresToAllRoutes(this.globalMiddlewares),this.wasInitialized=true);}handleNotFound=(e,t)=>{if(this.notFoundHandler){this.notFoundHandler(e,t);return}let r=new URL(e.url).pathname,s=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"],o=[];for(let a of s){if(a===e.method.toUpperCase())continue;let c=j.find(a,r);c&&c.handler!==this.handleNotFound&&o.push(a);}if(o.length){t.setHeader("Allow",o.join(", "));let a=new Be(r,e.method);t.methodNotAllowed({...A(a)});return}let i=new I(r,e.method);t.notFound({...A(i)});};registerNotFoundRoutes(){let e=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"];for(let t of e)j.addOrUpdate(t,"*",[],this.handleNotFound,{excludeFromSwagger:true});}};var J=class extends O{constructor(e){super(`File not found: ${e}`);}};var jr=class{constructor(e){this.options=e;}async getDownloadUrl(e,t=3600){await this.ensureClient();let r=this.containerClient.getBlockBlobClient(e),s=new Date(Date.now()-300*1e3),o=new Date(Date.now()+t*1e3),i=this.azureBlobLib.BlobSASPermissions.parse("r"),a=this.azureBlobLib.generateBlobSASQueryParameters({containerName:this.options.containerName,blobName:e,permissions:i,startsOn:s,expiresOn:o},this.sharedKeyCredential).toString();return `${r.url}?${a}`}async getUploadUrl(e,t=3600){await this.ensureClient();let r=this.containerClient.getBlockBlobClient(e),s=new Date(Date.now()-300*1e3),o=new Date(Date.now()+t*1e3),i=this.azureBlobLib.BlobSASPermissions.parse("w"),a=this.azureBlobLib.generateBlobSASQueryParameters({containerName:this.options.containerName,blobName:e,permissions:i,startsOn:s,expiresOn:o},this.sharedKeyCredential).toString();return `${r.url}?${a}`}async getPublicUrl(e){return await this.ensureClient(),this.containerClient.getBlockBlobClient(e).url}async listObjects(e){await this.ensureClient();let t=[],r=e?e.endsWith("/")?e:`${e}/`:void 0;for await(let s of this.containerClient.listBlobsFlat({prefix:r}))t.push(s.name);return t}async getObject(e,t="raw"){await this.ensureClient();try{let s=await this.containerClient.getBlockBlobClient(e).download();if(!s.readableStreamBody)throw new J(e);let o=t;if(o==="stream")return Readable.toWeb(s.readableStreamBody);let i=[];for await(let c of s.readableStreamBody)i.push(Buffer.isBuffer(c)?c:Buffer.from(c));let a=Buffer.concat(i);switch(o){case "raw":return new Uint8Array(a);case "text":return a.toString();default:throw new O("Invalid return type")}}catch(r){throw r.statusCode===404?new J(e):r}}async putObject(e,t,r){await this.ensureClient();let s=this.containerClient.getBlockBlobClient(e),o=t;await s.upload(o,o.length,{blobHTTPHeaders:{blobContentType:r||"application/octet-stream"}});}async deleteObject(e){await this.ensureClient();let t=this.containerClient.getBlockBlobClient(e);try{await t.delete();}catch(r){if(r&&typeof r=="object"&&"statusCode"in r&&r.statusCode===404)return;throw r}}async ensureClient(){if(this.azureBlobLib)return;this.azureBlobLib=await import('@azure/storage-blob').catch(()=>{throw new O("Library not installed: @azure/storage-blob, try run npm install @azure/storage-blob")}),this.blobServiceClient=this.azureBlobLib.BlobServiceClient.fromConnectionString(this.options.connectionString),this.containerClient=this.blobServiceClient.getContainerClient(this.options.containerName);let e=this.blobServiceClient.credential;if(!(e instanceof this.azureBlobLib.StorageSharedKeyCredential))throw new O("BlobStorage requires a shared key credential to generate SAS URLs");this.sharedKeyCredential=e;}};var qr=class{constructor(e){this.options=e;}wasDirectoryEnsured=false;async getDownloadUrl(e,t=3600){throw new O("LocalStorageProvider does not support getDownloadUrl. Use S3 or Azure Blob storage for signed URLs.")}async getUploadUrl(e,t=3600){throw new O("LocalStorageProvider does not support getUploadUrl. Use S3 or Azure Blob storage for signed URLs.")}async getPublicUrl(e){throw new O("`getPublicUrl` is not available in local storage provider")}async listObjects(e){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let t=h.resolve(this.options.directory),r=e?h.join(t,e):t;if(!await u.exists(r))return [];let o=[];return await this.listFilesRecursively(r,t,o),o}async getObject(e,t="raw"){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let r=h.join(this.options.directory,e);if(!await u.exists(r))throw new J(e);switch(t){case "raw":return await u.readFile(r);case "text":return await u.readFile(r,{encoding:"utf8"});case "stream":return await u.streamFile(r);default:throw new O("Invalid return type")}}async putObject(e,t,r){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let s=h.join(this.options.directory,e),o=h.join(s,"..");await u.mkdir(o,{recursive:true}),await u.writeFile(s,t);}async deleteObject(e){this.wasDirectoryEnsured||await this.ensureDirectoryExists();let t=h.join(this.options.directory,e);await u.exists(t)&&await u.unlink(t);}async listFilesRecursively(e,t,r){let s=await u.stat(e);if(s.isFile){let i=e.replace(t,"").replace(/^\//,"");r.push(i);return}if(!s.isDirectory)return;let o=await this.readDirectory(e);for(let i of o){let a=h.join(e,i);await this.listFilesRecursively(a,t,r);}}async readDirectory(e){let{runtime:t}=await Promise.resolve().then(()=>(U(),$t));switch(t.type){case "node":return await(await import('fs/promises')).readdir(e);case "bun":return await(await import('fs/promises')).readdir(e);case "deno":{let r=[];for await(let s of Deno.readDir(e))r.push(s.name);return r}default:throw new O("Unsupported runtime")}}async ensureDirectoryExists(){if(await u.exists(this.options.directory)){this.wasDirectoryEnsured=true;return}await u.mkdir(this.options.directory,{recursive:true}),this.wasDirectoryEnsured=true;}};var Er=class{options;constructor(e){this.options=e;}async getDownloadUrl(e,t=3600){if(await this.ensureClient(),!this.options.cloudfrontOptions)throw new O("getDownloadUrl requires CloudFront configuration");let{domainName:r,keyPairId:s,privateKey:o}=this.options.cloudfrontOptions,i=`https://${r}/${e}`,a=new Date(Date.now()+t*1e3).toISOString();return this.cloudfrontSignerLib.getSignedUrl({url:i,keyPairId:s,privateKey:o,dateLessThan:a})}async getUploadUrl(e,t=3600){await this.ensureClient();let r=new this.s3Lib.PutObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});return this.s3PresignerLib.getSignedUrl(this.s3Client,r,{expiresIn:t})}async getPublicUrl(e){await this.ensureClient();let{region:t,endpoint:r}=this.options.s3ClientConfig,s=this.options.s3ClientConfig.bucketName;return r?`${typeof r=="string"?r:r.toString()}/${s}/${e}`:`https://${s}.s3.${t}.amazonaws.com/${e}`}async listObjects(e){await this.ensureClient();let t=new this.s3Lib.ListObjectsV2Command({Bucket:this.options.s3ClientConfig.bucketName,Prefix:e});return (await this.s3Client.send(t)).Contents?.map(s=>s.Key).filter(Boolean)??[]}async getObject(e,t="raw"){await this.ensureClient();let r=new this.s3Lib.GetObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});try{let s=await this.s3Client.send(r);if(!s.Body)throw new J(e);switch(t){case "raw":return await s.Body.transformToByteArray();case "text":return await s.Body.transformToString();case "stream":return s.Body.transformToWebStream();default:throw new O("Invalid return type")}}catch(s){throw s.name==="NoSuchKey"?new J(e):s}}async putObject(e,t,r){await this.ensureClient();let s=new this.s3Lib.PutObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e,Body:t,ContentType:r});await this.s3Client.send(s);}async deleteObject(e){await this.ensureClient();let t=new this.s3Lib.DeleteObjectCommand({Bucket:this.options.s3ClientConfig.bucketName,Key:e});await this.s3Client.send(t);}async ensureClient(){this.s3Lib||(this.s3Lib=await import('@aws-sdk/client-s3').then(e=>e.default).catch(()=>{throw new O("Library not installed: @aws-sdk/client-s3, try run npm install @aws-sdk/client-s3")}),this.s3PresignerLib=await import('@aws-sdk/s3-request-presigner').then(e=>e.default).catch(()=>{throw new O("Library not installed: @aws-sdk/s3-request-presigner, try run npm install @aws-sdk/s3-request-presigner")}),this.options.cloudfrontOptions&&(this.cloudfrontSignerLib=await import('@aws-sdk/cloudfront-signer').then(e=>e.default).catch(()=>{throw new O("Library not installed: @aws-sdk/cloudfront-signer, try run npm install @aws-sdk/cloudfront-signer")})),this.s3Client=new this.s3Lib.S3Client(this.options.s3ClientConfig??{}));}};var Mr=class{providerOptions;defaultProvider;providerMap;constructor(e,t){this.providerOptions=e,this.defaultProvider=t.defaultProvider,this.providerMap=new Map(Object.entries(e).map(([r,s])=>[r,s]));}use(e){let t=this.providerMap.get(e);if(!t)throw new Error(`[Storage] Provider ${String(e)} not found`);return t}async getDownloadUrl(e,t){return this.providerOptions[this.defaultProvider].getDownloadUrl(e,t)}async getUploadUrl(e,t){return this.providerOptions[this.defaultProvider].getUploadUrl(e,t)}async getPublicUrl(e){return this.providerOptions[this.defaultProvider].getPublicUrl(e)}async listObjects(e){return this.providerOptions[this.defaultProvider].listObjects(e)}async getObject(e,t="raw"){return this.providerOptions[this.defaultProvider].getObject(e,t)}async putObject(e,t,r){return this.providerOptions[this.defaultProvider].putObject(e,t,r)}async deleteObject(e){return this.providerOptions[this.defaultProvider].deleteObject(e)}};var Ar=class{};var kr=n=>(e,t)=>(r,s,o)=>{let i={scope:e,handler:t,manager:n};if(typeof s>"u"){let c=x.get(r.prototype,"__class__");return c||(c={policies:[]}),c.policies||(c.policies=[]),c.policies.push(i),x.set(r.prototype,"__class__",c),r}let a=x.get(r,s);return a||(a={policies:[]}),a.policies||(a.policies=[]),a.policies.push(i),x.set(r,s,a),o};var $r=class{providers;constructor(e){this.providers=e;}createDecorator(){return kr(this)}canAccess(e,t,...r){let s=this.providers[e];if(!s)throw new O(`Policy provider for ${String(e)} not found`);return s[t](...r)}};var cu=j;
575
+ export{wo as ARG_SYMBOL,jr as AzureBlobStorageProvider,_t as BaseCron,Dt as BaseMqtt,Ar as BasePlugin,It as BaseQueue,Je as BullMQPubSub,q as Command,Pt as CommandRegistry,Te as CronService,Ie as CustomTypedQueue,Z as GraphQL,qr as LocalStorageProvider,De as MqttService,Ye as PGBossPubSub,$r as PolicyManager,re as QueueManager,he as QueueService,W as Request,oe as Response,Er as S3StorageProvider,Xe as SQSPubSub,Cr as Server,Mr as Storage,ge as TypedQueue,ue as VALIDATION_ERROR_SYMBOL,k as arg,Ct as asyncLocalStorage,Ne as asyncStorage,ss as baseCommands,Zr as bullmqQueue,Ae as commandRegistry,Vt as compression,Ao as controller,Jt as cookie,Xt as cors,nr as createExpressAdapter,kr as createPolicyDecorator,Yr as createQueue,io as cron,Vs as defineLoggerConfig,di as defineQueueConfiguration,Bo as del,ws as expressHandler,_e as expressMiddleware,R as flag,No as get,Ot as getContentType,Qe as hash,ir as helmet,cr as log,b as logger,pr as methodOverride,Zo as middleware,ot as mountExpressRouter,Cn as mqtt,Io as patch,Jr as pgbossQueue,Uo as post,Wo as put,lr as rateLimiter,cu as router,un as serialize,Kt as serveStatic,dr as session,so as setCronGlobalErrorHandler,On as setMqttGlobalErrorHandler,Vr as sqsQueue,hr as timeout,gr as trustProxy,fn as validate};//# sourceMappingURL=index.js.map
574
576
  //# sourceMappingURL=index.js.map