balda-js 0.0.26 → 0.0.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var Mt=Object.create;var te=Object.defineProperty;var Ze=Object.getOwnPropertyDescriptor;var At=Object.getOwnPropertyNames;var Ft=Object.getPrototypeOf,Ht=Object.prototype.hasOwnProperty;var kt=(s,e)=>{for(var t in e)te(s,t,{get:e[t],enumerable:!0})},Ke=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of At(e))!Ht.call(s,o)&&o!==t&&te(s,o,{get:()=>e[o],enumerable:!(r=Ze(e,o))||r.enumerable});return s};var T=(s,e,t)=>(t=s!=null?Mt(Ft(s)):{},Ke(e||!s||!s.__esModule?te(t,"default",{value:s,enumerable:!0}):t,s)),_t=s=>Ke(te({},"__esModule",{value:!0}),s),P=(s,e,t,r)=>{for(var o=r>1?void 0:r?Ze(e,t):e,n=s.length-1,a;n>=0;n--)(a=s[n])&&(o=(r?a(e,t,o):a(o))||o);return r&&o&&te(e,t,o),o};var gr={};kt(gr,{ARG_SYMBOL:()=>Jt,BasePlugin:()=>Xe,Command:()=>O,CommandRegistry:()=>ue,Request:()=>M,Response:()=>N,Server:()=>Ye,VALIDATION_ERROR_SYMBOL:()=>_,arg:()=>q,commandRegistry:()=>ke,controller:()=>jt,cookie:()=>Ne,cors:()=>ze,del:()=>Nt,fileParser:()=>Ve,flag:()=>j,get:()=>Dt,getContentType:()=>he,helmet:()=>Ge,json:()=>Je,log:()=>De,middleware:()=>zt,patch:()=>It,post:()=>Ut,put:()=>Bt,rateLimiter:()=>Ie,router:()=>hr,serialize:()=>Lt,serveStatic:()=>je,session:()=>Ue,timeout:()=>Be,trustProxy:()=>qe,urlencoded:()=>Le,validate:()=>Vt});module.exports=_t(gr);var et=require("path");var l=class{static metadata=new WeakMap;static set(e,t,r){this.metadata.has(e)||this.metadata.set(e,new Map),this.metadata.get(e).set(t,r)}static get(e,t){return this.metadata.get(e)?.get(t)}static getAll(e){return this.metadata.get(e)||new Map}static delete(e,t){this.metadata.get(e)?.delete(t.toString())}static clear(e){this.metadata.delete(e)}};var Y=class{staticChildren;paramChild;wildcardChild;middleware;handler;constructor(){this.staticChildren=new Map,this.paramChild=null,this.wildcardChild=null,this.middleware=null,this.handler=null}},Ce=class s{trees;routes;middlewares;basePath;constructor(e="",t=[]){this.trees=new Map,this.routes=[],this.middlewares=t,this.basePath=this.normalizeBasePath(e)}getRoutes(){return this.routes.slice()}addOrUpdate(e,t,r,o,n){e=e.toUpperCase();let a=this.trees.get(e);a||(a=new Y,this.trees.set(e,a));let d=t.split("?")[0].replace(/^\/+|\/+$/g,""),i=d.length===0?[]:d.split("/"),c=a;for(let m of i){if(m==="*"){c.wildcardChild||(c.wildcardChild=new Y),c=c.wildcardChild;break}if(m.startsWith(":")){let g=m.slice(1);c.paramChild||(c.paramChild={node:new Y,name:g}),c=c.paramChild.node;continue}c.staticChildren.has(m)||c.staticChildren.set(m,new Y),c=c.staticChildren.get(m)}c.middleware=r,c.handler=o;let u=this.routes.findIndex(m=>m.method===e&&m.path===t);if(u!==-1){this.routes[u].middleware=r,this.routes[u].handler=o;return}this.routes.push({method:e,path:t,middleware:r,handler:o,swaggerOptions:n})}find(e,t){e=e.toUpperCase();let r=this.trees.get(e);if(!r)return null;let n=t.split("?")[0].replace(/^\/+|\/+$/g,""),a=n.length===0?[]:n.split("/"),p={},d=r;for(let i=0;i<a.length;i++){let c=a[i];if(d.staticChildren.has(c)){d=d.staticChildren.get(c);continue}if(d.paramChild){p[d.paramChild.name]=c,d=d.paramChild.node;continue}if(d.wildcardChild){p["*"]=a.slice(i).join("/"),d=d.wildcardChild;break}return null}return!d.handler||!d.middleware?null:{middleware:d.middleware,handler:d.handler,params:p}}get(e,t,r,o){let n=this.joinPath(e),a=typeof t=="function"&&t.length!==3,p=a?t:r,d=a?[]:Array.isArray(t)?t:[t],i=[...this.middlewares,...d],c=a?r:o;this.addOrUpdate("GET",n,i,p,c)}post(e,t,r,o){let n=this.joinPath(e),a=typeof t=="function"&&t.length!==3,p=a?t:r,d=a?[]:Array.isArray(t)?t:[t],i=[...this.middlewares,...d],c=a?r:o;this.addOrUpdate("POST",n,i,p,c)}patch(e,t,r,o){let n=this.joinPath(e),a=typeof t=="function"&&t.length!==3,p=a?t:r,d=a?[]:Array.isArray(t)?t:[t],i=[...this.middlewares,...d],c=a?r:o;this.addOrUpdate("PATCH",n,i,p,c)}put(e,t,r,o){let n=this.joinPath(e),a=typeof t=="function"&&t.length!==3,p=a?t:r,d=a?[]:Array.isArray(t)?t:[t],i=[...this.middlewares,...d],c=a?r:o;this.addOrUpdate("PUT",n,i,p,c)}delete(e,t,r,o){let n=this.joinPath(e),a=typeof t=="function"&&t.length!==3,p=a?t:r,d=a?[]:Array.isArray(t)?t:[t],i=[...this.middlewares,...d],c=a?r:o;this.addOrUpdate("DELETE",n,i,p,c)}options(e,t,r,o){let n=this.joinPath(e),a=typeof t=="function"&&t.length!==3,p=a?t:r,d=a?[]:Array.isArray(t)?t:[t],i=[...this.middlewares,...d],c=a?r:o;this.addOrUpdate("OPTIONS",n,i,p,c)}group(e,t,r){let o=Array.isArray(t)?t:typeof t=="function"?[]:t?[t]:[],n=Array.isArray(t)?r:typeof t=="function"?t:void 0,a=this.joinPath(e),p=new s(a,[...this.middlewares,...o]);n?.(p);for(let d of p.getRoutes())this.addOrUpdate(d.method,d.path,d.middleware,d.handler,d.swaggerOptions)}applyGlobalMiddlewaresToAllRoutes(e){for(let t of this.routes)this.addOrUpdate(t.method,t.path,[...e,...t.middleware||[]],t.handler)}normalizeBasePath(e){if(!e)return"";let t=e.replace(/\s+/g,"");return t=t.replace(/\/+/g,"/"),t.startsWith("/")||(t="/"+t),t.length>1&&(t=t.replace(/\/+$/g,"")),t}joinPath(e){let r=[this.basePath,e].filter(o=>typeof o=="string"&&o.length>0).join("/");return r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r.length>1&&(r=r.replace(/\/+$/g,"")),r}},h=new Ce;var jt=(s,e)=>t=>{let o=l.get(t.prototype,"__class__")?.middlewares||[],n=l.getAll(t.prototype);for(let[a,p]of n.entries()){if(!p.route)continue;let d=t.prototype[a],i=s?(0,et.join)(s,p.route.path):p.route.path,c=[...o,...p.middlewares||[]];h.addOrUpdate(p.route.method,i,c,d,{service:t.name.replace(/Controller$/,""),...e,...p.documentation})}l.clear(t.prototype)};var Nt=(s,e)=>(t,r,o)=>{let n=l.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"DELETE"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"DELETE"},l.set(t,r,n),o};var Dt=(s,e)=>(t,r,o)=>{let n=l.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"GET"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"GET"},l.set(t,r,n),o};var It=(s,e)=>(t,r,o)=>{let n=l.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"PATCH"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"PATCH"},l.set(t,r,n),o};var Ut=(s,e)=>(t,r,o)=>{let n=l.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"POST"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"POST"},l.set(t,r,n),o};var Bt=(s,e)=>(t,r,o)=>{let n=l.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"PUT"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"PUT"},l.set(t,r,n),o};var st=require("ajv");var ae=T(require("ajv"),1),tt=T(require("ajv-formats"),1),qt=(0,tt.default)(new ae.default,["date-time","time","date","email","hostname","ipv4","ipv6","uri","uri-reference","uuid","uri-template","json-pointer","relative-json-pointer","regex","password","binary","byte","iso-date-time","iso-time"]),H=(s,e,t=!1)=>{let r=qt.compile(s);if(!r(e)){if(t)return e;throw new ae.ValidationError(r.errors||[])}return e};var rt=Symbol("serializeWrapped"),X=Symbol("serializeMetadata"),Lt=(s,e)=>(t,r,o)=>{let n=l.get(t,r)||{middlewares:[],route:{}};n.documentation||(n.documentation={}),n.documentation.responses||(n.documentation.responses={}),n.serializeOptions||(n.serializeOptions={});let a=Number(e?.status??200);if(n.documentation.responses[a]=s,n.serializeOptions[a]=e?.safe??!0,l.set(t,r,n),o.value[X]||(o.value[X]={}),o.value[X][a]={schema:s,safe:e?.safe??!0},!o.value[rt]){let p=o.value;o.value=async function(...d){let i=d[1];await p.apply(this,d);let c=i.responseStatus,u=p[X],m=u?.[c]?.schema,g=u?.[c]?.safe??!0;if(m&&!g){let f=i.getBody();try{i.send(H(m,f,g))}catch(S){if(S instanceof st.ValidationError){i.internalServerError({received:f,schema:m,error:S.errors});return}throw S}}},o.value[rt]=!0,o.value[X]=p[X]}};var zt=s=>(e,t,r)=>{if(typeof t>"u"){let n=l.get(e.prototype,"__class__");if(n||(n={middlewares:[]}),n.middlewares||(n.middlewares=[]),!s)throw new Error(`Middleware ${String(s)} not found, are you sure you defined it before using it?`);return Array.isArray(s)||(s=[s]),n.middlewares.push(...s),l.set(e.prototype,"__class__",n),e}let o=l.get(e,t);return o||(o={middlewares:[]}),o.middlewares||(o.middlewares=[]),Array.isArray(s)||(s=[s]),o.middlewares.push(...s),l.set(e,t,o),r};var ot=require("ajv");var U=s=>(e,t,r)=>{let o=r.value,n=l.get(e,t);return n||(n={middlewares:[],route:{}}),n.documentation||(n.documentation={}),s.body&&(n.documentation.requestBody=s.body),s.query&&(n.documentation.query=s.query),l.set(e,t,n),r.value=async function(...a){let p=a[0],d=a[1];try{let i,c,u;s.body&&(i=p.validate(s.body,s.safe)),s.query&&(c=p.validateQuery(s.query,s.safe)),s.all&&(u=p.validateAll(s.all,s.safe));let m=[...a];return i!==void 0&&m.push(i),c!==void 0&&m.push(c),u!==void 0&&m.push(u),o.apply(this,m)}catch(i){if(!(i instanceof ot.ValidationError))throw i;return s.customError?d.status(s.customError.status||400).json({received:p.body,schema:s.body,error:i.errors}):d.badRequest(i)}},r};U.query=(s,e)=>U({query:s,customError:e});U.body=(s,e)=>U({body:s,customError:e});U.all=(s,e)=>U({all:s,customError:e});var Vt=U;var Ee=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")}},y=new Ee;var $e=class{getCliArgs(){switch(y.type){case"bun":return this.getBunArgs();case"node":return this.getNodeArgs();case"deno":return Deno.args;default:throw new Error("Unsupported runtime")}}getBunArgs(){let e=Bun.argv,t=this.findScriptIndex(e);return e.slice(t+1)}getNodeArgs(){let e=process.argv,t=this.findScriptIndex(e);return e.slice(t+1)}findScriptIndex(e){if(e.length>=3&&e[1].includes(".bin/"))return 1;for(let t=0;t<e.length;t++){let r=e[t],o=r.split("/").pop()||r;if(!r.startsWith("-")){if(o==="yarn"&&t+1<e.length&&e[t+1]==="run"||o==="npx"&&t+1<e.length)return t+1;if(o==="yarn"||o==="pnpm")return t;if(o==="npm"&&t+1<e.length&&e[t+1]==="run"||o==="bun"&&t+1<e.length&&e[t+1]==="run")return t+1;if(/\.(js|ts|mjs|cjs)$/.test(r))return t;if(/^(tsx|ts-node|node|bun)$/.test(o)){for(let n=t+1;n<e.length;n++)if(!e[n].startsWith("-")&&/\.(js|ts|mjs|cjs)$/.test(e[n]))return n;return t}}}for(let t=e.length-1;t>=0;t--)if(!e[t].startsWith("-"))return t;return 1}},Pe=new $e;var Gt=s=>{if(!s||s==="-"||s==="--")return null;let e=s.indexOf("=");if(e>0){let t=s.substring(0,e),r=s.substring(e+1);return{name:t,value:nt(r)}}return{name:s,value:!0}},nt=s=>{if(s.toLowerCase()==="true")return!0;if(s.toLowerCase()==="false")return!1;let e=Number(s);return!Number.isNaN(e)&&Number.isFinite(e)?e:s},B=()=>{let s=Pe.getCliArgs(),e=[],t={};if(!s||!s.length)return{args:e,flags:t};for(let r=0;r<s.length;r++){let o=s[r];if(!(!o||typeof o!="string")){if(o.startsWith("-")){let n=Gt(o);if(n){if(n.value===!0&&r+1<s.length){let a=s[r+1];a&&typeof a=="string"&&!a.startsWith("-")&&(n.value=nt(a),r++)}t[n.name]=n.value}continue}e.push(o)}}return{args:e,flags:t}};var de=()=>Pe.getCliArgs()[0]||null;var _="VALIDATION_ERROR",Jt="ARG",it=B().args.slice(1),q=s=>(e,t)=>{let r=de();if(!r||r!==e.commandName)return;let o=t;l.set(e,t,{type:"arg",name:o,description:s.description});let n=it.length?it.shift():s.defaultValue;if(s.required&&!n){let a=l.get(e,_);l.set(e,_,[...a||[],{type:"arg",name:o,message:"Required argument not provided"}]);return}s.parse&&n&&(n=s.parse(n)),Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0})};var L=s=>(e,t)=>{let r=de();if(!r||r!==e.commandName)return;let o=s.name||t,n=B().flags,a=s.aliases||[],p=[o,...a],d=s.defaultValue;for(let i of p){let c=[i,`-${i}`,`--${i}`];for(let u of c)if(u in n){d=n[u],s.type==="boolean"?d=!!d:s.type==="number"&&(d=Number(d)),s.parse&&(d=s.parse(d));break}if(d!==s.defaultValue)break}if(l.set(e,t,{type:"flag",name:o,aliases:a||[],description:s.description}),s.required&&!d){let i=l.get(e,_);l.set(e,_,[...i||[],{type:"flag",name:o,message:"Required flag not provided"}]);return}Object.defineProperty(e,t,{value:d,enumerable:!0,configurable:!0,writable:!0})};L.boolean=s=>L({...s,type:"boolean"});L.string=s=>L({...s,type:"string"});L.number=s=>L({...s,type:"number"});var j=L;var pt=require("glob");var pe=require("path");var Me=class{exit(e){switch(y.type){case"bun":case"node":process.exit(e);case"deno":Deno.exit(e);default:throw new Error("Unsupported runtime")}}},Ae=new Me;var at=T(require("pino"),1),Wt=()=>(0,at.default)({level:"info",formatters:{level:e=>({level:e})}}),v=Wt();var O=class{static commandName=this.name;static description="";static help=[];static options={keepAlive:!1};static args=B().args.slice(1);static flags=B().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(i=>t.includes(i)))return;let o=this.commandName,n=this.description||"No description available",a=this.help||[],p=this.options,d=this.generateHelpOutput({name:o,description:n,helpText:a,options:p,args:this.args,flags:this.flags},this);console.log(d),Ae.exit(0)}static generateHelpOutput=(e,t)=>{let{name:r,description:o,helpText:n,options:a,args:p,flags:d}=e,i={title:"\x1B[1;36m",subtitle:"\x1B[1;33m",description:"\x1B[0;37m",code:"\x1B[0;32m",flag:"\x1B[0;35m",reset:"\x1B[0m",error:"\x1B[0;31m",success:"\x1B[0;32m",info:"\x1B[0;34m"},c=[`${i.title}${r}${i.reset}`,`${i.description}${o}${i.reset}`,"",`${i.subtitle}Usage:${i.reset}`,` ${i.code}${r}${i.reset} [options] [arguments]`,"",`${i.subtitle}Options:${i.reset}`,` ${i.flag}-h, --help${i.reset} Show this help message`,"",`${i.subtitle}Command Options:${i.reset}`,` ${i.flag}keepAlive${i.reset} ${a?.keepAlive??!1?i.success+"Enabled"+i.reset:i.error+"Disabled"+i.reset}`,""];if(n){let f=Array.isArray(n)?n:[n];c.push(`${i.subtitle}Help:${i.reset}`),f.forEach(S=>{c.push(` ${i.description}${S}${i.reset}`)}),c.push("")}let u=l.getAll(t),m=Array.from(u.values()).filter(f=>f.type==="arg"),g=Array.from(u.values()).filter(f=>f.type==="flag");return m.length&&(c.push(`${i.subtitle}Available Arguments:${i.reset}`),m.forEach(f=>{let S=f.required?` ${i.error}(required)${i.reset}`:"",R=f.description?` ${i.description}${f.description}${i.reset}`:"";c.push(` ${i.code}${f.name}${i.reset}${S}${R}`)}),c.push("")),g.length&&(c.push(`${i.subtitle}Available Flags:${i.reset}`),g.forEach(f=>{f.aliases&&!Array.isArray(f.aliases)&&(f.aliases=[f.aliases]);let S=f.aliases.length?` ${i.flag}(${f.aliases.join(", ")})${i.reset}`:"",R=f.required?` ${i.error}(required)${i.reset}`:"",E=f.description?` ${i.description}${f.description}${i.reset}`:"";c.push(` ${i.flag}--${f.name}${S}${i.reset}${R}${E}`)}),c.push("")),((p?.length??0)>0||d&&Object.keys(d).length>0)&&(c.push(`${i.subtitle}Current Context:${i.reset}`),p?.length&&c.push(` ${i.info}Provided Arguments:${i.reset} ${i.code}${p.join(" ")}${i.reset}`),d&&Object.keys(d).length>0&&(c.push(` ${i.info}Provided Flags:${i.reset}`),Object.keys(d).forEach(f=>{let S=d[f],R=S!=null?` = ${i.code}${S}${i.reset}`:"";c.push(` ${i.flag}${f}${i.reset}${R}`)})),c.push("")),n&&(Array.isArray(n)?n.some(f=>f.includes("example")):n.includes("example"))&&(c.push(`${i.subtitle}Examples:${i.reset}`),(Array.isArray(n)?n.filter(S=>S.includes("example")):[n.split("example")[1].trim()]).forEach(S=>{c.push(` ${i.code}${S}${i.reset}`)}),c.push("")),c.join(`
2
- `)};static validateContext=e=>{let t=Array.from(l.get(e,_)||[]);if(t.length){let r={error:"\x1B[0;31m",title:"\x1B[1;31m",reset:"\x1B[0m",info:"\x1B[0;34m",code:"\x1B[0;32m"};console.error(`${r.title}\u274C Validation Errors:${r.reset}`),console.error(""),t.forEach((o,n)=>{let a=`${r.info}${n+1}.${r.reset}`,p=`${r.error}${o.type.toUpperCase()}${r.reset}`,d=`${r.code}${o.name}${r.reset}`;console.error(` ${a} ${p} ${d}: ${r.error}${o.message}${r.reset}`)}),console.error(""),console.error(`${r.info}\u{1F4A1} Tip: Use --help for usage information${r.reset}`),Ae.exit(1)}}};var Fe=class{async mkdir(e,t){switch(y.type){case"bun":case"node":await(await import("fs/promises")).mkdir(e,{recursive:t?.recursive??!1});break;case"deno":await Deno.mkdir(e,{recursive:t?.recursive??!1});break}}async exists(e){switch(y.type){case"node":return(await import("fs")).existsSync(e);case"bun":return Bun.file(e).exists();case"deno":return Deno.stat(e).then(()=>!0).catch(()=>!1);default:throw new Error("Unsupported runtime")}}async readFile(e){switch(y.type){case"node":let r=await(await import("fs/promises")).readFile(e);return new Uint8Array(r);case"bun":let o=await Bun.file(e).arrayBuffer();return new Uint8Array(o);case"deno":return new Uint8Array(await Deno.readFile(e))}}async writeFile(e,t){switch(y.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(y.type){case"node":let r=await(await import("fs/promises")).stat(e);return{isDirectory:r.isDirectory(),isFile:r.isFile(),isSymbolicLink:r.isSymbolicLink(),size:r.size};case"bun":let o=await Bun.file(e).stat();return{isDirectory:o.isDirectory(),isFile:o.isFile(),isSymbolicLink:o.isSymbolicLink(),size:o.size};case"deno":let n=await Deno.stat(e);return{isDirectory:n.isDirectory,isFile:n.isFile,isSymbolicLink:!1,size:n.size}}}async unlink(e){switch(y.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")}}},b=new Fe;var Q=class extends O{static commandName="generate-command";static description="Generate a new command in the specified path";static help=["Generate a new cli command in the specified path","Example: npx balda generate-command my-command -p src/commands"];static path="src/commands";static name;static async handle(){let e=this.getCommandTemplate();this.path=(0,pe.join)(this.path,`${this.name}.ts`),await b.exists((0,pe.join)(process.cwd(),this.path))||await b.mkdir((0,pe.join)(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:!0}),await b.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Command ${this.name} created successfully at ${this.path}`)}static getCommandTemplate(){return`import { Command, CommandOptions } from "balda-js";
1
+ "use strict";var Mt=Object.create;var te=Object.defineProperty;var Ze=Object.getOwnPropertyDescriptor;var At=Object.getOwnPropertyNames;var Ht=Object.getPrototypeOf,Ft=Object.prototype.hasOwnProperty;var kt=(s,e)=>{for(var t in e)te(s,t,{get:e[t],enumerable:!0})},Ke=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of At(e))!Ft.call(s,o)&&o!==t&&te(s,o,{get:()=>e[o],enumerable:!(r=Ze(e,o))||r.enumerable});return s};var T=(s,e,t)=>(t=s!=null?Mt(Ht(s)):{},Ke(e||!s||!s.__esModule?te(t,"default",{value:s,enumerable:!0}):t,s)),_t=s=>Ke(te({},"__esModule",{value:!0}),s),$=(s,e,t,r)=>{for(var o=r>1?void 0:r?Ze(e,t):e,n=s.length-1,a;n>=0;n--)(a=s[n])&&(o=(r?a(e,t,o):a(o))||o);return r&&o&&te(e,t,o),o};var gr={};kt(gr,{ARG_SYMBOL:()=>Jt,BasePlugin:()=>Xe,Command:()=>x,CommandRegistry:()=>ue,Request:()=>M,Response:()=>N,Server:()=>Ye,VALIDATION_ERROR_SYMBOL:()=>_,arg:()=>U,commandRegistry:()=>ke,controller:()=>jt,cookie:()=>Ne,cors:()=>ze,del:()=>Nt,fileParser:()=>Ve,flag:()=>j,get:()=>Dt,getContentType:()=>he,helmet:()=>Ge,json:()=>Je,log:()=>De,middleware:()=>zt,patch:()=>It,post:()=>qt,put:()=>Bt,rateLimiter:()=>Ie,router:()=>hr,serialize:()=>Lt,serveStatic:()=>je,session:()=>qe,timeout:()=>Be,trustProxy:()=>Ue,urlencoded:()=>Le,validate:()=>Vt});module.exports=_t(gr);var et=require("path");var l=class{static metadata=new WeakMap;static set(e,t,r){this.metadata.has(e)||this.metadata.set(e,new Map),this.metadata.get(e).set(t,r)}static get(e,t){return this.metadata.get(e)?.get(t)}static getAll(e){return this.metadata.get(e)||new Map}static delete(e,t){this.metadata.get(e)?.delete(t.toString())}static clear(e){this.metadata.delete(e)}};var Y=class{staticChildren;paramChild;wildcardChild;middleware;handler;constructor(){this.staticChildren=new Map,this.paramChild=null,this.wildcardChild=null,this.middleware=null,this.handler=null}},Ce=class s{trees;routes;middlewares;basePath;constructor(e="",t=[]){this.trees=new Map,this.routes=[],this.middlewares=t,this.basePath=this.normalizeBasePath(e)}getRoutes(){return this.routes.slice()}addOrUpdate(e,t,r,o,n){e=e.toUpperCase();let a=this.trees.get(e);a||(a=new Y,this.trees.set(e,a));let d=t.split("?")[0].replace(/^\/+|\/+$/g,""),i=d.length===0?[]:d.split("/"),c=a;for(let m of i){if(m==="*"){c.wildcardChild||(c.wildcardChild=new Y),c=c.wildcardChild;break}if(m.startsWith(":")){let h=m.slice(1);c.paramChild||(c.paramChild={node:new Y,name:h}),c=c.paramChild.node;continue}c.staticChildren.has(m)||c.staticChildren.set(m,new Y),c=c.staticChildren.get(m)}c.middleware=r,c.handler=o;let u=this.routes.findIndex(m=>m.method===e&&m.path===t);if(u!==-1){this.routes[u].middleware=r,this.routes[u].handler=o;return}this.routes.push({method:e,path:t,middleware:r,handler:o,swaggerOptions:n})}find(e,t){e=e.toUpperCase();let r=this.trees.get(e);if(!r)return null;let n=t.split("?")[0].replace(/^\/+|\/+$/g,""),a=n.length===0?[]:n.split("/"),p={},d=r;for(let i=0;i<a.length;i++){let c=a[i];if(d.staticChildren.has(c)){d=d.staticChildren.get(c);continue}if(d.paramChild){p[d.paramChild.name]=c,d=d.paramChild.node;continue}if(d.wildcardChild){p["*"]=a.slice(i).join("/"),d=d.wildcardChild;break}return null}return!d.handler||!d.middleware?null:{middleware:d.middleware,handler:d.handler,params:p}}get(e,t,r,o){let n=this.joinPath(e),a=typeof t=="function"&&t.length!==3,p=a?t:r,d=a?[]:Array.isArray(t)?t:[t],i=[...this.middlewares,...d],c=a?r:o;this.addOrUpdate("GET",n,i,p,c)}post(e,t,r,o){let n=this.joinPath(e),a=typeof t=="function"&&t.length!==3,p=a?t:r,d=a?[]:Array.isArray(t)?t:[t],i=[...this.middlewares,...d],c=a?r:o;this.addOrUpdate("POST",n,i,p,c)}patch(e,t,r,o){let n=this.joinPath(e),a=typeof t=="function"&&t.length!==3,p=a?t:r,d=a?[]:Array.isArray(t)?t:[t],i=[...this.middlewares,...d],c=a?r:o;this.addOrUpdate("PATCH",n,i,p,c)}put(e,t,r,o){let n=this.joinPath(e),a=typeof t=="function"&&t.length!==3,p=a?t:r,d=a?[]:Array.isArray(t)?t:[t],i=[...this.middlewares,...d],c=a?r:o;this.addOrUpdate("PUT",n,i,p,c)}delete(e,t,r,o){let n=this.joinPath(e),a=typeof t=="function"&&t.length!==3,p=a?t:r,d=a?[]:Array.isArray(t)?t:[t],i=[...this.middlewares,...d],c=a?r:o;this.addOrUpdate("DELETE",n,i,p,c)}options(e,t,r,o){let n=this.joinPath(e),a=typeof t=="function"&&t.length!==3,p=a?t:r,d=a?[]:Array.isArray(t)?t:[t],i=[...this.middlewares,...d],c=a?r:o;this.addOrUpdate("OPTIONS",n,i,p,c)}group(e,t,r){let o=Array.isArray(t)?t:typeof t=="function"?[]:t?[t]:[],n=Array.isArray(t)?r:typeof t=="function"?t:void 0,a=this.joinPath(e),p=new s(a,[...this.middlewares,...o]);n?.(p);for(let d of p.getRoutes())this.addOrUpdate(d.method,d.path,d.middleware,d.handler,d.swaggerOptions)}applyGlobalMiddlewaresToAllRoutes(e){for(let t of this.routes)this.addOrUpdate(t.method,t.path,[...e,...t.middleware||[]],t.handler)}normalizeBasePath(e){if(!e)return"";let t=e.replace(/\s+/g,"");return t=t.replace(/\/+/g,"/"),t.startsWith("/")||(t="/"+t),t.length>1&&(t=t.replace(/\/+$/g,"")),t}joinPath(e){let r=[this.basePath,e].filter(o=>typeof o=="string"&&o.length>0).join("/");return r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r.length>1&&(r=r.replace(/\/+$/g,"")),r}},g=new Ce;var jt=(s,e)=>t=>{let o=l.get(t.prototype,"__class__")?.middlewares||[],n=l.getAll(t.prototype);for(let[a,p]of n.entries()){if(!p.route)continue;let d=t.prototype[a],i=s?(0,et.join)(s,p.route.path):p.route.path,c=[...o,...p.middlewares||[]];g.addOrUpdate(p.route.method,i,c,d,{service:t.name.replace(/Controller$/,""),...e,...p.documentation})}l.clear(t.prototype)};var Nt=(s,e)=>(t,r,o)=>{let n=l.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"DELETE"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"DELETE"},l.set(t,r,n),o};var Dt=(s,e)=>(t,r,o)=>{let n=l.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"GET"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"GET"},l.set(t,r,n),o};var It=(s,e)=>(t,r,o)=>{let n=l.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"PATCH"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"PATCH"},l.set(t,r,n),o};var qt=(s,e)=>(t,r,o)=>{let n=l.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"POST"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"POST"},l.set(t,r,n),o};var Bt=(s,e)=>(t,r,o)=>{let n=l.get(t,r);return n||(n={middlewares:[],route:{path:s,method:"PUT"}}),n.documentation={...n.documentation||{},name:r,...e},n.route={path:s,method:"PUT"},l.set(t,r,n),o};var st=require("ajv");var ae=T(require("ajv"),1),tt=T(require("ajv-formats"),1),Ut=(0,tt.default)(new ae.default,["date-time","time","date","email","hostname","ipv4","ipv6","uri","uri-reference","uuid","uri-template","json-pointer","relative-json-pointer","regex","password","binary","byte","iso-date-time","iso-time"]),F=(s,e,t=!1)=>{let r=Ut.compile(s);if(!r(e)){if(t)return e;throw new ae.ValidationError(r.errors||[])}return e};var rt=Symbol("serializeWrapped"),X=Symbol("serializeMetadata"),Lt=(s,e)=>(t,r,o)=>{let n=l.get(t,r)||{middlewares:[],route:{}};n.documentation||(n.documentation={}),n.documentation.responses||(n.documentation.responses={}),n.serializeOptions||(n.serializeOptions={});let a=Number(e?.status??200);if(n.documentation.responses[a]=s,n.serializeOptions[a]=e?.safe??!0,l.set(t,r,n),o.value[X]||(o.value[X]={}),o.value[X][a]={schema:s,safe:e?.safe??!0},!o.value[rt]){let p=o.value;o.value=async function(...d){let i=d[1];await p.apply(this,d);let c=i.responseStatus,u=p[X],m=u?.[c]?.schema,h=u?.[c]?.safe??!0;if(m&&!h){let f=i.getBody();try{i.send(F(m,f,h))}catch(w){if(w instanceof st.ValidationError){i.internalServerError({received:f,schema:m,error:w.errors});return}throw w}}},o.value[rt]=!0,o.value[X]=p[X]}};var zt=s=>(e,t,r)=>{if(typeof t>"u"){let n=l.get(e.prototype,"__class__");if(n||(n={middlewares:[]}),n.middlewares||(n.middlewares=[]),!s)throw new Error(`Middleware ${String(s)} not found, are you sure you defined it before using it?`);return Array.isArray(s)||(s=[s]),n.middlewares.push(...s),l.set(e.prototype,"__class__",n),e}let o=l.get(e,t);return o||(o={middlewares:[]}),o.middlewares||(o.middlewares=[]),Array.isArray(s)||(s=[s]),o.middlewares.push(...s),l.set(e,t,o),r};var ot=require("ajv");var q=s=>(e,t,r)=>{let o=r.value,n=l.get(e,t);return n||(n={middlewares:[],route:{}}),n.documentation||(n.documentation={}),s.body&&(n.documentation.requestBody=s.body),s.query&&(n.documentation.query=s.query),l.set(e,t,n),r.value=async function(...a){let p=a[0],d=a[1];try{let i,c,u;s.body&&(i=p.validate(s.body,s.safe)),s.query&&(c=p.validateQuery(s.query,s.safe)),s.all&&(u=p.validateAll(s.all,s.safe));let m=[...a];return i!==void 0&&m.push(i),c!==void 0&&m.push(c),u!==void 0&&m.push(u),o.apply(this,m)}catch(i){if(!(i instanceof ot.ValidationError))throw i;return s.customError?d.status(s.customError.status||400).json({received:p.body,schema:s.body,error:i.errors}):d.badRequest(i)}},r};q.query=(s,e)=>q({query:s,customError:e});q.body=(s,e)=>q({body:s,customError:e});q.all=(s,e)=>q({all:s,customError:e});var Vt=q;var Pe=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")}},y=new Pe;var Ee=class{getCliArgs(){switch(y.type){case"bun":return this.getBunArgs();case"node":return this.getNodeArgs();case"deno":return Deno.args;default:throw new Error("Unsupported runtime")}}getBunArgs(){let e=Bun.argv,t=this.findScriptIndex(e);return e.slice(t+1)}getNodeArgs(){let e=process.argv,t=this.findScriptIndex(e);return e.slice(t+1)}findScriptIndex(e){if(e.length>=3&&e[1].includes(".bin/"))return 1;for(let t=0;t<e.length;t++){let r=e[t],o=r.split("/").pop()||r;if(!r.startsWith("-")){if(o==="yarn"&&t+1<e.length&&e[t+1]==="run"||o==="npx"&&t+1<e.length)return t+1;if(o==="yarn"||o==="pnpm")return t;if(o==="npm"&&t+1<e.length&&e[t+1]==="run"||o==="bun"&&t+1<e.length&&e[t+1]==="run")return t+1;if(/\.(js|ts|mjs|cjs)$/.test(r))return t;if(/^(tsx|ts-node|node|bun)$/.test(o)){for(let n=t+1;n<e.length;n++)if(!e[n].startsWith("-")&&/\.(js|ts|mjs|cjs)$/.test(e[n]))return n;return t}}}for(let t=e.length-1;t>=0;t--)if(!e[t].startsWith("-"))return t;return 1}},$e=new Ee;var Gt=s=>{if(!s||s==="-"||s==="--")return null;let e=s.indexOf("=");if(e>0){let t=s.substring(0,e),r=s.substring(e+1);return{name:t,value:nt(r)}}return{name:s,value:!0}},nt=s=>{if(s.toLowerCase()==="true")return!0;if(s.toLowerCase()==="false")return!1;let e=Number(s);return!Number.isNaN(e)&&Number.isFinite(e)?e:s},B=()=>{let s=$e.getCliArgs(),e=[],t={};if(!s||!s.length)return{args:e,flags:t};for(let r=0;r<s.length;r++){let o=s[r];if(!(!o||typeof o!="string")){if(o.startsWith("-")){let n=Gt(o);if(n){if(n.value===!0&&r+1<s.length){let a=s[r+1];a&&typeof a=="string"&&!a.startsWith("-")&&(n.value=nt(a),r++)}t[n.name]=n.value}continue}e.push(o)}}return{args:e,flags:t}};var de=()=>$e.getCliArgs()[0]||null;var _="VALIDATION_ERROR",Jt="ARG",it=B().args.slice(1),U=s=>(e,t)=>{let r=de();if(!r||r!==e.commandName)return;let o=t;l.set(e,t,{type:"arg",name:o,description:s.description});let n=it.length?it.shift():s.defaultValue;if(s.required&&!n){let a=l.get(e,_);l.set(e,_,[...a||[],{type:"arg",name:o,message:"Required argument not provided"}]);return}s.parse&&n&&(n=s.parse(n)),Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0})};var L=s=>(e,t)=>{let r=de();if(!r||r!==e.commandName)return;let o=s.name||t,n=B().flags,a=s.aliases||[],p=[o,...a],d=s.defaultValue;for(let i of p){let c=[i,`-${i}`,`--${i}`];for(let u of c)if(u in n){d=n[u],s.type==="boolean"?d=!!d:s.type==="number"&&(d=Number(d)),s.parse&&(d=s.parse(d));break}if(d!==s.defaultValue)break}if(l.set(e,t,{type:"flag",name:o,aliases:a||[],description:s.description}),s.required&&!d){let i=l.get(e,_);l.set(e,_,[...i||[],{type:"flag",name:o,message:"Required flag not provided"}]);return}Object.defineProperty(e,t,{value:d,enumerable:!0,configurable:!0,writable:!0})};L.boolean=s=>L({...s,type:"boolean"});L.string=s=>L({...s,type:"string"});L.number=s=>L({...s,type:"number"});var j=L;var pt=require("glob");var pe=require("path");var Me=class{exit(e){switch(y.type){case"bun":case"node":process.exit(e);case"deno":Deno.exit(e);default:throw new Error("Unsupported runtime")}}},Ae=new Me;var at=T(require("pino"),1),Wt=()=>(0,at.default)({level:"info",formatters:{level:e=>({level:e})}}),v=Wt();var x=class{static commandName=this.name;static description="";static help=[];static options={keepAlive:!1};static args=B().args.slice(1);static flags=B().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(i=>t.includes(i)))return;let o=this.commandName,n=this.description||"No description available",a=this.help||[],p=this.options,d=this.generateHelpOutput({name:o,description:n,helpText:a,options:p,args:this.args,flags:this.flags},this);console.log(d),Ae.exit(0)}static generateHelpOutput=(e,t)=>{let{name:r,description:o,helpText:n,options:a,args:p,flags:d}=e,i={title:"\x1B[1;36m",subtitle:"\x1B[1;33m",description:"\x1B[0;37m",code:"\x1B[0;32m",flag:"\x1B[0;35m",reset:"\x1B[0m",error:"\x1B[0;31m",success:"\x1B[0;32m",info:"\x1B[0;34m"},c=[`${i.title}${r}${i.reset}`,`${i.description}${o}${i.reset}`,"",`${i.subtitle}Usage:${i.reset}`,` ${i.code}${r}${i.reset} [options] [arguments]`,"",`${i.subtitle}Options:${i.reset}`,` ${i.flag}-h, --help${i.reset} Show this help message`,"",`${i.subtitle}Command Options:${i.reset}`,` ${i.flag}keepAlive${i.reset} ${a?.keepAlive??!1?i.success+"Enabled"+i.reset:i.error+"Disabled"+i.reset}`,""];if(n){let f=Array.isArray(n)?n:[n];c.push(`${i.subtitle}Help:${i.reset}`),f.forEach(w=>{c.push(` ${i.description}${w}${i.reset}`)}),c.push("")}let u=l.getAll(t),m=Array.from(u.values()).filter(f=>f.type==="arg"),h=Array.from(u.values()).filter(f=>f.type==="flag");return m.length&&(c.push(`${i.subtitle}Available Arguments:${i.reset}`),m.forEach(f=>{let w=f.required?` ${i.error}(required)${i.reset}`:"",S=f.description?` ${i.description}${f.description}${i.reset}`:"";c.push(` ${i.code}${f.name}${i.reset}${w}${S}`)}),c.push("")),h.length&&(c.push(`${i.subtitle}Available Flags:${i.reset}`),h.forEach(f=>{f.aliases&&!Array.isArray(f.aliases)&&(f.aliases=[f.aliases]);let w=f.aliases.length?` ${i.flag}(${f.aliases.join(", ")})${i.reset}`:"",S=f.required?` ${i.error}(required)${i.reset}`:"",P=f.description?` ${i.description}${f.description}${i.reset}`:"";c.push(` ${i.flag}--${f.name}${w}${i.reset}${S}${P}`)}),c.push("")),((p?.length??0)>0||d&&Object.keys(d).length>0)&&(c.push(`${i.subtitle}Current Context:${i.reset}`),p?.length&&c.push(` ${i.info}Provided Arguments:${i.reset} ${i.code}${p.join(" ")}${i.reset}`),d&&Object.keys(d).length>0&&(c.push(` ${i.info}Provided Flags:${i.reset}`),Object.keys(d).forEach(f=>{let w=d[f],S=w!=null?` = ${i.code}${w}${i.reset}`:"";c.push(` ${i.flag}${f}${i.reset}${S}`)})),c.push("")),n&&(Array.isArray(n)?n.some(f=>f.includes("example")):n.includes("example"))&&(c.push(`${i.subtitle}Examples:${i.reset}`),(Array.isArray(n)?n.filter(w=>w.includes("example")):[n.split("example")[1].trim()]).forEach(w=>{c.push(` ${i.code}${w}${i.reset}`)}),c.push("")),c.join(`
2
+ `)};static validateContext=e=>{let t=Array.from(l.get(e,_)||[]);if(t.length){let r={error:"\x1B[0;31m",title:"\x1B[1;31m",reset:"\x1B[0m",info:"\x1B[0;34m",code:"\x1B[0;32m"};console.error(`${r.title}\u274C Validation Errors:${r.reset}`),console.error(""),t.forEach((o,n)=>{let a=`${r.info}${n+1}.${r.reset}`,p=`${r.error}${o.type.toUpperCase()}${r.reset}`,d=`${r.code}${o.name}${r.reset}`;console.error(` ${a} ${p} ${d}: ${r.error}${o.message}${r.reset}`)}),console.error(""),console.error(`${r.info}\u{1F4A1} Tip: Use --help for usage information${r.reset}`),Ae.exit(1)}}};var He=class{async mkdir(e,t){switch(y.type){case"bun":case"node":await(await import("fs/promises")).mkdir(e,{recursive:t?.recursive??!1});break;case"deno":await Deno.mkdir(e,{recursive:t?.recursive??!1});break}}async exists(e){switch(y.type){case"node":return(await import("fs")).existsSync(e);case"bun":return Bun.file(e).exists();case"deno":return Deno.stat(e).then(()=>!0).catch(()=>!1);default:throw new Error("Unsupported runtime")}}async readFile(e){switch(y.type){case"node":let r=await(await import("fs/promises")).readFile(e);return new Uint8Array(r);case"bun":let o=await Bun.file(e).arrayBuffer();return new Uint8Array(o);case"deno":return new Uint8Array(await Deno.readFile(e))}}async writeFile(e,t){switch(y.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(y.type){case"node":let r=await(await import("fs/promises")).stat(e);return{isDirectory:r.isDirectory(),isFile:r.isFile(),isSymbolicLink:r.isSymbolicLink(),size:r.size};case"bun":let o=await Bun.file(e).stat();return{isDirectory:o.isDirectory(),isFile:o.isFile(),isSymbolicLink:o.isSymbolicLink(),size:o.size};case"deno":let n=await Deno.stat(e);return{isDirectory:n.isDirectory,isFile:n.isFile,isSymbolicLink:!1,size:n.size}}}async unlink(e){switch(y.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")}}},R=new He;var Q=class extends x{static commandName="generate-command";static description="Generate a new command in the specified path";static help=["Generate a new cli command in the specified path","Example: npx balda generate-command my-command -p src/commands"];static path="src/commands";static name;static async handle(){let e=this.getCommandTemplate();this.path=(0,pe.join)(this.path,`${this.name}.ts`),await R.exists((0,pe.join)(process.cwd(),this.path))||await R.mkdir((0,pe.join)(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:!0}),await R.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Command ${this.name} created successfully at ${this.path}`)}static getCommandTemplate(){return`import { Command, CommandOptions } from "balda-js";
3
3
 
4
4
  export default class extends Command {
5
5
  static commandName = "${this.name}";
@@ -13,7 +13,7 @@ export default class extends Command {
13
13
  static async handle(): Promise<void> {
14
14
  // Implement your command logic here
15
15
  }
16
- }`}};P([q({description:"The name of the command to generate",required:!0})],Q,"name",2);var ce=require("path");var z=class extends O{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=(0,ce.join)(this.pluginPath,`${this.pluginName}.ts`),await b.exists((0,ce.join)(process.cwd(),this.pluginPath))||await b.mkdir((0,ce.join)(process.cwd(),this.pluginPath.split("/").slice(0,-1).join("/")),{recursive:!0}),await b.writeFile(this.pluginPath,new TextEncoder().encode(e)),this.logger.info(`Plugin ${this.name} created successfully at ${this.pluginPath}`)}static getPluginTemplate(){return`import { BasePlugin, Request, Response, NextFunction, ServerRouteMiddleware } from "balda-js";
16
+ }`}};$([U({description:"The name of the command to generate",required:!0})],Q,"name",2);var ce=require("path");var z=class extends x{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=(0,ce.join)(this.pluginPath,`${this.pluginName}.ts`),await R.exists((0,ce.join)(process.cwd(),this.pluginPath))||await R.mkdir((0,ce.join)(process.cwd(),this.pluginPath.split("/").slice(0,-1).join("/")),{recursive:!0}),await R.writeFile(this.pluginPath,new TextEncoder().encode(e)),this.logger.info(`Plugin ${this.name} created successfully at ${this.pluginPath}`)}static getPluginTemplate(){return`import { BasePlugin, Request, Response, NextFunction, ServerRouteMiddleware } from "balda-js";
17
17
 
18
18
  export default class extends BasePlugin {
19
19
  async handle(): Promise<ServerRouteMiddleware> {
@@ -22,14 +22,14 @@ export default class extends BasePlugin {
22
22
  await next();
23
23
  };
24
24
  }
25
- }`}};P([q({description:"The name of the plugin to generate",required:!0})],z,"pluginName",2),P([j({description:"The path to the plugin to generate, default is src/plugins",type:"string",aliases:"p",name:"path",required:!1,defaultValue:"src/plugins"})],z,"pluginPath",2);var He=class{getCwd(){switch(y.type){case"node":case"bun":return process.cwd();case"deno":return Deno.cwd();default:throw new Error("Unsupported runtime")}}},k=new He;var dt=require("path");var V=class extends O{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=(0,dt.join)(this.path,`${this.fileName}.ts`),await b.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Cron job ${this.fileName} created successfully at ${this.path}`)}static getCronTemplate(){return`import { cron } from "balda-js";
25
+ }`}};$([U({description:"The name of the plugin to generate",required:!0})],z,"pluginName",2),$([j({description:"The path to the plugin to generate, default is src/plugins",type:"string",aliases:"p",name:"path",required:!1,defaultValue:"src/plugins"})],z,"pluginPath",2);var Fe=class{getCwd(){switch(y.type){case"node":case"bun":return process.cwd();case"deno":return Deno.cwd();default:throw new Error("Unsupported runtime")}}},k=new Fe;var dt=require("path");var V=class extends x{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=(0,dt.join)(this.path,`${this.fileName}.ts`),await R.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Cron job ${this.fileName} created successfully at ${this.path}`)}static getCronTemplate(){return`import { cron } from "balda-js";
26
26
 
27
27
  export default class {
28
28
  @cron("* * * * *")
29
29
  handle() {
30
30
  // Implement your cron job logic here
31
31
  }
32
- }`}};P([q({description:"The name of the cron job file to generate",required:!0})],V,"fileName",2),P([j({description:"The path to the cron job to generate, default is src/cron",type:"string",aliases:"p",name:"path",required:!1,defaultValue:"src/cron"})],V,"path",2);var G=class extends O{static commandName="init";static description="Initialize a new balda project in the current directory";static help=["Initialize a new balda project, it is given for granted that balda-js is installed in the project as a dependency","All the files are created in the /src directory (created if not exists)","It adds a server.ts for the file instance and a index.ts for the entry point with a dummy hello world route","Example: npx balda init -p ./src -t true"];static srcPath;static typescript;static async handle(){let e=this.typescript?"ts":"js",t=this.getServerTemplate(),r=this.getIndexTemplate();b.exists(this.srcPath)||await b.mkdir(this.srcPath,{recursive:!0}),await b.writeFile(`${this.srcPath}/server.${e}`,new TextEncoder().encode(t)),await b.writeFile(`${this.srcPath}/index.${e}`,new TextEncoder().encode(r))}static getServerTemplate(){return`import { Server } from "balda-js";
32
+ }`}};$([U({description:"The name of the cron job file to generate",required:!0})],V,"fileName",2),$([j({description:"The path to the cron job to generate, default is src/cron",type:"string",aliases:"p",name:"path",required:!1,defaultValue:"src/cron"})],V,"path",2);var G=class extends x{static commandName="init";static description="Initialize a new balda project in the current directory";static help=["Initialize a new balda project, it is given for granted that balda-js is installed in the project as a dependency","All the files are created in the /src directory (created if not exists)","It adds a server.ts for the file instance and a index.ts for the entry point with a dummy hello world route","Example: npx balda init -p ./src -t true"];static srcPath;static typescript;static async handle(){let e=this.typescript?"ts":"js",t=this.getServerTemplate(),r=this.getIndexTemplate();R.exists(this.srcPath)||await R.mkdir(this.srcPath,{recursive:!0}),await R.writeFile(`${this.srcPath}/server.${e}`,new TextEncoder().encode(t)),await R.writeFile(`${this.srcPath}/index.${e}`,new TextEncoder().encode(r))}static getServerTemplate(){return`import { Server } from "balda-js";
33
33
 
34
34
  const serverInstance = new Server({
35
35
  port: 80,
@@ -42,20 +42,20 @@ export { serverInstance as server };
42
42
  server.listen(({ url }) => {
43
43
  console.log(\`Server is running on \${url}\`);
44
44
  });
45
- `}};P([j.string({description:"The path to the project, default is the current directory /src",aliases:"p",name:"path",required:!1,defaultValue:"./src"})],G,"srcPath",2),P([j.boolean({description:"Whether to use typescript, default is true",aliases:"t",name:"typescript",required:!1,defaultValue:!0})],G,"typescript",2);var re=class extends O{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=ke.getCommands();console.log(`
45
+ `}};$([j.string({description:"The path to the project, default is the current directory /src",aliases:"p",name:"path",required:!1,defaultValue:"./src"})],G,"srcPath",2),$([j.boolean({description:"Whether to use typescript, default is true",aliases:"t",name:"typescript",required:!1,defaultValue:!0})],G,"typescript",2);var re=class extends x{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=ke.getCommands();console.log(`
46
46
  \u2728 Available Balda Commands:
47
47
  `);let t=Math.max(...e.map(r=>r.commandName.length));for(let r of e){let o=r.commandName.padEnd(t+2),n=r.description||"No description available";console.log(` \x1B[36m${o}\x1B[0m ${n}`)}console.log(`
48
48
  \x1B[90mRun 'npx balda <command> -h' for more information on a specific command.\x1B[0m
49
- `)}};var Yt={},ue=class s{commands;static commandsPattern="src/commands/**/*.{ts,js}";static logger=v;constructor(){this.commands=new Map}static getInstance(){return new s}static setCommandsPattern(e){this.commandsPattern=e}getCommand(e){return this.commands.get(e)??null}getCommands(){return Array.from(this.commands.values())}async loadCommands(e){s.logger.info(`Loading commands from ${e}`);let t=await(0,pt.glob)(e,{absolute:!0,cwd:k.getCwd()});if(t.some(o=>o.endsWith(".ts")))try{let{register:o}=await import("module");o("ts-node/esm",Yt.url)}catch{s.logger.error("Failed to register ts-node/esm, you need to install it in your project in order to use typescript in the cli\ntry running: `npm install -D ts-node`"),process.exit(1)}for(let o of t){let n=await import(o).then(a=>a.default?a.default:a).catch(a=>(s.logger.error(`Error loading command ${o}: ${a}`),null));n&&this.commands.set(n.commandName,n)}let r=[z,Q,V,G,re];for(let o of r)this.commands.set(o.commandName,o)}},ke=ue.getInstance();var J=require("@sinclair/typebox");var le=class extends Request{};var ct=require("crypto"),M=class s extends le{static fromRequest(e){return new s(e.url,{method:e.method,body:e.body,headers:e.headers})}static enrichRequest(e){return e.validate=(t,r=!1)=>(typeof t=="function"&&(t=t(J.Type)),H(t,e.body||{},r)),e.validateQuery=(t,r=!1)=>(typeof t=="function"&&(t=t(J.Type)),H(t,e.query||{},r)),e.validateAll=(t,r=!1)=>(typeof t=="function"&&(t=t(J.Type)),H(t,{...e.body?{body:e.body}:{},...e.query?{query:e.query}:{}},r)),e.file=t=>e.files.find(r=>r.formName===t)??null,e.files=[],e.saveSession=async()=>{},e.destroySession=async()=>{},e.session={},e.cookies={},e.cookie=t=>e.cookies[t],e}file=e=>this.files.find(t=>t.formName===e)??null;cookies={};cookie=e=>this.cookies[e];timeout;session=void 0;saveSession=async()=>{};destroySession=async()=>{};ip;files=[];params={};query={};get id(){return this._id||(this._id=(0,ct.randomUUID)()),this._id}body;validate(e,t=!1){return typeof e=="function"&&(e=e(J.Type)),H(e,this.body||{},t)}validateQuery(e,t=!1){return typeof e=="function"&&(e=e(J.Type)),H(e,this.query||{},t)}validateAll(e,t=!1){return typeof e=="function"&&(e=e(J.Type)),H(e,{...this.body?{body:this.body}:{},...this.query?{query:this.query}:{}},t)}};var ut=T(require("fs/promises"),1),_e=class{file(e){switch(y.type){case"bun":return Bun.file(e);case"node":return ut.default.readFile(e);case"deno":return Deno.readFile(e);default:throw new Error("Unsupported runtime")}}},me=new _e;var Z=require("path");var w=s=>({name:s.constructor.name,cause:s.cause,message:s.message,stack:s.stack});var C=class extends Error{constructor(e){super(e)}};var fe=class extends C{constructor(e,t){super(`METHOD_NOT_ALLOWED: Cannot ${t} ${e}`)}};var x=class extends C{constructor(e,t){super(`ROUTE_NOT_FOUND: Cannot ${t} ${e}`)}};var lt=new Map([[".html","text/html"],[".css","text/css"],[".js","application/javascript"],[".png","image/png"],[".jpg","image/jpeg"],[".gif","image/gif"],[".svg","image/svg+xml"],[".json","application/json"],[".txt","text/plain"],[".ico","image/x-icon"],[".webp","image/webp"],[".mp4","video/mp4"],[".mp3","audio/mpeg"],[".wav","audio/wav"],[".ogg","audio/ogg"],[".webm","video/webm"]]);var je=(s="public",e)=>(h.addOrUpdate("GET",`${s}/*`,[],async(t,r)=>Xt(t,r,s),{service:"StaticFiles",...e}),async(t,r,o)=>o());async function Xt(s,e,t){if(s.method!=="GET"&&s.method!=="HEAD")return e.status(405).json({...w(new fe(s.url,s.method))});let r=s.params["*"]||"",o=(0,Z.join)(t,r),n=(0,Z.resolve)(k.getCwd(),o);try{if(!(await b.stat(n)).isFile)return e.notFound({...w(new x(s.url,s.method))})}catch(d){if(d.code==="ENOENT")return e.notFound({...w(new x(s.url,s.method))});throw d}let a=he((0,Z.extname)(n));e.setHeader("Content-Type",a);let p=await me.file(n);e.raw(p)}function he(s){return lt.get(s)||"application/octet-stream"}var N=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.text(String(e));if(e instanceof Date)return this.text(e.toISOString());if(e instanceof RegExp)return this.text(e.toString());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=="function")return this.text(e.toString());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){let t=he(e),r=me.file(e);this.headers={...this.headers,"Content-Type":t}}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)}getBody(){return this.body}};var Ct=require("glob"),We=require("path");var mt=require("glob");var K=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 C("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",n=>this.globalErrorHandler(n));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 o=await(0,mt.glob)(r,{absolute:!0,cwd:k.getCwd()});t.push(...o)}await Promise.all(t.map(async r=>{await import(r).catch(o=>{v.error(`Error importing cron job: ${r}`),v.error(o)})}))}};var ee=class{constructor(e){this.response=e}body(){return this.response.getBody()}statusCode(){return this.response.responseStatus}headers(){return this.response.headers}assertStatus(e){if(this.response.responseStatus!==e)throw new Error(`Expected status ${e}, but got ${this.response.responseStatus}`);return this}assertHeader(e,t){if(this.response.headers[e]!==t)throw new Error(`Expected header ${e} to be ${t}, but got ${this.response.headers[e]}`);return this}assertHeaderExists(e){if(!(e in this.response.headers))throw new Error(`Expected header ${e} to exist, but it was not found`);return this}assertHeaderNotExists(e){if(e in this.response.headers)throw new Error(`Expected header ${e} to not exist, but it was found with value: ${this.response.headers[e]}`);return this}assertBodySubset(e){return this.assertSubset(this.body(),e,"body"),this}assertBodyDeepEqual(e){return this.assertDeepEqual(this.body(),e,"body"),this}assertBodyNotSubset(e){return this.assertNotSubset(this.body(),e,"body"),this}assertBodyNotDeepEqual(e){return this.assertNotDeepEqual(this.body(),e,"body"),this}assertCustom(e){return e(this.response),this}assertSubset(e,t,r){for(let o in t){let n=r===""?o:`${r}.${o}`,a=e[o],p=t[o];if(!(o in e))throw new Error(`Expected ${r} to have key ${o}, but it was not found`);if(this.isObject(p)&&this.isObject(a))this.assertSubset(a,p,n);else if(Array.isArray(p)&&Array.isArray(a))this.assertArraySubset(a,p,n);else if(a!==p)throw new Error(`Expected ${n} to be ${p}, but got ${a}`)}}assertDeepEqual(e,t,r){if(this.isObject(e)&&this.isObject(t)){let o=Object.keys(e),n=Object.keys(t);if(o.length!==n.length)throw new Error(`Expected ${r} to have ${n.length} keys, but got ${o.length}`);for(let a of n){let p=r==="body"?a:`${r}.${a}`;this.assertDeepEqual(e[a],t[a],p)}}else if(Array.isArray(e)&&Array.isArray(t))this.assertArrayDeepEqual(e,t,r);else if(e!==t)throw new Error(`Expected ${r} to be ${t}, but got ${e}`)}assertNotSubset(e,t,r){try{throw this.assertSubset(e,t,r),new Error(`Expected ${r} to NOT contain the subset, but it does`)}catch(o){if(o instanceof Error&&o.message.includes("Expected"))return;throw o}}assertNotDeepEqual(e,t,r){try{throw this.assertDeepEqual(e,t,r),new Error(`Expected ${r} to NOT be deeply equal, but it is`)}catch(o){if(o instanceof Error&&o.message.includes("Expected"))return;throw o}}assertArraySubset(e,t,r){if(t.length>e.length)throw new Error(`Expected ${r} to have at least ${t.length} elements, but got ${e.length}`);for(let o=0;o<t.length;o++){let n=`${r}[${o}]`,a=e[o],p=t[o];if(this.isObject(p)&&this.isObject(a))this.assertSubset(a,p,n);else if(Array.isArray(p)&&Array.isArray(a))this.assertArraySubset(a,p,n);else if(a!==p)throw new Error(`Expected ${n} to be ${p}, but got ${a}`)}}assertArrayDeepEqual(e,t,r){if(e.length!==t.length)throw new Error(`Expected ${r} to have ${t.length} elements, but got ${e.length}`);for(let o=0;o<t.length;o++){let n=`${r}[${o}]`;this.assertDeepEqual(e[o],t[o],n)}}isObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}};var D=async(s,e,t,r=new N)=>{let o=0;if(!s.length)return await e(t,r),r;let n=async()=>{if(o++,o>=s.length){await e(t,r);return}let p=s[o];await p(t,r,n)},a=s[0];return await a(t,r,n),r},I=s=>s?["post","put","patch","delete"].includes(s.toLowerCase()):!0;var ge=class{server;constructor(e){this.server=e}async request(e,t,r={}){let{headers:o={},query:n={},cookies:a={},ip:p}=r;this.validateOptions(r);let d=h.find(e.toUpperCase(),t);if(!d){let g=new N(404);return g.json({caller:"MockServer",error:"Route not found",path:t,method:e}),new ee(g)}let i=r.body,c="application/json";if(i&&typeof i=="object"&&!(i instanceof Uint8Array)&&!(i instanceof ArrayBuffer)&&(i=JSON.stringify(i)),r.formData){let g=`----WebKitFormBoundary${Math.random().toString(36).substring(2)}`;c=`multipart/form-data; boundary=${g}`,i=await this.formDataToMultipart(r.formData,g)}r.urlencoded&&(c="application/x-www-form-urlencoded",i=new URLSearchParams(r.urlencoded).toString());let u=new URL(`http://${this.server.host}:${this.server.port}${t}`);u.search=new URLSearchParams(n).toString();let m=new M(u.toString(),{method:e.toUpperCase(),body:I(e)?i:void 0,headers:{"content-type":c,...o}});m.query={...Object.fromEntries(u.searchParams.entries()),...n},m.params=d.params,m.cookies=a,m.ip=p;try{let g=await D(d.middleware,d.handler,m);return new ee(g)}catch(g){v.error(`Error processing mock request ${e} ${t}:`,g);let f=new N(500);return f.json({error:"Internal server error",message:g instanceof Error?g.message:String(g)}),new ee(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,o=[];for(let[d,i]of e.entries()){o.push(r.encode(`--${t}\r
49
+ `)}};var Yt={},ue=class s{commands;static commandsPattern="src/commands/**/*.{ts,js}";static logger=v;constructor(){this.commands=new Map}static getInstance(){return new s}static setCommandsPattern(e){this.commandsPattern=e}getCommand(e){return this.commands.get(e)??null}getCommands(){return Array.from(this.commands.values())}async loadCommands(e){s.logger.info(`Loading commands from ${e}`);let t=await(0,pt.glob)(e,{absolute:!0,cwd:k.getCwd()});if(t.some(o=>o.endsWith(".ts")))try{let{register:o}=await import("module");o("ts-node/esm",Yt.url)}catch{s.logger.error("Failed to register ts-node/esm, you need to install it in your project in order to use typescript in the cli\ntry running: `npm install -D ts-node`"),process.exit(1)}for(let o of t){let n=await import(o).then(a=>a.default?a.default:a).catch(a=>(s.logger.error(`Error loading command ${o}: ${a}`),null));n&&this.commands.set(n.commandName,n)}let r=[z,Q,V,G,re];for(let o of r)this.commands.set(o.commandName,o)}},ke=ue.getInstance();var J=require("@sinclair/typebox");var le=class extends Request{};var ct=require("crypto"),M=class s extends le{static fromRequest(e){return new s(e.url,{method:e.method,body:e.body,headers:e.headers})}static enrichRequest(e){return e.validate=(t,r=!1)=>(typeof t=="function"&&(t=t(J.Type)),F(t,e.body||{},r)),e.validateQuery=(t,r=!1)=>(typeof t=="function"&&(t=t(J.Type)),F(t,e.query||{},r)),e.validateAll=(t,r=!1)=>(typeof t=="function"&&(t=t(J.Type)),F(t,{...e.body?{body:e.body}:{},...e.query?{query:e.query}:{}},r)),e.file=t=>e.files.find(r=>r.formName===t)??null,e.files=[],e.saveSession=async()=>{},e.destroySession=async()=>{},e.session={},e.cookies={},e.cookie=t=>e.cookies[t],e}file=e=>this.files.find(t=>t.formName===e)??null;cookies={};cookie=e=>this.cookies[e];timeout;session=void 0;saveSession=async()=>{};destroySession=async()=>{};ip;files=[];params={};query={};get id(){return this._id||(this._id=(0,ct.randomUUID)()),this._id}body;validate(e,t=!1){return typeof e=="function"&&(e=e(J.Type)),F(e,this.body||{},t)}validateQuery(e,t=!1){return typeof e=="function"&&(e=e(J.Type)),F(e,this.query||{},t)}validateAll(e,t=!1){return typeof e=="function"&&(e=e(J.Type)),F(e,{...this.body?{body:this.body}:{},...this.query?{query:this.query}:{}},t)}};var ut=T(require("fs/promises"),1),_e=class{file(e){switch(y.type){case"bun":return Bun.file(e);case"node":return ut.default.readFile(e);case"deno":return Deno.readFile(e);default:throw new Error("Unsupported runtime")}}},me=new _e;var Z=require("path");var b=s=>({name:s.constructor.name,cause:s.cause,message:s.message,stack:s.stack});var C=class extends Error{constructor(e){super(e)}};var fe=class extends C{constructor(e,t){super(`METHOD_NOT_ALLOWED: Cannot ${t} ${e}`)}};var O=class extends C{constructor(e,t){super(`ROUTE_NOT_FOUND: Cannot ${t} ${e}`)}};var lt=new Map([[".html","text/html"],[".css","text/css"],[".js","application/javascript"],[".png","image/png"],[".jpg","image/jpeg"],[".gif","image/gif"],[".svg","image/svg+xml"],[".json","application/json"],[".txt","text/plain"],[".ico","image/x-icon"],[".webp","image/webp"],[".mp4","video/mp4"],[".mp3","audio/mpeg"],[".wav","audio/wav"],[".ogg","audio/ogg"],[".webm","video/webm"]]);var je=(s="public",e)=>(g.addOrUpdate("GET",`${s}/*`,[],async(t,r)=>Xt(t,r,s),{service:"StaticFiles",...e}),async(t,r,o)=>o());async function Xt(s,e,t){if(s.method!=="GET"&&s.method!=="HEAD")return e.status(405).json({...b(new fe(s.url,s.method))});let r=s.params["*"]||"",o=(0,Z.join)(t,r),n=(0,Z.resolve)(k.getCwd(),o);try{if(!(await R.stat(n)).isFile)return e.notFound({...b(new O(s.url,s.method))})}catch(d){if(d.code==="ENOENT")return e.notFound({...b(new O(s.url,s.method))});throw d}let a=he((0,Z.extname)(n));e.setHeader("Content-Type",a);let p=await me.file(n);e.raw(p)}function he(s){return lt.get(s)||"application/octet-stream"}var N=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.text(String(e));if(e instanceof Date)return this.text(e.toISOString());if(e instanceof RegExp)return this.text(e.toString());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=="function")return this.text(e.toString());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){let t=he(e),r=me.file(e);this.headers={...this.headers,"Content-Type":t}}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)}getBody(){return this.body}};var Ct=require("glob"),We=require("path");var mt=require("glob");var K=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 C("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",n=>this.globalErrorHandler(n));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 o=await(0,mt.glob)(r,{absolute:!0,cwd:k.getCwd()});t.push(...o)}await Promise.all(t.map(async r=>{await import(r).catch(o=>{v.error(`Error importing cron job: ${r}`),v.error(o)})}))}};var ee=class{constructor(e){this.response=e}body(){return this.response.getBody()}statusCode(){return this.response.responseStatus}headers(){return this.response.headers}assertStatus(e){if(this.response.responseStatus!==e)throw new Error(`Expected status ${e}, but got ${this.response.responseStatus}`);return this}assertHeader(e,t){if(this.response.headers[e]!==t)throw new Error(`Expected header ${e} to be ${t}, but got ${this.response.headers[e]}`);return this}assertHeaderExists(e){if(!(e in this.response.headers))throw new Error(`Expected header ${e} to exist, but it was not found`);return this}assertHeaderNotExists(e){if(e in this.response.headers)throw new Error(`Expected header ${e} to not exist, but it was found with value: ${this.response.headers[e]}`);return this}assertBodySubset(e){return this.assertSubset(this.body(),e,"body"),this}assertBodyDeepEqual(e){return this.assertDeepEqual(this.body(),e,"body"),this}assertBodyNotSubset(e){return this.assertNotSubset(this.body(),e,"body"),this}assertBodyNotDeepEqual(e){return this.assertNotDeepEqual(this.body(),e,"body"),this}assertCustom(e){return e(this.response),this}assertSubset(e,t,r){for(let o in t){let n=r===""?o:`${r}.${o}`,a=e[o],p=t[o];if(!(o in e))throw new Error(`Expected ${r} to have key ${o}, but it was not found`);if(this.isObject(p)&&this.isObject(a))this.assertSubset(a,p,n);else if(Array.isArray(p)&&Array.isArray(a))this.assertArraySubset(a,p,n);else if(a!==p)throw new Error(`Expected ${n} to be ${p}, but got ${a}`)}}assertDeepEqual(e,t,r){if(this.isObject(e)&&this.isObject(t)){let o=Object.keys(e),n=Object.keys(t);if(o.length!==n.length)throw new Error(`Expected ${r} to have ${n.length} keys, but got ${o.length}`);for(let a of n){let p=r==="body"?a:`${r}.${a}`;this.assertDeepEqual(e[a],t[a],p)}}else if(Array.isArray(e)&&Array.isArray(t))this.assertArrayDeepEqual(e,t,r);else if(e!==t)throw new Error(`Expected ${r} to be ${t}, but got ${e}`)}assertNotSubset(e,t,r){try{throw this.assertSubset(e,t,r),new Error(`Expected ${r} to NOT contain the subset, but it does`)}catch(o){if(o instanceof Error&&o.message.includes("Expected"))return;throw o}}assertNotDeepEqual(e,t,r){try{throw this.assertDeepEqual(e,t,r),new Error(`Expected ${r} to NOT be deeply equal, but it is`)}catch(o){if(o instanceof Error&&o.message.includes("Expected"))return;throw o}}assertArraySubset(e,t,r){if(t.length>e.length)throw new Error(`Expected ${r} to have at least ${t.length} elements, but got ${e.length}`);for(let o=0;o<t.length;o++){let n=`${r}[${o}]`,a=e[o],p=t[o];if(this.isObject(p)&&this.isObject(a))this.assertSubset(a,p,n);else if(Array.isArray(p)&&Array.isArray(a))this.assertArraySubset(a,p,n);else if(a!==p)throw new Error(`Expected ${n} to be ${p}, but got ${a}`)}}assertArrayDeepEqual(e,t,r){if(e.length!==t.length)throw new Error(`Expected ${r} to have ${t.length} elements, but got ${e.length}`);for(let o=0;o<t.length;o++){let n=`${r}[${o}]`;this.assertDeepEqual(e[o],t[o],n)}}isObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}};var D=async(s,e,t,r=new N)=>{let o=0;if(!s.length)return await e(t,r),r;let n=async()=>{if(o++,o>=s.length){await e(t,r);return}let p=s[o];await p(t,r,n)},a=s[0];return await a(t,r,n),r},I=s=>s?["post","put","patch","delete"].includes(s.toLowerCase()):!0;var ge=class{server;constructor(e){this.server=e}async request(e,t,r={}){let{headers:o={},query:n={},cookies:a={},ip:p}=r;this.validateOptions(r);let d=g.find(e.toUpperCase(),t);if(!d){let h=new N(404);return h.json({caller:"MockServer",error:"Route not found",path:t,method:e}),new ee(h)}let i=r.body,c="application/json";if(i&&typeof i=="object"&&!(i instanceof Uint8Array)&&!(i instanceof ArrayBuffer)&&(i=JSON.stringify(i)),r.formData){let h=`----WebKitFormBoundary${Math.random().toString(36).substring(2)}`;c=`multipart/form-data; boundary=${h}`,i=await this.formDataToMultipart(r.formData,h)}r.urlencoded&&(c="application/x-www-form-urlencoded",i=new URLSearchParams(r.urlencoded).toString());let u=new URL(`http://${this.server.host}:${this.server.port}${t}`);u.search=new URLSearchParams(n).toString();let m=new M(u.toString(),{method:e.toUpperCase(),body:I(e)?i:void 0,headers:{"content-type":c,...o}});m.query={...Object.fromEntries(u.searchParams.entries()),...n},m.params=d.params,m.cookies=a,m.ip=p;try{let h=await D(d.middleware,d.handler,m);return new ee(h)}catch(h){v.error(`Error processing mock request ${e} ${t}:`,h);let f=new N(500);return f.json({error:"Internal server error",message:h instanceof Error?h.message:String(h)}),new ee(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,o=[];for(let[d,i]of e.entries()){o.push(r.encode(`--${t}\r
50
50
  `));let c=`Content-Disposition: form-data; name="${d}"`,u="";if(i instanceof File&&(c+=`; filename="${i.name}"`,u=`Content-Type: ${i.type||"application/octet-stream"}\r
51
51
  `),o.push(r.encode(`${c}\r
52
52
  ${u}\r
53
53
  `)),i instanceof File){let m=await i.arrayBuffer();o.push(new Uint8Array(m)),o.push(r.encode(`\r
54
54
  `))}else o.push(r.encode(`${String(i)}\r
55
55
  `))}o.push(r.encode(`--${t}--\r
56
- `));let n=o.reduce((d,i)=>d+i.byteLength,0),a=new Uint8Array(n),p=0;for(let d of o)a.set(d,p),p+=d.byteLength;return a}validateOptions(e){let{body:t,formData:r,urlencoded:o}=e;if(t&&(r||o))throw new Error("Only one of body, formData, urlencoded can be provided");if(r&&(o||t))throw new Error("Only one of formData, urlencoded can be provided");if(o&&(t||r))throw new Error("Only one of urlencoded, body can be provided")}};var Ne=s=>{let e={secret:s?.secret??"",defaults:{path:"/",httpOnly:!0,secure:!1,sameSite:"Lax",...s?.defaults},parse:s?.parse??!0,sign:s?.sign??!1};return async(t,r,o)=>{if(e.parse){let n=Qt(t.headers.get("cookie")||"");t.cookies={};for(let[a,p]of Object.entries(n)){if(e.sign&&e.secret){let d=await er(p,e.secret);d!==!1&&(t.cookies[a]=d);continue}t.cookies[a]=p}}r.cookie=(n,a,p)=>{ft(r,n,a,{...e.defaults,...p},e)},r.clearCookie=(n,a)=>{Zt(r,n,{...e.defaults,...a})},await o()}};function Qt(s){let e={};if(!s)return e;let t=s.split(";");for(let r of t){let[o,n]=r.trim().split("=");o&&n&&(e[decodeURIComponent(o)]=decodeURIComponent(n))}return e}async function ft(s,e,t,r,o){let n=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;r.domain&&(n+=`; Domain=${r.domain}`),r.path&&(n+=`; Path=${r.path}`),r.expires&&(n+=`; Expires=${r.expires.toUTCString()}`),r.maxAge&&(n+=`; Max-Age=${r.maxAge}`),r.secure&&(n+="; Secure"),r.httpOnly&&(n+="; HttpOnly"),r.sameSite&&(n+=`; SameSite=${r.sameSite}`),r.priority&&(n+=`; Priority=${r.priority}`),o.sign&&o.secret&&(n=await Kt(n,o.secret));let a=s.headers["set-cookie"]||"",p=a?`${a}, ${n}`:n;s.setHeader("Set-Cookie",p)}function Zt(s,e,t){let r={...t,expires:new Date(0),maxAge:0};ft(s,e,"",r,{secret:"",defaults:{},parse:!0,sign:!1})}async function Kt(s,e){let t=new TextEncoder,r=t.encode(e),o=t.encode(s),n=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=await crypto.subtle.sign("HMAC",n,o),p=new Uint8Array(a),d=Array.from(p).map(i=>i.toString(16).padStart(2,"0")).join("");return`${s}.${d}`}async function er(s,e){let t=s.split(".");if(t.length!==2)return!1;let[r,o]=t,n=new TextEncoder,a=n.encode(e),p=n.encode(r),d=await crypto.subtle.importKey("raw",a,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=await crypto.subtle.sign("HMAC",d,p),c=new Uint8Array(i),u=Array.from(c).map(m=>m.toString(16).padStart(2,"0")).join("");return o===u?r:!1}var De=s=>async(e,t,r)=>{try{let o=e.body;(s?.logRequest??!0)&&v.info({type:"request",requestId:e.id,method:s?.requestPayload?.method??!0?e.method:void 0,url:s?.requestPayload?.url??!0?e.url:void 0,ip:s?.requestPayload?.ip??!0?e.ip:void 0,headers:s?.requestPayload?.headers??!0?e.headers:void 0,body:s?.requestPayload?.body??!1?ht(o):void 0}),await r(),(s?.logResponse??!0)&&v.info({type:"response",requestId:e.id,status:s?.responsePayload?.status??t.responseStatus,body:s?.responsePayload?.body??!1?ht(t.getBody()):void 0,headers:s?.responsePayload?.headers??!1?t.headers:void 0})}catch(o){throw v.error(o),o}};function ht(s){if(typeof s=="string"||s&&typeof s=="object"&&s.constructor===Object)return s}var ye=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 Ie=(s,e)=>{let t={type:"ip",limit:100,message:"ERR_RATE_LIMIT_EXCEEDED",statusCode:429,...s},r={type:"memory",...e};r.type==="memory"&&!r.windowMs&&(r.windowMs=6e4);let o=r.type==="memory"?new ye(r.windowMs):{get:r.get,set:r.set};return async(n,a,p)=>{let d=t.type==="ip"?n.ip:t.key(n),i=await o.get(d);return i>=t.limit?a.status(t.statusCode).json({message:t.message}):(await o.set(d,i+1),p())}};var gt=require("crypto");var ve=class{store=new Map;async get(e){let t=this.store.get(e);if(t){if(t.exp&&Date.now()>t.exp){this.store.delete(e);return}return t.value}}async set(e,t,r){let o=r?Date.now()+r*1e3:void 0;this.store.set(e,{value:t,exp:o})}async destroy(e){this.store.delete(e)}};var Ue=s=>{let e=s?.name??"sid",t=s?.ttl??60*60*24,r=s?.store??new ve,o={path:"/",httpOnly:!0,secure:!1,sameSite:"Lax",...s?.cookie??{}};return async(n,a,p)=>{let i=n.cookies&&n.cookies[e],c=i?await r.get(i):void 0;(!i||!c)&&(i||=(0,gt.randomUUID)(),c||={},await r.set(i,c,t),a.cookie?.(e,i,o)),n.session=c,n.saveSession=async()=>r.set(i,c,t),n.destroySession=async()=>{await r.destroy(i),a.clearCookie?.(e,o)},await p(),await r.set(i,c,t)}};var Be=s=>async(e,t,r)=>{e.timeout=!1;let o=setTimeout(()=>{e.timeout=!0},s.ms);try{await r()}finally{clearTimeout(o)}};var qe=s=>{let e=s?.header??"x-forwarded-for",t=s?.trust??!0,r=s?.hop??"first";return async(o,n,a)=>{if(!t)return a();let p=o.headers.get(e);if(p&&typeof p=="string"){let d=p.split(",").map(i=>i.trim()).filter(Boolean);d.length&&(o.ip=r==="first"?d[0]:d[d.length-1])}return a()}};var Le=s=>{let e={limit:1048576,extended:!1,charset:"utf8",allowEmpty:!0,parameterLimit:1e3,...s};return async(t,r,o)=>{if(!(t.headers.get("content-type")||"").includes("application/x-www-form-urlencoded"))return o();try{await tr(t,e),await o()}catch(a){if(a instanceof Error&&a.message.includes("limit")){r.status(413).json({error:"Payload too large",message:"Request body exceeds the size limit"});return}throw a}}};async function tr(s,e){let t=s.rawBody;if(t.byteLength>e.limit)throw new Error(`Body size ${t.byteLength} exceeds limit ${e.limit}`);let o=new TextDecoder(e.charset).decode(t),n=rr(o,e);s.body=n}function rr(s,e){let t={},r=new URLSearchParams(s);if(r.size>e.parameterLimit)throw new Error(`Too many parameters: ${r.size} exceeds limit ${e.parameterLimit}`);for(let[o,n]of r.entries())!e.allowEmpty&&n===""||(e.extended?sr(t,o,n):t[o]=n);return t}function sr(s,e,t){let r=e.match(/\[([^\]]*)\]/g);if(!r){s[e]=t;return}let o=s,n=e.split("[")[0];for(let p=0;p<r.length-1;p++){let d=r[p].slice(1,-1);if(o[n]||(o[n]={}),d===""){Array.isArray(o[n])||(o[n]=[]),o=o[n];continue}o[n][d]||(o[n][d]={}),o=o[n][d]}let a=r[r.length-1].slice(1,-1);if(a===""){Array.isArray(o)||(o=[]),o.push(t);return}o[a]=t}var yt=()=>async(s,e,t)=>(I(s.method)&&(s.rawBody=await s.arrayBuffer(),Object.defineProperty(s,"body",{value:void 0,writable:!0,configurable:!0,enumerable:!0})),t());var ze=s=>{let e={origin:"*",methods:["GET","HEAD","PUT","PATCH","POST","DELETE"],allowedHeaders:"",exposedHeaders:"",credentials:!1,maxAge:void 0,preflightContinue:!1,optionsSuccessStatus:204,...s};return async(t,r,o)=>{let n=t.headers.get("origin")||"";if(t.method==="OPTIONS")return or(t,r,e,n,o);nr(t,r,e,n),await o()}};function or(s,e,t,r,o){let n=vt(t,r);if(!n){e.forbidden("CORS origin not allowed");return}if(wt(e,t,n),t.preflightContinue){o();return}e.status(t.optionsSuccessStatus||204),e.send("")}function nr(s,e,t,r){let o=vt(t,r);o&&wt(e,t,o)}function vt(s,e){if(typeof s.origin=="string")return s.origin;if(Array.isArray(s.origin)){let t=s.origin.find(r=>typeof r=="string"?r===e:r instanceof RegExp&&r.test(e));return typeof t=="string"?t:!1}return"*"}function wt(s,e,t){if(s.setHeader("Access-Control-Allow-Origin",t),e.credentials&&s.setHeader("Access-Control-Allow-Credentials","true"),e.exposedHeaders&&e.exposedHeaders!==""){let o=Array.isArray(e.exposedHeaders)?e.exposedHeaders.join(","):e.exposedHeaders;s.setHeader("Access-Control-Expose-Headers",o)}if(e.allowedHeaders&&e.allowedHeaders!==""){let o=Array.isArray(e.allowedHeaders)?e.allowedHeaders.join(","):e.allowedHeaders;s.setHeader("Access-Control-Allow-Headers",o)}let r=Array.isArray(e.methods)?e.methods.join(","):e.methods;s.setHeader("Access-Control-Allow-Methods",String(r||"")),typeof e.maxAge=="number"&&s.setHeader("Access-Control-Max-Age",e.maxAge.toString())}var Rt=require("os"),Se=require("path");var we=class extends C{constructor(e,t,r){super(`FILE_TOO_LARGE: "${e}" is too large. Max size is ${r} bytes, but got ${t} bytes`)}};var Ve=s=>async(e,t,r)=>{let o=[];try{let n=e.headers.get("content-type")??e.headers.get("Content-Type");if(!n||!n.startsWith("multipart/form-data")||!e.rawBody)return r();let a=n.match(/boundary=(.*)(;|$)/i);if(!a)return r();let p=a[1].replace(/(^\s*"?|"?\s*$)/g,""),d=new Uint8Array(e.rawBody),i=new TextEncoder().encode(`--${p}`),c=new Uint8Array([13,10,13,10]),u=[],m=(R,E,W=0)=>{e:for(let A=W;A<=R.length-E.length;A++){for(let $=0;$<E.length;$++)if(R[A+$]!==E[$])continue e;return A}return-1},g=m(d,i);for(;g!==-1&&(g+=i.length,!(d[g]===45&&d[g+1]===45));){d[g]===13&&d[g+1]===10&&(g+=2);let R=m(d,c,g);if(R===-1)break;let E=d.subarray(g,R),W=new TextDecoder().decode(E),A=R+c.length,$=m(d,i,A);if($===-1)break;let F=$-1;d[F]===10&&F--,d[F]===13&&F--;let Qe=d.subarray(A,F+1);u.push({headers:W,data:Qe}),g=$}let f=[],S={};for(let R of u){let E=R.headers.split(`\r
57
- `).find(ie=>ie.toLowerCase().startsWith("content-disposition:"));if(!E)continue;let W=E.match(/name="([^"]+)"/);if(!W)continue;let A=W[1],$=E.match(/filename="([^"]*)"/),F=$?$[1]:"";if(!!F){if(s?.maxFileSize&&R.data.length>s.maxFileSize)return t.badRequest({...w(new we(F,R.data.length,s.maxFileSize))});let ie=R.headers.split(`\r
58
- `).find(Pt=>Pt.toLowerCase().startsWith("content-type:")),Et=ie?ie.split(":")[1].trim():"application/octet-stream",$t=(0,Se.extname)(F),Te=(0,Se.join)((0,Rt.tmpdir)(),`${ir(10)}${$t}`);await b.writeFile(Te,R.data),o.push(Te),f.push({formName:A,mimeType:Et,size:R.data.length,tmpPath:Te,originalName:F})}else S[A]=new TextDecoder().decode(R.data)}e.files=f,e.body=S,await r(),await St(o)}catch(n){throw await St(o),n}};async function St(s){await Promise.allSettled(s.map(e=>b.unlink(e)))}function ir(s){return Math.random().toString(36).substring(2,2+s)}var Ge=s=>{let e={dnsPrefetchControl:!0,frameguard:{action:"SAMEORIGIN"},hsts:{maxAge:15552e3,includeSubDomains:!0,preload:!1},contentTypeOptions:!0,ieNoOpen:!0,xssFilter:!0,referrerPolicy:"no-referrer",crossOriginResourcePolicy:"same-origin",crossOriginOpenerPolicy:"same-origin",crossOriginEmbedderPolicy:"require-corp",contentSecurityPolicy:!1,...s};return async(t,r,o)=>{if(e.dnsPrefetchControl&&r.setHeader("X-DNS-Prefetch-Control","off"),e.frameguard){let n="SAMEORIGIN";typeof e.frameguard=="object"&&(n=e.frameguard.action),r.setHeader("X-Frame-Options",n)}if(e.hsts){let n={};typeof e.hsts=="object"&&(n=e.hsts);let a=n.maxAge!==void 0?n.maxAge:15552e3,p=n.includeSubDomains!==void 0?n.includeSubDomains:!0,d=n.preload!==void 0?n.preload:!1,i=`max-age=${a}`;p!==!1&&(i+="; includeSubDomains"),d&&(i+="; preload"),r.setHeader("Strict-Transport-Security",i)}e.contentTypeOptions&&r.setHeader("X-Content-Type-Options","nosniff"),e.ieNoOpen&&r.setHeader("X-Download-Options","noopen"),e.xssFilter&&r.setHeader("X-XSS-Protection","0"),e.referrerPolicy&&r.setHeader("Referrer-Policy",e.referrerPolicy),e.crossOriginResourcePolicy&&r.setHeader("Cross-Origin-Resource-Policy",e.crossOriginResourcePolicy),e.crossOriginOpenerPolicy&&r.setHeader("Cross-Origin-Opener-Policy",e.crossOriginOpenerPolicy),e.crossOriginEmbedderPolicy&&r.setHeader("Cross-Origin-Embedder-Policy",e.crossOriginEmbedderPolicy),e.contentSecurityPolicy&&r.setHeader("Content-Security-Policy",e.contentSecurityPolicy),await o()}};var se=class extends C{constructor(e){super(`JSON_NOT_VALID: "${JSON.stringify(e)}" is not a valid JSON`)}};var Je=s=>async(e,t,r)=>{if(!ar(e)||!I(e.method))return r();let o=s?.sizeLimit??5*1024*1024,n=e.rawBody;if(!n)return s?.parseEmptyBodyAsObject&&(e.body={}),r();let a=n.byteLength;if(!a)return s?.parseEmptyBodyAsObject&&(e.body={}),r();if(a>o){let p={status:413,message:"ERR_REQUEST_BODY_TOO_LARGE",...s?.customErrorMessage};return t.status(p.status).json({error:p.message})}try{let p=s?.encoding??"utf-8",d=new TextDecoder(p).decode(n);e.body=JSON.parse(d)}catch(p){return p instanceof SyntaxError?t.badRequest({...w(new se("Invalid JSON syntax"))}):t.badRequest({...w(new se("Invalid request body encoding"))})}await r()};function ar(s){let e=dr(s);return e?pr(e)==="application/json":!1}function dr(s){let e=s.headers.get("content-type")??s.headers.get("Content-Type");return e?Array.isArray(e)?e[0]||null:e:null}function pr(s){let e=s.trim(),t=e.indexOf(";");return t===-1?e.toLowerCase():e.substring(0,t).trim().toLowerCase()}var xt=s=>{let e={type:"standard",path:"/docs",title:"Balda API Documentation",description:"API Documentation from the Balda Framework",version:"1.0.0",servers:["http://localhost"],security:[],tags:[],components:{},securitySchemes:{},models:{}};typeof s!="boolean"&&(e={...e,...s});let t=cr(e),r=`${e.path}`,o=`${r}/json`,n=e.type==="redoc"?lr(o,e):e.type==="rapidoc"?mr(o,e):ur(o,e);h.addOrUpdate("GET",r,[],(a,p)=>{p.html(n)}),h.addOrUpdate("GET",o,[],(a,p)=>{p.json(t)})};function cr(s){let e=h.getRoutes(),t={},r={...s.components,securitySchemes:s.securitySchemes||{},schemas:s.models?{...s.components?.schemas||{},...s.models}:s.components?.schemas?{...s.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(),p={summary:n?.name||`${a.toUpperCase()} ${o.path}`,description:n?.description||"",tags:n?.service?[n.service]:[],deprecated:n?.deprecated||!1},d=[];if(n?.query&&n.query.type==="object"&&n.query.properties)for(let[i,c]of Object.entries(n.query.properties))d.push({name:i,in:"query",required:Array.isArray(n.query.required)?n.query.required.includes(i):!1,schema:oe(c)});if(n&&n.params?d=d.concat(bt(o.path,n.params)):d=d.concat(bt(o.path)),d.length>0&&(p.parameters=d),n?.requestBody){let i="application/json";n.bodyType==="form-data"?i="multipart/form-data":n.bodyType==="urlencoded"&&(i="application/x-www-form-urlencoded"),p.requestBody={content:{[i]:{schema:oe(n.requestBody)}},required:!0}}else n?.bodyType&&(n.bodyType.includes("form-data")||n.bodyType.includes("urlencoded"))&&(p.requestBody={content:{[n.bodyType]:{schema:{type:"object"}}},required:!0});if(p.responses={},n?.responses)for(let[i,c]of Object.entries(n.responses))p.responses[i]={description:`Response for ${i}`,content:{"application/json":{schema:oe(c)}}};if(n?.errors)for(let[i,c]of Object.entries(n.errors))p.responses[i]={description:`Error response for ${i}`,content:{"application/json":{schema:oe(c)}}};if(Object.keys(p.responses).length===0&&(p.responses[200]={description:"Successful response",content:{"application/json":{schema:{type:"object"}}}}),n?.security){let i=[];Array.isArray(n.security)||(n.security=[n.security]);for(let c of n.security)if(c.type==="bearer")r.securitySchemes.bearer||(r.securitySchemes.bearer={type:"http",scheme:"bearer",bearerFormat:c.bearerFormat||"JWT",description:c.description}),i.push({bearer:[]});else if(c.type==="apiKey")r.securitySchemes[c.name]||(r.securitySchemes[c.name]={type:"apiKey",name:c.name,in:c.in,description:c.description}),i.push({[c.name]:[]});else if(c.type==="oauth2"){let u=c.name||"oauth2";r.securitySchemes[u]||(r.securitySchemes[u]={type:"oauth2",flows:c.flows,description:c.description}),i.push({[u]:[]})}else if(c.type==="openIdConnect"){let u=c.name||"openIdConnect";r.securitySchemes[u]||(r.securitySchemes[u]={type:"openIdConnect",openIdConnectUrl:c.openIdConnectUrl,description:c.description}),i.push({[u]:[]})}i.length&&(p.security=i)}else s.security&&(p.security=s.security);t[o.path][a]=p}return{openapi:"3.0.0",info:{title:s.title,description:s.description,version:s.version,...s.info},servers:s.servers?.map(o=>({url:o}))||[{url:"/"}],paths:t,components:r,security:s.security||[],tags:s.tags?Object.entries(s.tags).map(([o,n])=>({name:o,...n})):[]}}function ur(s,e){return`
56
+ `));let n=o.reduce((d,i)=>d+i.byteLength,0),a=new Uint8Array(n),p=0;for(let d of o)a.set(d,p),p+=d.byteLength;return a}validateOptions(e){let{body:t,formData:r,urlencoded:o}=e;if(t&&(r||o))throw new Error("Only one of body, formData, urlencoded can be provided");if(r&&(o||t))throw new Error("Only one of formData, urlencoded can be provided");if(o&&(t||r))throw new Error("Only one of urlencoded, body can be provided")}};var Ne=s=>{let e={secret:s?.secret??"",defaults:{path:"/",httpOnly:!0,secure:!1,sameSite:"Lax",...s?.defaults},parse:s?.parse??!0,sign:s?.sign??!1};return async(t,r,o)=>{if(e.parse){let n=Qt(t.headers.get("cookie")||"");t.cookies={};for(let[a,p]of Object.entries(n)){if(e.sign&&e.secret){let d=await er(p,e.secret);d!==!1&&(t.cookies[a]=d);continue}t.cookies[a]=p}}r.cookie=(n,a,p)=>{ft(r,n,a,{...e.defaults,...p},e)},r.clearCookie=(n,a)=>{Zt(r,n,{...e.defaults,...a})},await o()}};function Qt(s){let e={};if(!s)return e;let t=s.split(";");for(let r of t){let[o,n]=r.trim().split("=");o&&n&&(e[decodeURIComponent(o)]=decodeURIComponent(n))}return e}async function ft(s,e,t,r,o){let n=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;r.domain&&(n+=`; Domain=${r.domain}`),r.path&&(n+=`; Path=${r.path}`),r.expires&&(n+=`; Expires=${r.expires.toUTCString()}`),r.maxAge&&(n+=`; Max-Age=${r.maxAge}`),r.secure&&(n+="; Secure"),r.httpOnly&&(n+="; HttpOnly"),r.sameSite&&(n+=`; SameSite=${r.sameSite}`),r.priority&&(n+=`; Priority=${r.priority}`),o.sign&&o.secret&&(n=await Kt(n,o.secret));let a=s.headers["set-cookie"]||"",p=a?`${a}, ${n}`:n;s.setHeader("Set-Cookie",p)}function Zt(s,e,t){let r={...t,expires:new Date(0),maxAge:0};ft(s,e,"",r,{secret:"",defaults:{},parse:!0,sign:!1})}async function Kt(s,e){let t=new TextEncoder,r=t.encode(e),o=t.encode(s),n=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=await crypto.subtle.sign("HMAC",n,o),p=new Uint8Array(a),d=Array.from(p).map(i=>i.toString(16).padStart(2,"0")).join("");return`${s}.${d}`}async function er(s,e){let t=s.split(".");if(t.length!==2)return!1;let[r,o]=t,n=new TextEncoder,a=n.encode(e),p=n.encode(r),d=await crypto.subtle.importKey("raw",a,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=await crypto.subtle.sign("HMAC",d,p),c=new Uint8Array(i),u=Array.from(c).map(m=>m.toString(16).padStart(2,"0")).join("");return o===u?r:!1}var De=s=>async(e,t,r)=>{try{let o=e.body;(s?.logRequest??!0)&&v.info({type:"request",requestId:e.id,method:s?.requestPayload?.method??!0?e.method:void 0,url:s?.requestPayload?.url??!0?e.url:void 0,ip:s?.requestPayload?.ip??!0?e.ip:void 0,headers:s?.requestPayload?.headers??!0?e.headers:void 0,body:s?.requestPayload?.body??!1?ht(o):void 0}),await r(),(s?.logResponse??!0)&&v.info({type:"response",requestId:e.id,status:s?.responsePayload?.status??t.responseStatus,body:s?.responsePayload?.body??!1?ht(t.getBody()):void 0,headers:s?.responsePayload?.headers??!1?t.headers:void 0})}catch(o){throw v.error(o),o}};function ht(s){if(typeof s=="string"||s&&typeof s=="object"&&s.constructor===Object)return s}var ye=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 Ie=(s,e)=>{let t={type:"ip",limit:100,message:"ERR_RATE_LIMIT_EXCEEDED",statusCode:429,...s},r={type:"memory",...e};r.type==="memory"&&!r.windowMs&&(r.windowMs=6e4);let o=r.type==="memory"?new ye(r.windowMs):{get:r.get,set:r.set};return async(n,a,p)=>{let d=t.type==="ip"?n.ip:t.key(n),i=await o.get(d);return i>=t.limit?a.status(t.statusCode).json({message:t.message}):(await o.set(d,i+1),p())}};var gt=require("crypto");var ve=class{store=new Map;async get(e){let t=this.store.get(e);if(t){if(t.exp&&Date.now()>t.exp){this.store.delete(e);return}return t.value}}async set(e,t,r){let o=r?Date.now()+r*1e3:void 0;this.store.set(e,{value:t,exp:o})}async destroy(e){this.store.delete(e)}};var qe=s=>{let e=s?.name??"sid",t=s?.ttl??60*60*24,r=s?.store??new ve,o={path:"/",httpOnly:!0,secure:!1,sameSite:"Lax",...s?.cookie??{}};return async(n,a,p)=>{let i=n.cookies&&n.cookies[e],c=i?await r.get(i):void 0;(!i||!c)&&(i||=(0,gt.randomUUID)(),c||={},await r.set(i,c,t),a.cookie?.(e,i,o)),n.session=c,n.saveSession=async()=>r.set(i,c,t),n.destroySession=async()=>{await r.destroy(i),a.clearCookie?.(e,o)},await p(),await r.set(i,c,t)}};var Be=s=>async(e,t,r)=>{e.timeout=!1;let o=setTimeout(()=>{e.timeout=!0},s.ms);try{await r()}finally{clearTimeout(o)}};var Ue=s=>{let e=s?.header??"x-forwarded-for",t=s?.trust??!0,r=s?.hop??"first";return async(o,n,a)=>{if(!t)return a();let p=o.headers.get(e);if(p&&typeof p=="string"){let d=p.split(",").map(i=>i.trim()).filter(Boolean);d.length&&(o.ip=r==="first"?d[0]:d[d.length-1])}return a()}};var Le=s=>{let e={limit:1048576,extended:!1,charset:"utf8",allowEmpty:!0,parameterLimit:1e3,...s};return async(t,r,o)=>{if(!(t.headers.get("content-type")||"").includes("application/x-www-form-urlencoded"))return o();try{await tr(t,e),await o()}catch(a){if(a instanceof Error&&a.message.includes("limit")){r.status(413).json({error:"Payload too large",message:"Request body exceeds the size limit"});return}throw a}}};async function tr(s,e){let t=s.rawBody;if(t.byteLength>e.limit)throw new Error(`Body size ${t.byteLength} exceeds limit ${e.limit}`);let o=new TextDecoder(e.charset).decode(t),n=rr(o,e);s.body=n}function rr(s,e){let t={},r=new URLSearchParams(s);if(r.size>e.parameterLimit)throw new Error(`Too many parameters: ${r.size} exceeds limit ${e.parameterLimit}`);for(let[o,n]of r.entries())!e.allowEmpty&&n===""||(e.extended?sr(t,o,n):t[o]=n);return t}function sr(s,e,t){let r=e.match(/\[([^\]]*)\]/g);if(!r){s[e]=t;return}let o=s,n=e.split("[")[0];for(let p=0;p<r.length-1;p++){let d=r[p].slice(1,-1);if(o[n]||(o[n]={}),d===""){Array.isArray(o[n])||(o[n]=[]),o=o[n];continue}o[n][d]||(o[n][d]={}),o=o[n][d]}let a=r[r.length-1].slice(1,-1);if(a===""){Array.isArray(o)||(o=[]),o.push(t);return}o[a]=t}var se=class{get(e){switch(y.type){case"node":return process.env[e]??"";case"bun":return Bun.env[e]??"";case"deno":return Deno.env.get(e)??"";default:throw new Error(`Unsupported runtime: ${y.type}`)}}};var yt=()=>async(s,e,t)=>(I(s.method)&&(s.rawBody=await s.arrayBuffer(),Object.defineProperty(s,"body",{value:void 0,writable:!0,configurable:!0,enumerable:!0})),t());var ze=s=>{let e={origin:"*",methods:["GET","HEAD","PUT","PATCH","POST","DELETE"],allowedHeaders:"",exposedHeaders:"",credentials:!1,maxAge:void 0,preflightContinue:!1,optionsSuccessStatus:204,...s};return async(t,r,o)=>{let n=t.headers.get("origin")||"";if(t.method==="OPTIONS")return or(t,r,e,n,o);nr(t,r,e,n),await o()}};function or(s,e,t,r,o){let n=vt(t,r);if(!n){e.forbidden("CORS origin not allowed");return}if(wt(e,t,n),t.preflightContinue){o();return}e.status(t.optionsSuccessStatus||204),e.send("")}function nr(s,e,t,r){let o=vt(t,r);o&&wt(e,t,o)}function vt(s,e){if(typeof s.origin=="string")return s.origin;if(Array.isArray(s.origin)){let t=s.origin.find(r=>typeof r=="string"?r===e:r instanceof RegExp&&r.test(e));return typeof t=="string"?t:!1}return"*"}function wt(s,e,t){if(s.setHeader("Access-Control-Allow-Origin",t),e.credentials&&s.setHeader("Access-Control-Allow-Credentials","true"),e.exposedHeaders&&e.exposedHeaders!==""){let o=Array.isArray(e.exposedHeaders)?e.exposedHeaders.join(","):e.exposedHeaders;s.setHeader("Access-Control-Expose-Headers",o)}if(e.allowedHeaders&&e.allowedHeaders!==""){let o=Array.isArray(e.allowedHeaders)?e.allowedHeaders.join(","):e.allowedHeaders;s.setHeader("Access-Control-Allow-Headers",o)}let r=Array.isArray(e.methods)?e.methods.join(","):e.methods;s.setHeader("Access-Control-Allow-Methods",String(r||"")),typeof e.maxAge=="number"&&s.setHeader("Access-Control-Max-Age",e.maxAge.toString())}var Rt=require("os"),Se=require("path");var we=class extends C{constructor(e,t,r){super(`FILE_TOO_LARGE: "${e}" is too large. Max size is ${r} bytes, but got ${t} bytes`)}};var Ve=s=>async(e,t,r)=>{let o=[];try{let n=e.headers.get("content-type")??e.headers.get("Content-Type");if(!n||!n.startsWith("multipart/form-data")||!e.rawBody)return r();let a=n.match(/boundary=(.*)(;|$)/i);if(!a)return r();let p=a[1].replace(/(^\s*"?|"?\s*$)/g,""),d=new Uint8Array(e.rawBody),i=new TextEncoder().encode(`--${p}`),c=new Uint8Array([13,10,13,10]),u=[],m=(S,P,W=0)=>{e:for(let A=W;A<=S.length-P.length;A++){for(let E=0;E<P.length;E++)if(S[A+E]!==P[E])continue e;return A}return-1},h=m(d,i);for(;h!==-1&&(h+=i.length,!(d[h]===45&&d[h+1]===45));){d[h]===13&&d[h+1]===10&&(h+=2);let S=m(d,c,h);if(S===-1)break;let P=d.subarray(h,S),W=new TextDecoder().decode(P),A=S+c.length,E=m(d,i,A);if(E===-1)break;let H=E-1;d[H]===10&&H--,d[H]===13&&H--;let Qe=d.subarray(A,H+1);u.push({headers:W,data:Qe}),h=E}let f=[],w={};for(let S of u){let P=S.headers.split(`\r
57
+ `).find(ie=>ie.toLowerCase().startsWith("content-disposition:"));if(!P)continue;let W=P.match(/name="([^"]+)"/);if(!W)continue;let A=W[1],E=P.match(/filename="([^"]*)"/),H=E?E[1]:"";if(!!H){if(s?.maxFileSize&&S.data.length>s.maxFileSize)return t.badRequest({...b(new we(H,S.data.length,s.maxFileSize))});let ie=S.headers.split(`\r
58
+ `).find($t=>$t.toLowerCase().startsWith("content-type:")),Pt=ie?ie.split(":")[1].trim():"application/octet-stream",Et=(0,Se.extname)(H),Te=(0,Se.join)((0,Rt.tmpdir)(),`${ir(10)}${Et}`);await R.writeFile(Te,S.data),o.push(Te),f.push({formName:A,mimeType:Pt,size:S.data.length,tmpPath:Te,originalName:H})}else w[A]=new TextDecoder().decode(S.data)}e.files=f,e.body=w,await r(),await St(o)}catch(n){throw await St(o),n}};async function St(s){await Promise.allSettled(s.map(e=>R.unlink(e)))}function ir(s){return Math.random().toString(36).substring(2,2+s)}var Ge=s=>{let e={dnsPrefetchControl:!0,frameguard:{action:"SAMEORIGIN"},hsts:{maxAge:15552e3,includeSubDomains:!0,preload:!1},contentTypeOptions:!0,ieNoOpen:!0,xssFilter:!0,referrerPolicy:"no-referrer",crossOriginResourcePolicy:"same-origin",crossOriginOpenerPolicy:"same-origin",crossOriginEmbedderPolicy:"require-corp",contentSecurityPolicy:!1,...s};return async(t,r,o)=>{if(e.dnsPrefetchControl&&r.setHeader("X-DNS-Prefetch-Control","off"),e.frameguard){let n="SAMEORIGIN";typeof e.frameguard=="object"&&(n=e.frameguard.action),r.setHeader("X-Frame-Options",n)}if(e.hsts){let n={};typeof e.hsts=="object"&&(n=e.hsts);let a=n.maxAge!==void 0?n.maxAge:15552e3,p=n.includeSubDomains!==void 0?n.includeSubDomains:!0,d=n.preload!==void 0?n.preload:!1,i=`max-age=${a}`;p!==!1&&(i+="; includeSubDomains"),d&&(i+="; preload"),r.setHeader("Strict-Transport-Security",i)}e.contentTypeOptions&&r.setHeader("X-Content-Type-Options","nosniff"),e.ieNoOpen&&r.setHeader("X-Download-Options","noopen"),e.xssFilter&&r.setHeader("X-XSS-Protection","0"),e.referrerPolicy&&r.setHeader("Referrer-Policy",e.referrerPolicy),e.crossOriginResourcePolicy&&r.setHeader("Cross-Origin-Resource-Policy",e.crossOriginResourcePolicy),e.crossOriginOpenerPolicy&&r.setHeader("Cross-Origin-Opener-Policy",e.crossOriginOpenerPolicy),e.crossOriginEmbedderPolicy&&r.setHeader("Cross-Origin-Embedder-Policy",e.crossOriginEmbedderPolicy),e.contentSecurityPolicy&&r.setHeader("Content-Security-Policy",e.contentSecurityPolicy),await o()}};var oe=class extends C{constructor(e){super(`JSON_NOT_VALID: "${JSON.stringify(e)}" is not a valid JSON`)}};var Je=s=>async(e,t,r)=>{if(!ar(e)||!I(e.method))return r();let o=s?.sizeLimit??5*1024*1024,n=e.rawBody;if(!n)return s?.parseEmptyBodyAsObject&&(e.body={}),r();let a=n.byteLength;if(!a)return s?.parseEmptyBodyAsObject&&(e.body={}),r();if(a>o){let p={status:413,message:"ERR_REQUEST_BODY_TOO_LARGE",...s?.customErrorMessage};return t.status(p.status).json({error:p.message})}try{let p=s?.encoding??"utf-8",d=new TextDecoder(p).decode(n);e.body=JSON.parse(d)}catch(p){return p instanceof SyntaxError?t.badRequest({...b(new oe("Invalid JSON syntax"))}):t.badRequest({...b(new oe("Invalid request body encoding"))})}await r()};function ar(s){let e=dr(s);return e?pr(e)==="application/json":!1}function dr(s){let e=s.headers.get("content-type")??s.headers.get("Content-Type");return e?Array.isArray(e)?e[0]||null:e:null}function pr(s){let e=s.trim(),t=e.indexOf(";");return t===-1?e.toLowerCase():e.substring(0,t).trim().toLowerCase()}var xt=s=>{let e={type:"standard",path:"/docs",title:"Balda API Documentation",description:"API Documentation from the Balda Framework",version:"1.0.0",servers:["http://localhost"],security:[],tags:[],components:{},securitySchemes:{},models:{}};typeof s!="boolean"&&(e={...e,...s});let t=cr(e),r=`${e.path}`,o=`${r}/json`,n=e.type==="redoc"?lr(o,e):e.type==="rapidoc"?mr(o,e):ur(o,e);g.addOrUpdate("GET",r,[],(a,p)=>{p.html(n)}),g.addOrUpdate("GET",o,[],(a,p)=>{p.json(t)})};function cr(s){let e=g.getRoutes(),t={},r={...s.components,securitySchemes:s.securitySchemes||{},schemas:s.models?{...s.components?.schemas||{},...s.models}:s.components?.schemas?{...s.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(),p={summary:n?.name||`${a.toUpperCase()} ${o.path}`,description:n?.description||"",tags:n?.service?[n.service]:[],deprecated:n?.deprecated||!1},d=[];if(n?.query&&n.query.type==="object"&&n.query.properties)for(let[i,c]of Object.entries(n.query.properties))d.push({name:i,in:"query",required:Array.isArray(n.query.required)?n.query.required.includes(i):!1,schema:ne(c)});if(n&&n.params?d=d.concat(bt(o.path,n.params)):d=d.concat(bt(o.path)),d.length>0&&(p.parameters=d),n?.requestBody){let i="application/json";n.bodyType==="form-data"?i="multipart/form-data":n.bodyType==="urlencoded"&&(i="application/x-www-form-urlencoded"),p.requestBody={content:{[i]:{schema:ne(n.requestBody)}},required:!0}}else n?.bodyType&&(n.bodyType.includes("form-data")||n.bodyType.includes("urlencoded"))&&(p.requestBody={content:{[n.bodyType]:{schema:{type:"object"}}},required:!0});if(p.responses={},n?.responses)for(let[i,c]of Object.entries(n.responses))p.responses[i]={description:`Response for ${i}`,content:{"application/json":{schema:ne(c)}}};if(n?.errors)for(let[i,c]of Object.entries(n.errors))p.responses[i]={description:`Error response for ${i}`,content:{"application/json":{schema:ne(c)}}};if(Object.keys(p.responses).length===0&&(p.responses[200]={description:"Successful response",content:{"application/json":{schema:{type:"object"}}}}),n?.security){let i=[];Array.isArray(n.security)||(n.security=[n.security]);for(let c of n.security)if(c.type==="bearer")r.securitySchemes.bearer||(r.securitySchemes.bearer={type:"http",scheme:"bearer",bearerFormat:c.bearerFormat||"JWT",description:c.description}),i.push({bearer:[]});else if(c.type==="apiKey")r.securitySchemes[c.name]||(r.securitySchemes[c.name]={type:"apiKey",name:c.name,in:c.in,description:c.description}),i.push({[c.name]:[]});else if(c.type==="oauth2"){let u=c.name||"oauth2";r.securitySchemes[u]||(r.securitySchemes[u]={type:"oauth2",flows:c.flows,description:c.description}),i.push({[u]:[]})}else if(c.type==="openIdConnect"){let u=c.name||"openIdConnect";r.securitySchemes[u]||(r.securitySchemes[u]={type:"openIdConnect",openIdConnectUrl:c.openIdConnectUrl,description:c.description}),i.push({[u]:[]})}i.length&&(p.security=i)}else s.security&&(p.security=s.security);t[o.path][a]=p}return{openapi:"3.0.0",info:{title:s.title,description:s.description,version:s.version,...s.info},servers:s.servers?.map(o=>({url:o}))||[{url:"/"}],paths:t,components:r,security:s.security||[],tags:s.tags?Object.entries(s.tags).map(([o,n])=>({name:o,...n})):[]}}function ur(s,e){return`
59
59
  <!DOCTYPE html>
60
60
  <html lang="en">
61
61
  <head>
@@ -152,5 +152,5 @@ ${u}\r
152
152
  <script type="module" src="https://unpkg.com/rapidoc/dist/rapidoc-min.js"></script>
153
153
  </body>
154
154
  </html>
155
- `}function oe(s){if(!s)return;let{$id:e,$schema:t,...r}=s;return r}function bt(s,e){let t=[],r=/:([a-zA-Z0-9_]+)/g,o;for(;(o=r.exec(s))!==null;){let n=o[1],a={type:"string"};e&&e.type==="object"&&e.properties&&e.properties[n]&&(a=oe(e.properties[n])||{type:"string"}),t.push({name:n,in:"path",required:!0,schema:a})}return t}var Re=class{port;hostname;host;routes;tapOptions;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.hostname=e?.host??"0.0.0.0",this.host=e?.host??"0.0.0.0",this.tapOptions=e?.tapOptions}listen(){let e=this.tapOptions?.options,{fetch:t,...r}=e??{};this.runtimeServer=Bun.serve({port:this.port,hostname:this.hostname,fetch:async(o,n)=>{let a=new URL(o.url),p=h.find(o.method,a.pathname);M.enrichRequest(o),o.params=p?.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);let d=await D(p?.middleware??[],p?.handler??((c,u)=>{u.notFound({...w(new x(c.url,c.method))})}),o);return d.headers["Content-Type"]==="application/json"?Response.json(d.getBody(),{status:d.responseStatus,headers:d.headers}):new Response(d.getBody(),{status:d.responseStatus,headers:d.headers})},...r}),this.url=this.runtimeServer.url.toString()}async close(){if(!this.runtimeServer)throw new Error("Server is not listening or not initialized");await this.runtimeServer.stop()}};var be=class{constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.hostname=e?.host??"0.0.0.0",this.host=e?.host??"0.0.0.0",this.tapOptions=e?.tapOptions}listen(){let e=this.tapOptions?.options,{handler:t,...r}=e??{};this.runtimeServer=Deno.serve({port:this.port,hostname:this.hostname,handler:async(o,n)=>{let a=new URL(o.url),p=h.find(o.method,a.pathname);M.enrichRequest(o),o.params=p?.params??{},o.query=Object.fromEntries(a.searchParams.entries()),o.ip=o.headers.get("x-forwarded-for")?.split(",")[0]??n.remoteAddr?.hostname,await t?.(o,n);let d=await D(p?.middleware??[],p?.handler??((c,u)=>{u.notFound({...w(new x(c.url,c.method))})}),o);return d.headers["Content-Type"]==="application/json"?Response.json(d.getBody(),{status:d.responseStatus,headers:d.headers}):new Response(d.getBody(),{status:d.responseStatus,headers:d.headers})},...r}),this.url=`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 Ot=require("http");async function fr(s,e){let t=s.getReader();try{for(;;){let{done:r,value:o}=await t.read();if(r){e.end();break}e.write(o)}}catch(r){e.destroy(r)}}var xe=class{port;host;url;routes;tapOptions;runtimeServer;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.host=e?.host??"0.0.0.0",this.url=`http://${this.host}:${this.port}`,this.tapOptions=e?.tapOptions,this.runtimeServer=(0,Ot.createServer)(async(t,r)=>{if(this.tapOptions){let{options:u}=this.tapOptions;await u?.(t)}let o=h.find(t.method,t.url),n=new M(`${this.url}${t.url}`,{method:t.method,body:I(t.method)?await this.readRequestBody(t):void 0,headers:t.headers}),a=t.headers["x-forwarded-for"];Array.isArray(a)&&(a=a[0]),n.ip=a??t.socket.remoteAddress;let[p,d=""]=t.url?.split("?",2)??[];n.query=Object.fromEntries(new URLSearchParams(d)),n.params=o?.params??{};let i=await D(o?.middleware??[],o?.handler??((u,m)=>{m.notFound({...w(new x(u.url,u.method))})}),n),c=i.getBody();if(c instanceof ReadableStream){fr(c,r);return}c instanceof Buffer||c instanceof Uint8Array||typeof c=="string"?c=c:i.headers["Content-Type"]==="application/json"?c=JSON.stringify(c):c=String(c),r.writeHead(i.responseStatus,i.headers),r.end(c)})}listen(){this.runtimeServer.listen(this.port,this.host)}async close(){return new Promise((e,t)=>{this.runtimeServer.close(r=>{r&&"code"in r&&r.code!=="ERR_SERVER_NOT_RUNNING"?t(r):e()})})}async readRequestBody(e){return new Promise((t,r)=>{let o=[];e.on("data",n=>o.push(Buffer.from(n))),e.on("error",r),e.on("end",()=>t(Buffer.concat(o).toString()))})}};var Oe=class{server;constructor(e){this.server=this.getRuntimeServer(e),this.routes=this.server.routes}get url(){return this.server.url}get port(){return this.server.port}get host(){return this.server.host}getServer(e){return this.server.runtimeServer}listen(){return this.server.listen()}close(){return this.server.close()}getRuntimeServer(e){if(e?.runtime==="bun")return new Re(e);if(e?.runtime==="node")return new xe(e);if(e?.runtime==="deno")return new be(e);throw new Error("No server implementation found for runtime: "+e?.runtime)}};var Tt=["isListening","url","port","host","routes","embed","constructor","get","post","put","patch","delete","getNodeServer","getBunServer","getDenoServer","use","setErrorHandler","listen","close","tapOptions","startUpOptions","tmpDir","logger","getMockServer"];var ne=class{get(e){switch(y.type){case"node":return process.env[e]??"";case"bun":return Bun.env[e]??"";case"deno":return Deno.env.get(e)??"";default:throw new Error(`Unsupported runtime: ${y.type}`)}}};var Ye=class{isListening;router=h;wasInitialized;serverConnector;globalMiddlewares=[];serverOptions;controllerImportBlacklistedPaths=["node_modules"];constructor(e){this.wasInitialized=!1,this.serverOptions={port:e?.port??Number(new ne().get("PORT"))??80,host:e?.host??new ne().get("HOST")??"0.0.0.0",controllerPatterns:e?.controllerPatterns??[],plugins:e?.plugins??{},tapOptions:e?.tapOptions??{},swagger:e?.swagger??!0,useBodyParser:e?.useBodyParser??!0},this.serverConnector=new Oe({routes:[],port:this.serverOptions.port,host:this.serverOptions.host,tapOptions:this.serverOptions.tapOptions,runtime:y.type}),this.serverOptions.useBodyParser&&this.use(yt()),this.isListening=!1}get url(){return this.serverConnector.url}get port(){return this.serverConnector.port}get host(){return this.serverConnector.host}get routes(){return h.getRoutes()}tmpDir(...e){let t="tmp";return e?(0,We.join)(t,...e):(0,We.join)(k.getCwd(),t)}get(e,t,r){let{middlewares:o,handler:n,swaggerOptions:a}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);h.addOrUpdate("GET",e,o,n,a)}post(e,t,r){let{middlewares:o,handler:n,swaggerOptions:a}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);h.addOrUpdate("POST",e,o,n,a)}patch(e,t,r){let{middlewares:o,handler:n,swaggerOptions:a}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);h.addOrUpdate("PATCH",e,o,n,a)}put(e,t,r){let{middlewares:o,handler:n,swaggerOptions:a}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);h.addOrUpdate("PUT",e,o,n,a)}delete(e,t,r){let{middlewares:o,handler:n,swaggerOptions:a}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);h.addOrUpdate("DELETE",e,o,n,a)}options(e,t,r){let{middlewares:o,handler:n,swaggerOptions:a}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);h.addOrUpdate("OPTIONS",e,o,n,a)}group(e,t,r){this.router.group(e,t,r)}getNodeServer(){if(y.type!=="node")throw new Error("Server is not using node runtime, you can't call `.getNodeServer()`");return this.serverConnector.getServer("node")}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(Tt.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:!1,configurable:!0,enumerable:!0})}exit(e=0){switch(y.type){case"bun":case"node":process.exit(e);case"deno":Deno.exit(e);default:throw new Error(`Unsupported runtime: ${y.type}`)}}on(e,t){switch(y.type){case"bun":case"node":process.on(e,t);break;case"deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${y.type}, only node, bun and deno are supported`)}}once(e,t){switch(y.type){case"bun":case"node":process.once(e,t);break;case"deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${y.type}, only node, bun and deno are supported`)}}use(...e){this.globalMiddlewares.push(...e)}setErrorHandler(e){this.globalMiddlewares.unshift(async(t,r,o)=>{try{await o()}catch(n){await e?.(t,r,o,n)}})}setGlobalCronErrorHandler(e){K.globalErrorHandler=e}startRegisteredCrons=async(e,t)=>{e?.length&&await K.massiveImportCronJobs(e),K.run().then(()=>{t?.()})};listen(e){if(this.isListening)throw new Error("Server is already listening, you can't call `.listen()` multiple times");this.bootstrap().then(()=>{this.serverConnector.listen(),this.isListening=!0,this.serverOptions.swagger&&xt(this.serverOptions.swagger),e?.({port:this.port,host:this.host,url:this.url})})}async close(){await this.serverConnector.close(),this.isListening=!1}async getMockServer(){return await this.bootstrap(),new ge(this)}async importControllers(){let e=this.serverOptions.controllerPatterns,t=await Promise.all(e.map(async r=>(0,Ct.glob)(r,{absolute:!0,cwd:k.getCwd()}))).then(r=>r.flat());t=t.flat(),t=t.filter(r=>!this.controllerImportBlacklistedPaths.some(o=>r.includes(o))),v.debug(`Found ${t.length} controllers to import`),await Promise.all(t.map(async r=>{v.debug(`Importing controller ${r}`),await import(r).catch(o=>{v.error(`Error importing controller ${r}: ${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(ze(r));break;case"json":this.use(Je(r));break;case"static":this.use(je(r));break;case"fileParser":this.use(Ve(r));break;case"helmet":this.use(Ge(r));break;case"cookie":this.use(Ne(r));break;case"log":this.use(De(r));break;case"rateLimiter":let{keyOptions:o,storageOptions:n}=r;this.use(Ie(o,n));break;case"urlencoded":this.use(Le(r));break;case"trustProxy":this.use(qe(r));break;case"timeout":this.use(Be(r));break;case"session":this.use(Ue(r));break;default:v.warn(`Unknown plugin ${t}`);break}})}async bootstrap(){this.wasInitialized||(await this.importControllers(),this.applyPlugins(this.serverOptions.plugins),this.registerNotFoundRoutes(),this.globalMiddlewares.length&&h.applyGlobalMiddlewaresToAllRoutes(this.globalMiddlewares),this.wasInitialized=!0)}registerNotFoundRoutes(){h.addOrUpdate("GET","*",[],(e,t)=>{let r=new x(e.url,e.method);t.notFound({...w(r)})},{excludeFromSwagger:!0}),h.addOrUpdate("POST","*",[],(e,t)=>{let r=new x(e.url,e.method);t.notFound({...w(r)})},{excludeFromSwagger:!0}),h.addOrUpdate("PUT","*",[],(e,t)=>{let r=new x(e.url,e.method);t.notFound({...w(r)})},{excludeFromSwagger:!0}),h.addOrUpdate("PATCH","*",[],(e,t)=>{let r=new x(e.url,e.method);t.notFound({...w(r)})},{excludeFromSwagger:!0}),h.addOrUpdate("DELETE","*",[],(e,t)=>{let r=new x(e.url,e.method);t.notFound({...w(r)})},{excludeFromSwagger:!0})}};var Xe=class{};var hr=h;0&&(module.exports={ARG_SYMBOL,BasePlugin,Command,CommandRegistry,Request,Response,Server,VALIDATION_ERROR_SYMBOL,arg,commandRegistry,controller,cookie,cors,del,fileParser,flag,get,getContentType,helmet,json,log,middleware,patch,post,put,rateLimiter,router,serialize,serveStatic,session,timeout,trustProxy,urlencoded,validate});
155
+ `}function ne(s){if(!s)return;let{$id:e,$schema:t,...r}=s;return r}function bt(s,e){let t=[],r=/:([a-zA-Z0-9_]+)/g,o;for(;(o=r.exec(s))!==null;){let n=o[1],a={type:"string"};e&&e.type==="object"&&e.properties&&e.properties[n]&&(a=ne(e.properties[n])||{type:"string"}),t.push({name:n,in:"path",required:!0,schema:a})}return t}var Re=class{port;hostname;host;routes;tapOptions;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.hostname=e?.host??"0.0.0.0",this.host=e?.host??"0.0.0.0",this.tapOptions=e?.tapOptions}listen(){let e=this.tapOptions?.options,{fetch:t,...r}=e??{};this.runtimeServer=Bun.serve({port:this.port,hostname:this.hostname,fetch:async(o,n)=>{let a=new URL(o.url),p=g.find(o.method,a.pathname);M.enrichRequest(o),o.params=p?.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);let d=await D(p?.middleware??[],p?.handler??((c,u)=>{u.notFound({...b(new O(c.url,c.method))})}),o);return d.headers["Content-Type"]==="application/json"?Response.json(d.getBody(),{status:d.responseStatus,headers:d.headers}):new Response(d.getBody(),{status:d.responseStatus,headers:d.headers})},...r}),this.url=this.runtimeServer.url.toString()}async close(){if(!this.runtimeServer)throw new Error("Server is not listening or not initialized");await this.runtimeServer.stop()}};var be=class{constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.hostname=e?.host??"0.0.0.0",this.host=e?.host??"0.0.0.0",this.tapOptions=e?.tapOptions}listen(){let e=this.tapOptions?.options,{handler:t,...r}=e??{};this.runtimeServer=Deno.serve({port:this.port,hostname:this.hostname,handler:async(o,n)=>{let a=new URL(o.url),p=g.find(o.method,a.pathname);M.enrichRequest(o),o.params=p?.params??{},o.query=Object.fromEntries(a.searchParams.entries()),o.ip=o.headers.get("x-forwarded-for")?.split(",")[0]??n.remoteAddr?.hostname,await t?.(o,n);let d=await D(p?.middleware??[],p?.handler??((c,u)=>{u.notFound({...b(new O(c.url,c.method))})}),o);return d.headers["Content-Type"]==="application/json"?Response.json(d.getBody(),{status:d.responseStatus,headers:d.headers}):new Response(d.getBody(),{status:d.responseStatus,headers:d.headers})},...r}),this.url=`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 Ot=require("http");async function fr(s,e){let t=s.getReader();try{for(;;){let{done:r,value:o}=await t.read();if(r){e.end();break}e.write(o)}}catch(r){e.destroy(r)}}var xe=class{port;host;url;routes;tapOptions;runtimeServer;constructor(e){this.routes=e?.routes??[],this.port=e?.port??80,this.host=e?.host??"0.0.0.0",this.url=`http://${this.host}:${this.port}`,this.tapOptions=e?.tapOptions,this.runtimeServer=(0,Ot.createServer)(async(t,r)=>{if(this.tapOptions){let{options:u}=this.tapOptions;await u?.(t)}let o=g.find(t.method,t.url),n=new M(`${this.url}${t.url}`,{method:t.method,body:I(t.method)?await this.readRequestBody(t):void 0,headers:t.headers}),a=t.headers["x-forwarded-for"];Array.isArray(a)&&(a=a[0]),n.ip=a??t.socket.remoteAddress;let[p,d=""]=t.url?.split("?",2)??[];n.query=Object.fromEntries(new URLSearchParams(d)),n.params=o?.params??{};let i=await D(o?.middleware??[],o?.handler??((u,m)=>{m.notFound({...b(new O(u.url,u.method))})}),n),c=i.getBody();if(c instanceof ReadableStream){fr(c,r);return}c instanceof Buffer||c instanceof Uint8Array||typeof c=="string"?c=c:i.headers["Content-Type"]==="application/json"?c=JSON.stringify(c):c=String(c),r.writeHead(i.responseStatus,i.headers),r.end(c)})}listen(){this.runtimeServer.listen(this.port,this.host)}async close(){return new Promise((e,t)=>{this.runtimeServer.close(r=>{r&&"code"in r&&r.code!=="ERR_SERVER_NOT_RUNNING"?t(r):e()})})}async readRequestBody(e){return new Promise((t,r)=>{let o=[];e.on("data",n=>o.push(Buffer.from(n))),e.on("error",r),e.on("end",()=>t(Buffer.concat(o).toString()))})}};var Oe=class{server;constructor(e){this.server=this.getRuntimeServer(e),this.routes=this.server.routes}get url(){return this.server.url}get port(){return this.server.port}get host(){return this.server.host}getServer(e){return this.server.runtimeServer}listen(){return this.server.listen()}close(){return this.server.close()}getRuntimeServer(e){if(e?.runtime==="bun")return new Re(e);if(e?.runtime==="node")return new xe(e);if(e?.runtime==="deno")return new be(e);throw new Error("No server implementation found for runtime: "+e?.runtime)}};var Tt=["isListening","url","port","host","routes","embed","constructor","get","post","put","patch","delete","getNodeServer","getBunServer","getDenoServer","use","setErrorHandler","listen","close","tapOptions","startUpOptions","tmpDir","logger","getMockServer"];var Ye=class{isListening;router=g;wasInitialized;serverConnector;globalMiddlewares=[];serverOptions;controllerImportBlacklistedPaths=["node_modules"];notFoundHandler;constructor(e){this.wasInitialized=!1,this.serverOptions={port:e?.port??Number(new se().get("PORT"))??80,host:e?.host??new se().get("HOST")??"0.0.0.0",controllerPatterns:e?.controllerPatterns??[],plugins:e?.plugins??{},tapOptions:e?.tapOptions??{},swagger:e?.swagger??!0,useBodyParser:e?.useBodyParser??!0},this.serverConnector=new Oe({routes:[],port:this.serverOptions.port,host:this.serverOptions.host,tapOptions:this.serverOptions.tapOptions,runtime:y.type}),this.serverOptions.useBodyParser&&this.use(yt()),this.isListening=!1}get url(){return this.serverConnector.url}get port(){return this.serverConnector.port}get host(){return this.serverConnector.host}get routes(){return g.getRoutes()}tmpDir(...e){let t="tmp";return e?(0,We.join)(t,...e):(0,We.join)(k.getCwd(),t)}get(e,t,r){let{middlewares:o,handler:n,swaggerOptions:a}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);g.addOrUpdate("GET",e,o,n,a)}post(e,t,r){let{middlewares:o,handler:n,swaggerOptions:a}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);g.addOrUpdate("POST",e,o,n,a)}patch(e,t,r){let{middlewares:o,handler:n,swaggerOptions:a}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);g.addOrUpdate("PATCH",e,o,n,a)}put(e,t,r){let{middlewares:o,handler:n,swaggerOptions:a}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);g.addOrUpdate("PUT",e,o,n,a)}delete(e,t,r){let{middlewares:o,handler:n,swaggerOptions:a}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);g.addOrUpdate("DELETE",e,o,n,a)}options(e,t,r){let{middlewares:o,handler:n,swaggerOptions:a}=this.extractOptionsAndHandlerFromRouteRegistration(t,r);g.addOrUpdate("OPTIONS",e,o,n,a)}group(e,t,r){this.router.group(e,t,r)}getNodeServer(){if(y.type!=="node")throw new Error("Server is not using node runtime, you can't call `.getNodeServer()`");return this.serverConnector.getServer("node")}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(Tt.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:!1,configurable:!0,enumerable:!0})}exit(e=0){switch(y.type){case"bun":case"node":process.exit(e);case"deno":Deno.exit(e);default:throw new Error(`Unsupported runtime: ${y.type}`)}}on(e,t){switch(y.type){case"bun":case"node":process.on(e,t);break;case"deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${y.type}, only node, bun and deno are supported`)}}once(e,t){switch(y.type){case"bun":case"node":process.once(e,t);break;case"deno":Deno.addSignalListener(e,t);break;default:throw new Error(`Unsupported runtime: ${y.type}, only node, bun and deno are supported`)}}use(...e){this.globalMiddlewares.push(...e)}setErrorHandler(e){this.globalMiddlewares.unshift(async(t,r,o)=>{try{await o()}catch(n){await e?.(t,r,o,n)}})}setNotFoundHandler(e){this.notFoundHandler=e}setGlobalCronErrorHandler(e){K.globalErrorHandler=e}startRegisteredCrons=async(e,t)=>{e?.length&&await K.massiveImportCronJobs(e),K.run().then(()=>{t?.()})};listen(e){if(this.isListening)throw new Error("Server is already listening, you can't call `.listen()` multiple times");this.bootstrap().then(()=>{this.serverConnector.listen(),this.isListening=!0,this.serverOptions.swagger&&xt(this.serverOptions.swagger),e?.({port:this.port,host:this.host,url:this.url})})}async close(){await this.serverConnector.close(),this.isListening=!1}async getMockServer(e){return await this.bootstrap(e),new ge(this)}async importControllers(e){let t=e??this.serverOptions.controllerPatterns,r=await Promise.all(t.map(async o=>(0,Ct.glob)(o,{absolute:!0,cwd:k.getCwd()}))).then(o=>o.flat());r=r.flat(),r=r.filter(o=>!this.controllerImportBlacklistedPaths.some(n=>o.includes(n))),v.debug(`Found ${r.length} controllers to import`),await Promise.all(r.map(async o=>{v.debug(`Importing controller ${o}`),await import(o).catch(n=>{v.error(`Error importing controller ${o}: ${n}`)})}))}extractOptionsAndHandlerFromRouteRegistration(e,t){if(typeof e=="function")return{middlewares:[],handler:e,swaggerOptions:void 0};let r=e;return{middlewares:Array.isArray(r.middlewares)?r.middlewares:r.middlewares?[r.middlewares]:[],handler:t,swaggerOptions:r.swagger}}applyPlugins(e){Object.entries(e).forEach(([t,r])=>{switch(t){case"cors":this.use(ze(r));break;case"json":this.use(Je(r));break;case"static":this.use(je(r));break;case"fileParser":this.use(Ve(r));break;case"helmet":this.use(Ge(r));break;case"cookie":this.use(Ne(r));break;case"log":this.use(De(r));break;case"rateLimiter":let{keyOptions:o,storageOptions:n}=r;this.use(Ie(o,n));break;case"urlencoded":this.use(Le(r));break;case"trustProxy":this.use(Ue(r));break;case"timeout":this.use(Be(r));break;case"session":this.use(qe(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&&g.applyGlobalMiddlewaresToAllRoutes(this.globalMiddlewares),this.wasInitialized=!0)}handleNotFound=(e,t)=>{if(this.notFoundHandler){this.notFoundHandler(e,t);return}let r=new O(e.url,e.method);t.notFound({...b(r)})};registerNotFoundRoutes(){let e=["GET","POST","PUT","PATCH","DELETE","OPTIONS"];for(let t of e)g.addOrUpdate(t,"*",[],this.handleNotFound,{excludeFromSwagger:!0})}};var Xe=class{};var hr=g;0&&(module.exports={ARG_SYMBOL,BasePlugin,Command,CommandRegistry,Request,Response,Server,VALIDATION_ERROR_SYMBOL,arg,commandRegistry,controller,cookie,cors,del,fileParser,flag,get,getContentType,helmet,json,log,middleware,patch,post,put,rateLimiter,router,serialize,serveStatic,session,timeout,trustProxy,urlencoded,validate});
156
156
  //# sourceMappingURL=index.cjs.map