balda 0.0.51 → 0.0.52

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/cli.js CHANGED
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import Nt from'pino';import Ae from'path';import Ce from'fs';import {execSync}from'child_process';import*as ut from'readline';import {createRequire}from'module';import {Ajv}from'ajv';import Bt from'fast-json-stringify';import Gt from'crypto';import {promisify}from'util';import {gzip,gunzip}from'zlib';var Ue=Object.defineProperty;var ze=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var S=(o,e,t,r)=>{for(var s=void 0,n=o.length-1,c;n>=0;n--)(c=o[n])&&(s=(c(e,t,s))||s);return s&&Ue(e,t,s),s};var Je=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")}},O=new Je;var Ke=class{getCliArgs(){switch(O.type){case "bun":return this.getBunArgs();case "node":return this.getNodeArgs();case "deno":return Deno.args;default:throw new Error("Unsupported runtime")}}getCliCaller(){switch(O.type){case "bun":return "bun";case "node":return process.argv[0];case "deno":return "deno";default:throw new Error("Unsupported runtime")}}getBunArgs(){let e=Bun.argv,t=this.findScriptIndex(e);return e.slice(t+1)}getNodeArgs(){let e=process.argv,t=this.findScriptIndex(e);return e.slice(t+1)}findScriptIndex(e){if(e.length>=3&&e[1].includes(".bin/"))return 1;for(let t=0;t<e.length;t++){let r=e[t],s=r.split("/").pop()||r;if(!r.startsWith("-")){if(s==="yarn"&&t+1<e.length&&e[t+1]==="run"||s==="npx"&&t+1<e.length)return t+1;if(s==="yarn"||s==="pnpm")return t;if(s==="npm"&&t+1<e.length&&e[t+1]==="run"||s==="bun"&&t+1<e.length&&e[t+1]==="run")return t+1;if(/\.(js|ts|mjs|cjs)$/.test(r))return t;if(/^(tsx|ts-node|node|bun)$/.test(s)){for(let 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}},ye=new Ke;var it=(o,e)=>{let t=Array(e.length+1).fill(null).map(()=>Array(o.length+1).fill(null));for(let r=0;r<=o.length;r++)t[0][r]=r;for(let r=0;r<=e.length;r++)t[r][0]=r;for(let r=1;r<=e.length;r++)for(let s=1;s<=o.length;s++){let n=o[s-1]===e[r-1]?0:1;t[r][s]=Math.min(t[r][s-1]+1,t[r-1][s]+1,t[r-1][s-1]+n);}return t[e.length][o.length]},Me=o=>o.toLowerCase().replace(/[-_.]/g,"_").replace(/([A-Z])/g,"_$1").replace(/^_+/,"").replace(/_+$/,"").toLowerCase(),$e=o=>o.split(/[-_.]/g).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),at=o=>o.split(/[-_.]/g).map(e=>e.toLowerCase()).join("-");var jt=o=>{if(!o||o==="-"||o==="--")return null;let e=o.indexOf("=");if(e>0){let t=o.substring(0,e),r=o.substring(e+1);return {name:t,value:lt(r)}}return {name:o,value:true}},lt=o=>{if(o.toLowerCase()==="true")return true;if(o.toLowerCase()==="false")return false;let e=Number(o);return !Number.isNaN(e)&&Number.isFinite(e)?e:o},Y=()=>{let o=ye.getCliArgs(),e=[],t={};if(!o||!o.length)return {args:e,flags:t};for(let r=0;r<o.length;r++){let s=o[r];if(!(!s||typeof s!="string")){if(s.startsWith("-")){let n=jt(s);if(n){if(n.value===true&&r+1<o.length){let c=o[r+1];c&&typeof c=="string"&&!c.startsWith("-")&&(n.value=lt(c),r++);}if(n.name in t){let c=t[n.name];Array.isArray(c)?c.push(n.value):t[n.name]=[c,n.value];}else t[n.name]=n.value;}continue}e.push(s);}}return {args:e,flags:t}},ct=(o,e)=>{if(!o||typeof o!="string"||!e||!Array.isArray(e)||e.length===0)return "";let t=o.toLowerCase().trim(),r=e.filter(c=>{let a=c.toLowerCase();if(a===t||a.includes(t)||t.includes(a))return true;let d=it(a,t),u=Math.max(t.length,a.length)*.4;return d<=u});if(r.length===0)return "";let n=r.slice(0,3).map(c=>`\x1B[36m${c}\x1B[0m`).join(", ");return `\x1B[31m\u2717\x1B[0m Command \x1B[33m${o}\x1B[0m not found
3
- \x1B[32m\u{1F4A1}\x1B[0m Did you mean: ${n}?`},Ee=()=>ye.getCliArgs()[0]||null;var _t=()=>Nt({level:"info",formatters:{level:e=>({level:e})}}),E=_t();var We=class{getCwd(){switch(O.type){case "node":case "bun":return process.cwd();case "deno":return Deno.cwd();default:throw new Error("Unsupported runtime")}}},N=new We;var Ve=class{basename(e){switch(O.type){case "node":case "bun":case "deno":return Ae.basename(e);default:throw new Error("Unsupported runtime")}}join(...e){switch(O.type){case "node":case "bun":case "deno":return Ae.join(...e);default:throw new Error("Unsupported runtime")}}extName(e){switch(O.type){case "bun":case "node":case "deno":return Ae.extname(e);default:throw new Error("Unsupported runtime")}}resolve(...e){switch(O.type){case "bun":case "node":case "deno":return Ae.resolve(...e);default:throw new Error("Unsupported runtime")}}},w=new Ve;var _=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)}static getOrCreateAll(e){return this.metadata.has(e)||this.metadata.set(e,new Map),this.metadata.get(e)}static delete(e,t){this.metadata.get(e)?.delete(t);}static clear(e){this.metadata.delete(e);}};var ee="VALIDATION_ERROR";var dt=Y().args.slice(1),R=o=>(e,t)=>{let r=Ee();if(!r||r!==e.commandName)return;let s=t;_.set(e,t,{type:"arg",name:s,description:o.description});let n=dt.length?dt.shift():o.defaultValue;if(o.required&&!n){let c=_.get(e,ee);_.set(e,ee,[...c||[],{type:"arg",name:s,message:"Required argument not provided"}]);return}o.parse&&n&&(n=o.parse(n)),Object.defineProperty(e,t,{value:n,enumerable:true,configurable:true,writable:true});};var Xe=class{exit(e){switch(O.type){case "bun":case "node":process.exit(e);case "deno":Deno.exit(e);default:throw new Error(`Unsupported runtime: ${O.type}`)}}},z=new Xe;var q=class{static flagsAndArgs={flags:Y().flags,args:Y().args.slice(1)};static commandName=this.name;static calledBy=this.name;static description="";static help=[];static options={keepAlive:false,loggerPath:"src/logger.ts",allowUnknownFlags:true};static args=this.flagsAndArgs.args;static flags=this.flagsAndArgs.flags;static logger=E.child({scope:this.constructor.name});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(u=>t.includes(u)))return;let s=this.commandName,n=this.description||"No description available",c=this.help||[],a=this.options,d=this.generateHelpOutput({name:s,description:n,helpText:c,options:a,args:this.args,flags:this.flags},this);console.log(d),z.exit(0);}static generateHelpOutput=(e,t)=>{let{name:r,description:s,helpText:n,options:c,args:a,flags:d}=e,u={title:"\x1B[1;36m",subtitle:"\x1B[1;33m",description:"\x1B[0;37m",code:"\x1B[0;32m",flag:"\x1B[0;35m",reset:"\x1B[0m",error:"\x1B[0;31m",success:"\x1B[0;32m",info:"\x1B[0;34m"},l=[`${u.title}${r}${u.reset}`,`${u.description}${s}${u.reset}`,"",`${u.subtitle}Usage:${u.reset}`,` ${u.code}${r}${u.reset} [options] [arguments]`,"",`${u.subtitle}Options:${u.reset}`,` ${u.flag}-h, --help${u.reset} Show this help message`,"",`${u.subtitle}Command Options:${u.reset}`,` ${u.flag}keepAlive${u.reset} ${c?.keepAlive??false?u.success+"Enabled"+u.reset:u.error+"Disabled"+u.reset}`,` ${u.flag}loggerPath${u.reset} ${c?.loggerPath??"src/logger.ts"}`,` ${u.flag}allowUnknownFlags${u.reset} ${c?.allowUnknownFlags??true?u.success+"Enabled"+u.reset:u.error+"Disabled"+u.reset}`,""];if(n){let m=Array.isArray(n)?n:[n];l.push(`${u.subtitle}Help:${u.reset}`),m.forEach(g=>{l.push(` ${u.description}${g}${u.reset}`);}),l.push("");}let i=_.getAll(t),p=i?Array.from(i.values()).filter(m=>m.type==="arg"):[],h=i?Array.from(i.values()).filter(m=>m.type==="flag"):[];return p.length&&(l.push(`${u.subtitle}Available Arguments:${u.reset}`),p.forEach(m=>{let g=m.required?` ${u.error}(required)${u.reset}`:"",f=m.description?` ${u.description}${m.description}${u.reset}`:"";l.push(` ${u.code}${m.name}${u.reset}${g}${f}`);}),l.push("")),h.length&&(l.push(`${u.subtitle}Available Flags:${u.reset}`),h.forEach(m=>{m.aliases&&!Array.isArray(m.aliases)&&(m.aliases=[m.aliases]);let g=m.aliases.length?` ${u.flag}(${m.aliases.join(", ")})${u.reset}`:"",f=m.required?` ${u.error}(required)${u.reset}`:"",x=m.description?` ${u.description}${m.description}${u.reset}`:"";l.push(` ${u.flag}--${m.name}${g}${u.reset}${f}${x}`);}),l.push("")),((a?.length??0)>0||d&&Object.keys(d).length>0)&&(l.push(`${u.subtitle}Current Context:${u.reset}`),a?.length&&l.push(` ${u.info}Provided Arguments:${u.reset} ${u.code}${a.join(" ")}${u.reset}`),d&&Object.keys(d).length>0&&(l.push(` ${u.info}Provided Flags:${u.reset}`),Object.keys(d).forEach(m=>{let g=d[m],f=g!=null?` = ${u.code}${g}${u.reset}`:"";l.push(` ${u.flag}${m}${u.reset}${f}`);})),l.push("")),n&&(Array.isArray(n)?n.some(m=>m.includes("example")):n.includes("example"))&&(l.push(`${u.subtitle}Examples:${u.reset}`),(Array.isArray(n)?n.filter(g=>g.includes("example")):[n.split("example")[1].trim()]).forEach(g=>{l.push(` ${u.code}${g}${u.reset}`);}),l.push("")),l.join(`
4
- `)};static validateUnknownFlags=e=>{if(e.options?.allowUnknownFlags!==false)return;let t=new Set(["-h","--help"]),r=new Set,s=_.getAll(e);if(s){for(let c of s.values())if(c.type==="flag"&&(r.add(`--${c.name}`),r.add(`-${c.name}`),r.add(c.name),c.aliases)){let a=Array.isArray(c.aliases)?c.aliases:[c.aliases];for(let d of a)r.add(`--${d}`),r.add(`-${d}`),r.add(d);}}let n=Object.keys(e.flags).filter(c=>!t.has(c)&&!r.has(c));if(n.length){let c={error:"\x1B[0;31m",title:"\x1B[1;31m",reset:"\x1B[0m",info:"\x1B[0;34m",flag:"\x1B[0;35m"};console.error(`${c.title}\u274C Unknown Flags:${c.reset}`),console.error(""),n.forEach(a=>{console.error(` ${c.error}\u2022${c.reset} ${c.flag}${a}${c.reset}`);}),console.error(""),console.error(`${c.info}\u{1F4A1} Tip: Use --help for available flags${c.reset}`),z.exit(1);}};static validateContext=e=>{let t=Array.from(_.get(e,ee)||[]);if(t.length){let r={error:"\x1B[0;31m",title:"\x1B[1;31m",reset:"\x1B[0m",info:"\x1B[0;34m",code:"\x1B[0;32m"};console.error(`${r.title}\u274C Validation Errors:${r.reset}`),console.error(""),t.forEach((s,n)=>{let c=`${r.info}${n+1}.${r.reset}`,a=`${r.error}${s.type.toUpperCase()}${r.reset}`,d=`${r.code}${s.name}${r.reset}`;console.error(` ${c} ${a} ${d}: ${r.error}${s.message}${r.reset}`);}),console.error(""),console.error(`${r.info}\u{1F4A1} Tip: Use --help for usage information${r.reset}`),z.exit(1);}}};var H=o=>(e,t)=>{let r=Ee();if(!r||r!==e.commandName)return;let s=o.name||t,n=Y().flags,c=o.aliases?Array.isArray(o.aliases)?o.aliases:[o.aliases]:[],a=[s,...c],d=o.defaultValue;for(let u of a){let l=[u,`-${u}`,`--${u}`];for(let i of l)if(i in n){let p=n[i];o.type==="list"?d=(Array.isArray(p)?p:[p]).map(m=>{let g=String(m);return o.parse?o.parse(g):g}):(d=p,o.type==="boolean"?d=!!d:o.type==="number"?d=Number(d):o.type==="string"&&(d=String(d)),o.parse&&(d=o.parse(d)));break}if(d!==o.defaultValue)break}if(_.set(e,t,{type:"flag",name:s,aliases:c||[],description:o.description}),o.required&&(o.type==="list"?!d||Array.isArray(d)&&d.length===0:!d)){let l=_.get(e,ee);_.set(e,ee,[...l||[],{type:"flag",name:s,message:"Required flag not provided"}]);return}Object.defineProperty(e,t,{value:d,enumerable:true,configurable:true,writable:true});};H.boolean=o=>H({...o,type:"boolean"});H.string=o=>H({...o,type:"string"});H.number=o=>H({...o,type:"number"});H.list=o=>H({...o,type:"list"});H.array=o=>H({...o,type:"list"});var C=H;var Ge=class{async glob(...e){let t=await import('fs/promises'),r=N.getCwd(),s=w.resolve(r,e[1]?.cwd??""),n=[];for await(let c of t.glob(...e)){if(typeof c=="string"){n.push(w.resolve(s,c));continue}c.isFile()&&n.push(w.resolve(s,c.name));}return n}async mkdir(e,t){switch(O.type){case "bun":case "node":await(await import('fs/promises')).mkdir(e,{recursive:t?.recursive??false,mode:t?.mode});break;case "deno":typeof t?.mode=="string"&&(t.mode=Number.parseInt(t.mode)),await Deno.mkdir(e,{recursive:t?.recursive??false,mode:t?.mode});break}}async exists(e){switch(O.type){case "node":return (await import('fs')).existsSync(e);case "bun":return (await import('fs')).existsSync(e);case "deno":return Deno.stat(e).then(()=>true).catch(()=>false);default:throw new Error("Unsupported runtime")}}async readFile(e,t){switch(O.type){case "node":let s=await(await import('fs/promises')).readFile(e,{encoding:t?.encoding??null});return t?.encoding==="utf8"?s:new Uint8Array(s);case "bun":let n=Bun.file(e);return t?.encoding==="utf8"?n.text():new Uint8Array(await n.arrayBuffer());case "deno":let c=await Deno.readFile(e);return t?.encoding==="utf8"?new TextDecoder().decode(c):new Uint8Array(c)}}async writeFile(e,t){switch(O.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(O.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 n=await(await import('fs/promises')).stat(e);return {isDirectory:n.isDirectory(),isFile:n.isFile(),isSymbolicLink:n.isSymbolicLink(),size:n.size};case "deno":let c=await Deno.stat(e);return {isDirectory:c.isDirectory,isFile:c.isFile,isSymbolicLink:false,size:c.size}}}async unlink(e){switch(O.type){case "node":await(await import('fs/promises')).unlink(e);break;case "bun":await Bun.file(e).delete();break;case "deno":await Deno.remove(e);break;default:throw new Error("Unsupported runtime")}}async streamFile(e){switch(O.type){case "node":let t=await import('fs'),{Readable:r}=await import('stream'),s=t.createReadStream(e);return r.toWeb(s);case "bun":return Bun.file(e).stream();case "deno":return (await Deno.open(e)).readable;default:throw new Error("Unsupported runtime")}}async readdir(e){switch(O.type){case "bun":case "node":return (await import('fs/promises')).readdir(e);case "deno":let r=[];for await(let s of Deno.readDir(e))r.push(s.name);return r;default:throw new Error("Unsupported runtime")}}},y=new Ge;var ke=typeof import.meta<"u"?createRequire(import.meta.url):ze("module").createRequire?.(import.meta?.url??__filename)??ze,W=async o=>{let e=w.join(process.cwd(),"node_modules");if(!await y.exists(e))return o;let r=[];for(let s of o){let n=w.join(e,s);await y.exists(n)||r.push(s);}return r},I=async()=>await y.exists(w.join(process.cwd(),"yarn.lock"))?["yarn","add","-D"]:await y.exists(w.join(process.cwd(),"pnpm-lock.yaml"))?["pnpm","add","-D"]:await y.exists(w.join(process.cwd(),"package-lock.json"))?["npm","install","-D"]:await y.exists(w.join(process.cwd(),"bun.lockb"))?["bun","add","-D"]:await y.exists(w.join(process.cwd(),"deno.lock"))?["deno","add","-D"]:["npm","install","-D"],k=async(o,e,t,r,s=true)=>{let n=ut.createInterface({input:process.stdin,output:process.stdout}),c=t.join(", "),a=`Do you want to install the following ${s?"dev":""} dependencies using ${e}?
2
+ import Nt from'pino';import Ae from'path';import Ce from'fs';import {execSync}from'child_process';import*as ut from'readline';import {createRequire}from'module';import {Ajv}from'ajv';import Bt from'fast-json-stringify';import Xt from'crypto';import {promisify}from'util';import {gzip,gunzip}from'zlib';var Ue=Object.defineProperty;var ze=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var S=(o,e,t,r)=>{for(var s=void 0,n=o.length-1,c;n>=0;n--)(c=o[n])&&(s=(c(e,t,s))||s);return s&&Ue(e,t,s),s};var Je=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")}},O=new Je;var Ke=class{getCliArgs(){switch(O.type){case "bun":return this.getBunArgs();case "node":return this.getNodeArgs();case "deno":return Deno.args;default:throw new Error("Unsupported runtime")}}getCliCaller(){switch(O.type){case "bun":return "bun";case "node":return process.argv[0];case "deno":return "deno";default:throw new Error("Unsupported runtime")}}getBunArgs(){let e=Bun.argv,t=this.findScriptIndex(e);return e.slice(t+1)}getNodeArgs(){let e=process.argv,t=this.findScriptIndex(e);return e.slice(t+1)}findScriptIndex(e){if(e.length>=3&&e[1].includes(".bin/"))return 1;for(let t=0;t<e.length;t++){let r=e[t],s=r.split("/").pop()||r;if(!r.startsWith("-")){if(s==="yarn"&&t+1<e.length&&e[t+1]==="run"||s==="npx"&&t+1<e.length)return t+1;if(s==="yarn"||s==="pnpm")return t;if(s==="npm"&&t+1<e.length&&e[t+1]==="run"||s==="bun"&&t+1<e.length&&e[t+1]==="run")return t+1;if(/\.(js|ts|mjs|cjs)$/.test(r))return t;if(/^(tsx|ts-node|node|bun)$/.test(s)){for(let 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}},ye=new Ke;var it=(o,e)=>{let t=Array(e.length+1).fill(null).map(()=>Array(o.length+1).fill(null));for(let r=0;r<=o.length;r++)t[0][r]=r;for(let r=0;r<=e.length;r++)t[r][0]=r;for(let r=1;r<=e.length;r++)for(let s=1;s<=o.length;s++){let n=o[s-1]===e[r-1]?0:1;t[r][s]=Math.min(t[r][s-1]+1,t[r-1][s]+1,t[r-1][s-1]+n);}return t[e.length][o.length]},Me=o=>o.toLowerCase().replace(/[-_.]/g,"_").replace(/([A-Z])/g,"_$1").replace(/^_+/,"").replace(/_+$/,"").toLowerCase(),$e=o=>o.split(/[-_.]/g).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),at=o=>o.split(/[-_.]/g).map(e=>e.toLowerCase()).join("-");var jt=o=>{if(!o||o==="-"||o==="--")return null;let e=o.indexOf("=");if(e>0){let t=o.substring(0,e),r=o.substring(e+1);return {name:t,value:lt(r)}}return {name:o,value:true}},lt=o=>{if(o.toLowerCase()==="true")return true;if(o.toLowerCase()==="false")return false;let e=Number(o);return !Number.isNaN(e)&&Number.isFinite(e)?e:o},Y=()=>{let o=ye.getCliArgs(),e=[],t={};if(!o||!o.length)return {args:e,flags:t};for(let r=0;r<o.length;r++){let s=o[r];if(!(!s||typeof s!="string")){if(s.startsWith("-")){let n=jt(s);if(n){if(n.value===true&&r+1<o.length){let c=o[r+1];c&&typeof c=="string"&&!c.startsWith("-")&&(n.value=lt(c),r++);}if(n.name in t){let c=t[n.name];Array.isArray(c)?c.push(n.value):t[n.name]=[c,n.value];}else t[n.name]=n.value;}continue}e.push(s);}}return {args:e,flags:t}},ct=(o,e)=>{if(!o||typeof o!="string"||!e||!Array.isArray(e)||e.length===0)return "";let t=o.toLowerCase().trim(),r=e.filter(c=>{let a=c.toLowerCase();if(a===t||a.includes(t)||t.includes(a))return true;let d=it(a,t),u=Math.max(t.length,a.length)*.4;return d<=u});if(r.length===0)return "";let n=r.slice(0,3).map(c=>`\x1B[36m${c}\x1B[0m`).join(", ");return `\x1B[31m\u2717\x1B[0m Command \x1B[33m${o}\x1B[0m not found
3
+ \x1B[32m\u{1F4A1}\x1B[0m Did you mean: ${n}?`},Ee=()=>ye.getCliArgs()[0]||null;var _t=()=>Nt({level:"info",formatters:{level:e=>({level:e})}}),E=_t();var We=class{getCwd(){switch(O.type){case "node":case "bun":return process.cwd();case "deno":return Deno.cwd();default:throw new Error("Unsupported runtime")}}},N=new We;var Ve=class{basename(e){switch(O.type){case "node":case "bun":case "deno":return Ae.basename(e);default:throw new Error("Unsupported runtime")}}join(...e){switch(O.type){case "node":case "bun":case "deno":return Ae.join(...e);default:throw new Error("Unsupported runtime")}}extName(e){switch(O.type){case "bun":case "node":case "deno":return Ae.extname(e);default:throw new Error("Unsupported runtime")}}resolve(...e){switch(O.type){case "bun":case "node":case "deno":return Ae.resolve(...e);default:throw new Error("Unsupported runtime")}}},w=new Ve;var _=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)}static getOrCreateAll(e){return this.metadata.has(e)||this.metadata.set(e,new Map),this.metadata.get(e)}static delete(e,t){this.metadata.get(e)?.delete(t);}static clear(e){this.metadata.delete(e);}};var ee="VALIDATION_ERROR";var dt=Y().args.slice(1),R=o=>(e,t)=>{let r=Ee();if(!r||r!==e.commandName)return;let s=t;_.set(e,t,{type:"arg",name:s,description:o.description});let n=dt.length?dt.shift():o.defaultValue;if(o.required&&!n){let c=_.get(e,ee);_.set(e,ee,[...c||[],{type:"arg",name:s,message:"Required argument not provided"}]);return}o.parse&&n&&(n=o.parse(n)),Object.defineProperty(e,t,{value:n,enumerable:true,configurable:true,writable:true});};var Ge=class{exit(e){switch(O.type){case "bun":case "node":process.exit(e);case "deno":Deno.exit(e);default:throw new Error(`Unsupported runtime: ${O.type}`)}}},z=new Ge;var q=class{static flagsAndArgs={flags:Y().flags,args:Y().args.slice(1)};static commandName=this.name;static calledBy=this.name;static description="";static help=[];static options={keepAlive:false,loggerPath:"src/logger.ts",allowUnknownFlags:true};static args=this.flagsAndArgs.args;static flags=this.flagsAndArgs.flags;static logger=E.child({scope:this.constructor.name});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(u=>t.includes(u)))return;let s=this.commandName,n=this.description||"No description available",c=this.help||[],a=this.options,d=this.generateHelpOutput({name:s,description:n,helpText:c,options:a,args:this.args,flags:this.flags},this);console.log(d),z.exit(0);}static generateHelpOutput=(e,t)=>{let{name:r,description:s,helpText:n,options:c,args:a,flags:d}=e,u={title:"\x1B[1;36m",subtitle:"\x1B[1;33m",description:"\x1B[0;37m",code:"\x1B[0;32m",flag:"\x1B[0;35m",reset:"\x1B[0m",error:"\x1B[0;31m",success:"\x1B[0;32m",info:"\x1B[0;34m"},l=[`${u.title}${r}${u.reset}`,`${u.description}${s}${u.reset}`,"",`${u.subtitle}Usage:${u.reset}`,` ${u.code}${r}${u.reset} [options] [arguments]`,"",`${u.subtitle}Options:${u.reset}`,` ${u.flag}-h, --help${u.reset} Show this help message`,"",`${u.subtitle}Command Options:${u.reset}`,` ${u.flag}keepAlive${u.reset} ${c?.keepAlive??false?u.success+"Enabled"+u.reset:u.error+"Disabled"+u.reset}`,` ${u.flag}loggerPath${u.reset} ${c?.loggerPath??"src/logger.ts"}`,` ${u.flag}allowUnknownFlags${u.reset} ${c?.allowUnknownFlags??true?u.success+"Enabled"+u.reset:u.error+"Disabled"+u.reset}`,""];if(n){let m=Array.isArray(n)?n:[n];l.push(`${u.subtitle}Help:${u.reset}`),m.forEach(g=>{l.push(` ${u.description}${g}${u.reset}`);}),l.push("");}let i=_.getAll(t),p=i?Array.from(i.values()).filter(m=>m.type==="arg"):[],h=i?Array.from(i.values()).filter(m=>m.type==="flag"):[];return p.length&&(l.push(`${u.subtitle}Available Arguments:${u.reset}`),p.forEach(m=>{let g=m.required?` ${u.error}(required)${u.reset}`:"",f=m.description?` ${u.description}${m.description}${u.reset}`:"";l.push(` ${u.code}${m.name}${u.reset}${g}${f}`);}),l.push("")),h.length&&(l.push(`${u.subtitle}Available Flags:${u.reset}`),h.forEach(m=>{m.aliases&&!Array.isArray(m.aliases)&&(m.aliases=[m.aliases]);let g=m.aliases.length?` ${u.flag}(${m.aliases.join(", ")})${u.reset}`:"",f=m.required?` ${u.error}(required)${u.reset}`:"",x=m.description?` ${u.description}${m.description}${u.reset}`:"";l.push(` ${u.flag}--${m.name}${g}${u.reset}${f}${x}`);}),l.push("")),((a?.length??0)>0||d&&Object.keys(d).length>0)&&(l.push(`${u.subtitle}Current Context:${u.reset}`),a?.length&&l.push(` ${u.info}Provided Arguments:${u.reset} ${u.code}${a.join(" ")}${u.reset}`),d&&Object.keys(d).length>0&&(l.push(` ${u.info}Provided Flags:${u.reset}`),Object.keys(d).forEach(m=>{let g=d[m],f=g!=null?` = ${u.code}${g}${u.reset}`:"";l.push(` ${u.flag}${m}${u.reset}${f}`);})),l.push("")),n&&(Array.isArray(n)?n.some(m=>m.includes("example")):n.includes("example"))&&(l.push(`${u.subtitle}Examples:${u.reset}`),(Array.isArray(n)?n.filter(g=>g.includes("example")):[n.split("example")[1].trim()]).forEach(g=>{l.push(` ${u.code}${g}${u.reset}`);}),l.push("")),l.join(`
4
+ `)};static validateUnknownFlags=e=>{if(e.options?.allowUnknownFlags!==false)return;let t=new Set(["-h","--help"]),r=new Set,s=_.getAll(e);if(s){for(let c of s.values())if(c.type==="flag"&&(r.add(`--${c.name}`),r.add(`-${c.name}`),r.add(c.name),c.aliases)){let a=Array.isArray(c.aliases)?c.aliases:[c.aliases];for(let d of a)r.add(`--${d}`),r.add(`-${d}`),r.add(d);}}let n=Object.keys(e.flags).filter(c=>!t.has(c)&&!r.has(c));if(n.length){let c={error:"\x1B[0;31m",title:"\x1B[1;31m",reset:"\x1B[0m",info:"\x1B[0;34m",flag:"\x1B[0;35m"};console.error(`${c.title}\u274C Unknown Flags:${c.reset}`),console.error(""),n.forEach(a=>{console.error(` ${c.error}\u2022${c.reset} ${c.flag}${a}${c.reset}`);}),console.error(""),console.error(`${c.info}\u{1F4A1} Tip: Use --help for available flags${c.reset}`),z.exit(1);}};static validateContext=e=>{let t=Array.from(_.get(e,ee)||[]);if(t.length){let r={error:"\x1B[0;31m",title:"\x1B[1;31m",reset:"\x1B[0m",info:"\x1B[0;34m",code:"\x1B[0;32m"};console.error(`${r.title}\u274C Validation Errors:${r.reset}`),console.error(""),t.forEach((s,n)=>{let c=`${r.info}${n+1}.${r.reset}`,a=`${r.error}${s.type.toUpperCase()}${r.reset}`,d=`${r.code}${s.name}${r.reset}`;console.error(` ${c} ${a} ${d}: ${r.error}${s.message}${r.reset}`);}),console.error(""),console.error(`${r.info}\u{1F4A1} Tip: Use --help for usage information${r.reset}`),z.exit(1);}}};var H=o=>(e,t)=>{let r=Ee();if(!r||r!==e.commandName)return;let s=o.name||t,n=Y().flags,c=o.aliases?Array.isArray(o.aliases)?o.aliases:[o.aliases]:[],a=[s,...c],d=o.defaultValue;for(let u of a){let l=[u,`-${u}`,`--${u}`];for(let i of l)if(i in n){let p=n[i];o.type==="list"?d=(Array.isArray(p)?p:[p]).map(m=>{let g=String(m);return o.parse?o.parse(g):g}):(d=p,o.type==="boolean"?d=!!d:o.type==="number"?d=Number(d):o.type==="string"&&(d=String(d)),o.parse&&(d=o.parse(d)));break}if(d!==o.defaultValue)break}if(_.set(e,t,{type:"flag",name:s,aliases:c||[],description:o.description}),o.required&&(o.type==="list"?!d||Array.isArray(d)&&d.length===0:!d)){let l=_.get(e,ee);_.set(e,ee,[...l||[],{type:"flag",name:s,message:"Required flag not provided"}]);return}Object.defineProperty(e,t,{value:d,enumerable:true,configurable:true,writable:true});};H.boolean=o=>H({...o,type:"boolean"});H.string=o=>H({...o,type:"string"});H.number=o=>H({...o,type:"number"});H.list=o=>H({...o,type:"list"});H.array=o=>H({...o,type:"list"});var C=H;var Xe=class{async glob(...e){let t=await import('fs/promises'),r=N.getCwd(),s=w.resolve(r,e[1]?.cwd??""),n=[];for await(let c of t.glob(...e)){if(typeof c=="string"){n.push(w.resolve(s,c));continue}c.isFile()&&n.push(w.resolve(s,c.name));}return n}async mkdir(e,t){switch(O.type){case "bun":case "node":await(await import('fs/promises')).mkdir(e,{recursive:t?.recursive??false,mode:t?.mode});break;case "deno":typeof t?.mode=="string"&&(t.mode=Number.parseInt(t.mode)),await Deno.mkdir(e,{recursive:t?.recursive??false,mode:t?.mode});break}}async exists(e){switch(O.type){case "node":return (await import('fs')).existsSync(e);case "bun":return (await import('fs')).existsSync(e);case "deno":return Deno.stat(e).then(()=>true).catch(()=>false);default:throw new Error("Unsupported runtime")}}async readFile(e,t){switch(O.type){case "node":let s=await(await import('fs/promises')).readFile(e,{encoding:t?.encoding??null});return t?.encoding==="utf8"?s:new Uint8Array(s);case "bun":let n=Bun.file(e);return t?.encoding==="utf8"?n.text():new Uint8Array(await n.arrayBuffer());case "deno":let c=await Deno.readFile(e);return t?.encoding==="utf8"?new TextDecoder().decode(c):new Uint8Array(c)}}async writeFile(e,t){switch(O.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(O.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 n=await(await import('fs/promises')).stat(e);return {isDirectory:n.isDirectory(),isFile:n.isFile(),isSymbolicLink:n.isSymbolicLink(),size:n.size};case "deno":let c=await Deno.stat(e);return {isDirectory:c.isDirectory,isFile:c.isFile,isSymbolicLink:false,size:c.size}}}async unlink(e){switch(O.type){case "node":await(await import('fs/promises')).unlink(e);break;case "bun":await Bun.file(e).delete();break;case "deno":await Deno.remove(e);break;default:throw new Error("Unsupported runtime")}}async streamFile(e){switch(O.type){case "node":let t=await import('fs'),{Readable:r}=await import('stream'),s=t.createReadStream(e);return r.toWeb(s);case "bun":return Bun.file(e).stream();case "deno":return (await Deno.open(e)).readable;default:throw new Error("Unsupported runtime")}}async readdir(e){switch(O.type){case "bun":case "node":return (await import('fs/promises')).readdir(e);case "deno":let r=[];for await(let s of Deno.readDir(e))r.push(s.name);return r;default:throw new Error("Unsupported runtime")}}},y=new Xe;var ke=typeof import.meta<"u"?createRequire(import.meta.url):ze("module").createRequire?.(import.meta?.url??__filename)??ze,W=async o=>{let e=w.join(process.cwd(),"node_modules");if(!await y.exists(e))return o;let r=[];for(let s of o){let n=w.join(e,s);await y.exists(n)||r.push(s);}return r},I=async()=>await y.exists(w.join(process.cwd(),"yarn.lock"))?["yarn","add","-D"]:await y.exists(w.join(process.cwd(),"pnpm-lock.yaml"))?["pnpm","add","-D"]:await y.exists(w.join(process.cwd(),"package-lock.json"))?["npm","install","-D"]:await y.exists(w.join(process.cwd(),"bun.lockb"))?["bun","add","-D"]:await y.exists(w.join(process.cwd(),"deno.lock"))?["deno","add","-D"]:["npm","install","-D"],k=async(o,e,t,r,s=true)=>{let n=ut.createInterface({input:process.stdin,output:process.stdout}),c=t.join(", "),a=`Do you want to install the following ${s?"dev":""} dependencies using ${e}?
5
5
  ${c}
6
6
  (y/n): `;return new Promise(d=>{n.question(a,u=>{if(n.close(),u.toLowerCase()==="y"||u.toLowerCase()==="yes"){execSync(o,r),d(true);return}d(false);});})};var B=class extends q{static commandName="build";static description="Build the project for production, node.js only";static help=["Build the project for production, node.js only","It will create a production build of the project in the dist directory","Must have a tsconfig.json file in the root of the project","Must have esbuild installed as a dependency while running the command","Must have esbuild-plugin-copy installed as a dependency while running the command if you want to copy assets to the output directory","Example: npx balda build -t ./tsconfig.json -a ./assets"];static clearDist;static entry;static output;static tsconfig;static assets;static format;static packages;static sourcemap;static async handle(){if(typeof process===void 0&&(this.logger.error("Build command is only supported in node.js"),process.exit(1)),["esm","cjs"].includes(this.format)||(this.logger.error("Invalid format, must be 'esm' or 'cjs'"),process.exit(1)),["bundle","external"].includes(this.packages)||(this.logger.error("Invalid packages, must be 'bundle' or 'external'"),process.exit(1)),!await import('esbuild').then(a=>true).catch(()=>false)){let[a,d,u]=await I();await k(`${a} ${d} esbuild ${u}`,a,["esbuild"],{stdio:"inherit"})||(this.logger.warn("User chose to not continue with the installation of esbuild, exiting..."),process.exit(0));}let t=await import('esbuild').catch(a=>{throw this.logger.error("esbuild is not installed, please install it with `npm install -D esbuild` to use the build command"),new Error("esbuild is not installed")}),r=Ae.join(this.output,"assets"),s=[];if(this.assets){let{copy:a}=await import('esbuild-plugin-copy').catch(d=>{throw this.logger.error("esbuild-plugin-copy is not installed, please install it with `npm install -D esbuild-plugin-copy` to use the build command"),new Error("esbuild-plugin-copy is not installed")});Ce.existsSync(r)||Ce.mkdirSync(r,{recursive:true}),s.push(a({assets:{from:this.assets,to:r}}));}this.clearDist&&Ce.existsSync(this.output)&&(this.logger.info("Clearing dist directory..."),Ce.rmSync(this.output,{recursive:true})),this.logger.info("Building project...");let n=Ae.join(this.output,"server.js"),c=await t.build({tsconfig:this.tsconfig,entryPoints:[this.entry],bundle:true,platform:"node",outfile:n,minify:true,sourcemap:this.sourcemap,plugins:s,format:this.format,packages:this.packages});c.errors.length&&(this.logger.error(JSON.stringify({message:"Failed to build the project",errors:c.errors},null,2)),process.exit(1)),c.warnings.length&&this.logger.warn(JSON.stringify({message:"Failed to build the project",warnings:c.warnings},null,2)),this.logger.info(JSON.stringify({message:`Project built successfully in ${n}`,output:n,assets:!!this.assets},null,2)),process.exit(0);}};S([C({type:"boolean",aliases:["c"],name:"clear-dist",required:false,defaultValue:false,description:"Whether to clear the dist directory before building the project"})],B,"clearDist"),S([C({type:"string",aliases:["e"],name:"entry",required:false,defaultValue:"./src/index.ts",description:"The entry point of the project, default is ./src/index.ts"})],B,"entry"),S([C({type:"string",aliases:["o"],name:"output",required:false,defaultValue:"./dist",description:"The path to the output directory, default is ./dist"})],B,"output"),S([C({type:"string",aliases:["t"],name:"tsconfig",required:false,defaultValue:"./tsconfig.json",description:"The path to the tsconfig.json file, default is ./tsconfig.json"})],B,"tsconfig"),S([C({type:"string",aliases:["a"],name:"assets",required:false,description:"The path to the assets directory that will be loaded in the production build"})],B,"assets"),S([C({type:"string",aliases:["f"],name:"format",required:false,defaultValue:"esm",description:"The format to build the project, default is esm, can be 'esm' or 'cjs'"})],B,"format"),S([C({type:"string",aliases:["p"],name:"packages",required:false,defaultValue:"external",description:"Weather to bundle node_modules or not, default is external, can be 'bundle' or 'external'"})],B,"packages"),S([C({type:"boolean",aliases:["s"],name:"sourcemap",required:false,defaultValue:true,description:"Whether to generate sourcemaps or not, default is true"})],B,"sourcemap");var F=class extends Error{constructor(e){super(e);}};var Ne=class extends F{constructor(e){super(`Failed to convert Zod schema to JSON Schema. This usually happens when using Zod v3 schemas with Zod v4. Make sure you're importing from 'zod' (v4) and not 'zod/v3'. Original error: ${e.message}`);}};var be=class extends F{constructor(){super("Zod v4 is required with the toJSONSchema() method. Install it with: npm install zod@^4.0.0");}};var Q=class{static zodModule=null;static zodSchemaCache=new WeakSet;static load(){if(this.zodModule)return this.zodModule;try{return this.zodModule=ke("zod"),this.ensureZodV4(),this.zodModule}catch{throw new Error(`Zod is not installed. Install it with: npm install zod
7
- Zod is a peer dependency required when using Zod schemas for validation.`)}}static get(){return this.load()}static isZodSchema(e){try{this.load();}catch{return false}if(typeof e!="object"||e===null)return false;if(this.zodSchemaCache.has(e))return true;let t="_def"in e&&typeof e.parse=="function"&&typeof e.safeParse=="function";return t&&this.zodSchemaCache.add(e),t}static ensureZodV4(){let e=this.zodModule?.z;if(!e)throw new be;if(!("toJSONSchema"in e))throw new be}static toJSONSchema(e){this.load(),this.ensureZodV4();let t=this.zodModule?.z;if(!t?.toJSONSchema)throw new be;if(!e||typeof e!="object"||!("_def"in e))throw new Error(`Invalid Zod schema provided. Make sure you're using Zod v4 schemas. If you're importing from 'zod/v3', change to 'zod' or '{ z } from "zod"'.`);try{return t.toJSONSchema(e)}catch(r){throw r instanceof Error&&r.message.includes("Cannot read properties of undefined")?new Ne(r):r}}};var _e=class extends F{constructor(){super("TypeBox is not installed. Install it with: npm install @sinclair/typebox");}};var X=class{static typeboxModule=null;static typeboxSchemaCache=new WeakSet;static load(){if(this.typeboxModule)return this.typeboxModule;try{return this.typeboxModule=ke("@sinclair/typebox"),this.typeboxModule}catch{throw new _e}}static get(){return this.load()}static isTypeBoxSchema(e){try{this.load();}catch{return false}if(typeof e!="object"||e===null)return false;if(this.typeboxSchemaCache.has(e))return true;let t="type"in e&&Object.getOwnPropertySymbols(e).some(r=>r.toString()==="Symbol(TypeBox.Kind)");return t&&this.typeboxSchemaCache.add(e),t}};function Se(o){if(!o||typeof o!="object")return o;let e;if(o.properties&&typeof o.properties=="object"){e={...o,additionalProperties:false};let t=o.properties,r={},s=false;for(let n in t){let c=t[n];if(c&&typeof c=="object"&&!("$ref"in c)){let a=Se(c);a!==c&&(s=true),r[n]=a;}else r[n]=c;}s&&(e.properties=r);}if(o.items&&typeof o.items=="object"&&!("$ref"in o.items)){let t=Se(o.items);t!==o.items&&(e=e??{...o},e.items=t);}for(let t of ["oneOf","anyOf","allOf"]){let r=o[t];if(Array.isArray(r)){let s=[],n=false;for(let c of r)if(c&&typeof c=="object"&&!("$ref"in c)){let a=Se(c);a!==c&&(n=true),s.push(a);}else s.push(c);n&&(e=e??{...o},e[t]=s);}}for(let t of ["$defs","definitions"]){let r=o[t];if(r&&typeof r=="object"){let s={},n=false;for(let c in r){let a=r[c];if(a&&typeof a=="object"){let d=Se(a);d!==a&&(n=true),s[c]=d;}else s[c]=a;}n&&(e=e??{...o},e[t]=s);}}return e??o}var M=class{static ajv=new Ajv({validateSchema:false,strict:false});static serializerCache=new WeakMap;static responseSerializersCache=new WeakMap;static refCounter=0;static schemaKeyCache=new WeakMap;static setGlobalInstance(e){this.ajv=e,this.ajv.opts.strict=false,this.ajv.opts.validateSchema=false;}static getSchemaKey(e,t){let r=this.schemaKeyCache.get(e);r||(r=new Map,this.schemaKeyCache.set(e,r));let s=r.get(t);return s||(s=`${t}_${++this.refCounter}`,r.set(t,s)),s}static getOrCompileValidator(e,t){let r=this.getSchemaKey(e,t),s=this.ajv.getSchema(r);if(s)return s;this.ajv.addSchema(e,r);let n=this.ajv.getSchema(r);if(!n)throw new Error(`Failed to compile schema with key: ${r}`);return n}static getOrCreateSerializer(e,t){if(!e||typeof e!="object")return null;let r=this.serializerCache.get(e);r||(r=new Map,this.serializerCache.set(e,r));let s=r.get(t);if(s)return s;try{let n=Se(e),c=Bt(n,{ajv:this.ajv.opts});return r.set(t,c),c}catch{return null}}static getOrCreateResponseSerializers(e){if(!e)return null;let t=this.responseSerializersCache.get(e);if(t)return t;let r=new Map;for(let[s,n]of Object.entries(e)){let c=Number(s),a=null;if(Q.isZodSchema(n)){let d=Q.toJSONSchema(n);a=this.getOrCreateSerializer(d,"fast_stringify_zod");}else X.isTypeBoxSchema(n)?a=this.getOrCreateSerializer(n,"fast_stringify_typebox"):typeof n=="object"&&n!==null&&(a=this.getOrCreateSerializer(n,"fast_stringify_json"));a&&r.set(c,a);}return this.responseSerializersCache.set(e,r),r}static storeJsonSchema(e,t){let r=this.getSchemaKey(e,t);this.ajv.getSchema(r)||this.ajv.addSchema(e,r);}static getJsonSchema(e,t){let r=this.schemaKeyCache.get(e);if(!r)return;let s=r.get(t);return s?this.ajv.getSchema(s)?.schema:void 0}static clearAllCaches(){this.ajv=new Ajv({validateSchema:false,strict:false}),this.serializerCache=new WeakMap,this.schemaKeyCache=new WeakMap,this.refCounter=0;}static getSchemaCount(){return Object.keys(this.ajv.schemas).length}static getCacheStats(){return {schemaCount:this.getSchemaCount(),totalRefsCreated:this.refCounter}}};var Qt=o=>{if(Q.isZodSchema(o)){try{let t=Q.toJSONSchema(o);M.storeJsonSchema(t,"serialize_zod"),M.getOrCompileValidator(t,"serialize_zod");}catch(t){E.warn({error:t,schemaType:"zod",context:"serialize_decorator"},"Failed to compile Zod schema for validation. Schema may contain unsupported types (e.g., z.instanceof). Runtime validation will still work, but Swagger documentation may be incomplete.");return}return}if(X.isTypeBoxSchema(o)){try{M.storeJsonSchema(o,"serialize_typebox"),M.getOrCompileValidator(o,"serialize_typebox");}catch(t){E.warn({error:t,schemaType:"typebox",context:"serialize_decorator"},"Failed to compile TypeBox schema for validation. Schema may be invalid or use unsupported features.");return}return}if(typeof o=="object"&&o!==null){try{M.storeJsonSchema(o,"serialize_json"),M.getOrCompileValidator(o,"serialize_json");}catch(t){E.warn({error:t,schemaType:"json",context:"serialize_decorator"},"Failed to compile JSON schema for validation. Schema may be invalid or malformed.");return}return}let e=JSON.stringify(o);try{let t={type:typeof o};M.storeJsonSchema(t,`serialize_primitive_${e}`),M.getOrCompileValidator(t,`serialize_primitive_${e}`);}catch(t){E.warn({error:t,schemaType:"primitive",cacheKey:e,context:"serialize_decorator"},"Failed to compile schema for validation. Schema format may be unsupported.");}},ht=o=>{if(Q.isZodSchema(o)){try{let t=Q.toJSONSchema(o);M.storeJsonSchema(t,"zod_schema"),M.getOrCompileValidator(t,"zod_schema");}catch(t){E.warn({error:t,schemaType:"zod",context:"request_validation"},"Failed to compile Zod schema for request validation. Schema may contain unsupported types (e.g., z.instanceof). Swagger documentation may be incomplete.");return}return}if(X.isTypeBoxSchema(o)){try{M.storeJsonSchema(o,"typebox_schema"),M.getOrCompileValidator(o,"typebox_schema");}catch(t){E.warn({error:t,schemaType:"typebox",context:"request_validation"},"Failed to compile TypeBox schema for request validation. Schema may be invalid or use unsupported features.");return}return}if(typeof o=="object"&&o!==null){try{M.storeJsonSchema(o,"json_schema"),M.getOrCompileValidator(o,"json_schema");}catch(t){E.warn({error:t,schemaType:"json",context:"request_validation"},"Failed to compile JSON schema for request validation. Schema may be invalid or malformed.");return}return}let e=JSON.stringify(o);try{let t={type:typeof o};M.storeJsonSchema(t,`primitive_${e}`),M.getOrCompileValidator(t,`primitive_${e}`);}catch(t){E.warn({error:t,schemaType:"primitive",cacheKey:e,context:"request_validation"},"Failed to compile schema for request validation. Schema format may be unsupported.");}},gt=(o,e)=>{o&&ht(o),e&&ht(e);},ft=o=>{if(!o||Object.keys(o).length===0)return;let e={};for(let[t,r]of Object.entries(o)){let s=Number(t);if(e[s]=r,Qt(r),Q.isZodSchema(r))try{let n=Q.toJSONSchema(r);M.getOrCreateSerializer(n,"fast_stringify_zod");}catch{}else X.isTypeBoxSchema(r)?M.getOrCreateSerializer(r,"fast_stringify_typebox"):typeof r=="object"&&r!==null&&M.getOrCreateSerializer(r,"fast_stringify_json");}return e};var yt=(o,e)=>async function(t,r,...s){try{if(e.body){let n=t.validate(e.body,!0);t.body=n;}if(e.query){let n=t.validateQuery(e.query,!0);t.query=n;}if(e.all){let n=t.validateAll(e.all,!0);t.body=n;}return o(t,r,...s)}catch(n){return r.badRequest(n)}};promisify(gzip);promisify(gunzip);var ve=class{staticChildren;paramChild;wildcardChild;middleware;handler;paramName;constructor(){this.staticChildren=new Map,this.paramChild=null,this.wildcardChild=null,this.middleware=null,this.handler=null,this.paramName=null;}},Ye=class o{trees;routes;middlewares;basePath;staticRouteCache;handlerResponseSchemas;constructor(e="",t=[]){this.trees=new Map,this.routes=[],this.middlewares=t,this.basePath=this.normalizeBasePath(e),this.staticRouteCache=new Map,this.handlerResponseSchemas=new Map;}getRoutes(){return this.routes.slice()}addOrUpdate(e,t,r,s,n,c,a,d=false){e=e.toUpperCase();let u=t.split("?")[0];gt(n?.body,n?.query);let l=ft(a),i=n&&(n.body||n.query||n.all),p=i?yt(s,n):s,h=i?n:void 0,m=this.trees.get(e);m||(m=new ve,this.trees.set(e,m));let g=u.replace(/^\/+|\/+$/g,""),f=g.length===0?[]:g.split("/"),x=true,P=[],T=m;for(let v of f){if(v==="*"){x=false,T.wildcardChild||(T.wildcardChild=new ve),T=T.wildcardChild;break}if(v.startsWith(":")){x=false;let $=v.slice(1);P.push($),T.paramChild||(T.paramChild={node:new ve,name:$}),T=T.paramChild.node;continue}T.staticChildren.has(v)||T.staticChildren.set(v,new ve),T=T.staticChildren.get(v);}if(T.middleware=r,T.handler=p,P.length>0&&(T.paramName=P.join(",")),l&&this.handlerResponseSchemas.set(s,l),x){let v="/"+g,$=`${e}:${v}`;this.staticRouteCache.set($,{middleware:r,handler:p,params:{},responseSchemas:l});}else {let v="/"+g.replace(/:[^/]+/g,"").replace(/\/+/g,"/"),$=`${e}:${v}`;this.staticRouteCache.delete($);}let b=this.routes.findIndex(v=>v.method===e&&v.path===t);if(b!==-1){if(!d)throw new Error(`Duplicate route detected: ${e} ${t} is already registered. Each route must be unique.`);this.routes[b].middleware=r,this.routes[b].handler=p,this.routes[b].swaggerOptions=c,this.routes[b].responses=a,this.routes[b].responseSchemas=l,this.routes[b].validationSchemas=h;return}this.routes.push({method:e,path:t,middleware:r,handler:p,swaggerOptions:c,responses:a,responseSchemas:l,validationSchemas:h});}find(e,t){e=e.toUpperCase();let r=t,s=t.indexOf("?");s!==-1&&(r=t.substring(0,s));let n=`${e}:${r}`,c=this.staticRouteCache.get(n);if(c)return c;let a=this.trees.get(e);if(!a)return null;let d=r.replace(/^\/+|\/+$/g,""),u=d.length===0?[]:d.split("/"),l={},i=a;for(let h=0;h<u.length;h++){let m=u[h];if(i.staticChildren.has(m)){i=i.staticChildren.get(m);continue}if(i.paramChild){l[i.paramChild.name]=m,i=i.paramChild.node;continue}if(i.wildcardChild){l["*"]=u.slice(h).join("/"),i=i.wildcardChild;break}return null}if(!i.handler||!i.middleware)return null;let p=this.handlerResponseSchemas.get(i.handler);return {middleware:i.middleware,handler:i.handler,params:l,responseSchemas:p}}extractOptionsAndHandler(e,t){if(typeof e=="function")return {middlewares:[],handler:e,swaggerOptions:void 0};let r=e,s=Array.isArray(r.middlewares)?r.middlewares:r.middlewares?[r.middlewares]:[];if(r.cache);return {middlewares:s,handler:t,body:r.body,query:r.query,all:r.all,responses:r.responses,swaggerOptions:r.swagger}}get(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:c,body:a,query:d,all:u,responses:l,swaggerOptions:i}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...n],h={body:a,query:d,all:u};this.addOrUpdate("GET",s,p,c,h,i,l);}post(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:c,body:a,query:d,all:u,responses:l,swaggerOptions:i}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...n],h={body:a,query:d,all:u};this.addOrUpdate("POST",s,p,c,h,i,l);}patch(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:c,body:a,query:d,all:u,responses:l,swaggerOptions:i}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...n],h={body:a,query:d,all:u};this.addOrUpdate("PATCH",s,p,c,h,i,l);}put(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:c,body:a,query:d,all:u,responses:l,swaggerOptions:i}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...n],h={body:a,query:d,all:u};this.addOrUpdate("PUT",s,p,c,h,i,l);}delete(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:c,body:a,query:d,all:u,responses:l,swaggerOptions:i}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...n],h={body:a,query:d,all:u};this.addOrUpdate("DELETE",s,p,c,h,i,l);}options(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:c,body:a,query:d,all:u,responses:l,swaggerOptions:i}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...n],h={body:a,query:d,all:u};this.addOrUpdate("OPTIONS",s,p,c,h,i,l);}head(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:c,body:a,query:d,all:u,responses:l,swaggerOptions:i}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...n],h={body:a,query:d,all:u};this.addOrUpdate("HEAD",s,p,c,h,i,l);}group(e,t,r){let s=Array.isArray(t)?t:typeof t=="function"?[]:t?[t]:[],n=Array.isArray(t)?r:typeof t=="function"?t:void 0,c=this.joinPath(e),a=new o(c,[...this.middlewares,...s]);n?.(a);for(let d of a.getRoutes())this.addOrUpdate(d.method,d.path,d.middleware,d.handler,d.validationSchemas,d.swaggerOptions,d.responses);}applyGlobalMiddlewaresToAllRoutes(e){for(let t of this.routes){let r=[...e,...t.middleware||[]];this.addOrUpdate(t.method,t.path,r,t.handler,void 0,void 0,void 0,true);}}normalizeBasePath(e){if(!e)return "";let t=e.replace(/\s+/g,"");return t=t.replace(/\/+/g,"/"),t.startsWith("/")||(t="/"+t),t.length>1&&(t=t.replace(/\/+$/g,"")),t}joinPath(e){let r=[this.basePath,e].filter(s=>typeof s=="string"&&s.length>0).join("/");return r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r.length>1&&(r=r.replace(/\/+$/g,"")),r}clearRoutes(){this.routes=[],this.staticRouteCache.clear(),this.handlerResponseSchemas.clear(),this.trees.clear();}};new Ye;var G=class{static scheduledJobs=[];static logger=E.child({scope:"CronService"});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 F("node-cron not installed as a dependency, it is required in order to run cron jobs with the @cron decorator")})).default;if(this.logger.info("Scheduling cron jobs"),!this.scheduledJobs.length){this.logger.info("No cron jobs to schedule");return}for(let{name:t,args:r}of this.scheduledJobs)this.logger.info(`Scheduling cron job: ${t}`),e.schedule(...r).on("execution:failed",n=>this.globalErrorHandler(n));this.logger.info("Cron jobs scheduled");}static globalErrorHandler(e){this.logger.error(e.execution?.error);}static async massiveImportCronJobs(e){let t=[];for(let r of e){let s=await y.glob(r,{cwd:N.getCwd()});t.push(...s);}await Promise.all(t.map(async r=>{await import(r).catch(s=>{this.logger.error(`Error importing cron job: ${r}`),E.error(s);});}));}};var re=class extends q{static commandName="cron-start";static description="Start cron job scheduler";static help=["Start the cron job scheduler to run scheduled tasks","Loads cron jobs from specified patterns and starts scheduling","Example: npx balda cron-start","Example: npx balda cron-start src/crons/**/*.ts --patterns src/schedules/**/*.ts"];static options={keepAlive:true};static pattern;static additionalPatterns;static async handle(){this.logger.info("Starting cron scheduler...");let e=[this.pattern];this.additionalPatterns&&this.additionalPatterns.length>0&&e.push(...this.additionalPatterns),this.logger.info(`Loading cron jobs from patterns: ${e.join(", ")}`),await G.massiveImportCronJobs(e);let t=G.scheduledJobs.length;if(t===0){this.logger.warn("No cron jobs found. Make sure your cron jobs are decorated with @cron decorator");return}this.logger.info(`Found ${t} cron job(s)`),G.run().then(()=>{this.logger.info("Cron scheduler started successfully. Press Ctrl+C to stop.");}).catch(r=>{this.logger.error("Error starting cron scheduler",r);});}};S([R({required:false,defaultValue:"src/crons/**/*.{ts,js}",description:"Primary glob pattern for cron jobs (default: src/crons/**/*.{ts,js})"})],re,"pattern"),S([C.array({aliases:["p"],name:"patterns",required:false,description:"Additional glob patterns for cron jobs"})],re,"additionalPatterns");var we=class extends q{static commandName="generate-command";static description="Generate a new command in the specified path";static help=["Generate a new cli command in the specified path","Example: npx balda generate-command my-command -p src/commands"];static path="src/commands";static name;static async handle(){if(D.getCommand(this.name)){let s=D.isBuiltInCommand(this.name)?"built-in":"user-defined";this.logger.error({commandName:this.name,type:s},`Command "${this.name}" already exists as a ${s} command. Cannot override existing commands.`);return}let t=this.getCommandTemplate();this.path=w.join(this.path,`${this.name}.ts`),await y.exists(w.join(process.cwd(),this.path))||await y.mkdir(w.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await y.writeFile(this.path,new TextEncoder().encode(t)),this.logger.info(`Command ${this.name} created successfully at ${this.path}`);}static getCommandTemplate(){return `import { Command, CommandOptions } from "balda";
7
+ Zod is a peer dependency required when using Zod schemas for validation.`)}}static get(){return this.load()}static isZodSchema(e){try{this.load();}catch{return false}if(typeof e!="object"||e===null)return false;if(this.zodSchemaCache.has(e))return true;let t="_def"in e&&typeof e.parse=="function"&&typeof e.safeParse=="function";return t&&this.zodSchemaCache.add(e),t}static ensureZodV4(){let e=this.zodModule?.z;if(!e)throw new be;if(!("toJSONSchema"in e))throw new be}static toJSONSchema(e){this.load(),this.ensureZodV4();let t=this.zodModule?.z;if(!t?.toJSONSchema)throw new be;if(!e||typeof e!="object"||!("_def"in e))throw new Error(`Invalid Zod schema provided. Make sure you're using Zod v4 schemas. If you're importing from 'zod/v3', change to 'zod' or '{ z } from "zod"'.`);try{return t.toJSONSchema(e)}catch(r){throw r instanceof Error&&r.message.includes("Cannot read properties of undefined")?new Ne(r):r}}};var _e=class extends F{constructor(){super("TypeBox is not installed. Install it with: npm install @sinclair/typebox");}};var G=class{static typeboxModule=null;static typeboxSchemaCache=new WeakSet;static load(){if(this.typeboxModule)return this.typeboxModule;try{return this.typeboxModule=ke("@sinclair/typebox"),this.typeboxModule}catch{throw new _e}}static get(){return this.load()}static isTypeBoxSchema(e){try{this.load();}catch{return false}if(typeof e!="object"||e===null)return false;if(this.typeboxSchemaCache.has(e))return true;let t="type"in e&&Object.getOwnPropertySymbols(e).some(r=>r.toString()==="Symbol(TypeBox.Kind)");return t&&this.typeboxSchemaCache.add(e),t}};function Se(o){if(!o||typeof o!="object")return o;let e;if(o.properties&&typeof o.properties=="object"){e={...o,additionalProperties:false};let t=o.properties,r={},s=false;for(let n in t){let c=t[n];if(c&&typeof c=="object"&&!("$ref"in c)){let a=Se(c);a!==c&&(s=true),r[n]=a;}else r[n]=c;}s&&(e.properties=r);}if(o.items&&typeof o.items=="object"&&!("$ref"in o.items)){let t=Se(o.items);t!==o.items&&(e=e??{...o},e.items=t);}for(let t of ["oneOf","anyOf","allOf"]){let r=o[t];if(Array.isArray(r)){let s=[],n=false;for(let c of r)if(c&&typeof c=="object"&&!("$ref"in c)){let a=Se(c);a!==c&&(n=true),s.push(a);}else s.push(c);n&&(e=e??{...o},e[t]=s);}}for(let t of ["$defs","definitions"]){let r=o[t];if(r&&typeof r=="object"){let s={},n=false;for(let c in r){let a=r[c];if(a&&typeof a=="object"){let d=Se(a);d!==a&&(n=true),s[c]=d;}else s[c]=a;}n&&(e=e??{...o},e[t]=s);}}return e??o}var M=class{static ajv=new Ajv({validateSchema:false,strict:false});static serializerCache=new WeakMap;static responseSerializersCache=new WeakMap;static refCounter=0;static schemaKeyCache=new WeakMap;static setGlobalInstance(e){this.ajv=e,this.ajv.opts.strict=false,this.ajv.opts.validateSchema=false;}static getSchemaKey(e,t){let r=this.schemaKeyCache.get(e);r||(r=new Map,this.schemaKeyCache.set(e,r));let s=r.get(t);return s||(s=`${t}_${++this.refCounter}`,r.set(t,s)),s}static getOrCompileValidator(e,t){let r=this.getSchemaKey(e,t),s=this.ajv.getSchema(r);if(s)return s;this.ajv.addSchema(e,r);let n=this.ajv.getSchema(r);if(!n)throw new Error(`Failed to compile schema with key: ${r}`);return n}static getOrCreateSerializer(e,t){if(!e||typeof e!="object")return null;let r=this.serializerCache.get(e);r||(r=new Map,this.serializerCache.set(e,r));let s=r.get(t);if(s)return s;try{let n=Se(e),c=Bt(n,{ajv:this.ajv.opts});return r.set(t,c),c}catch{return null}}static getOrCreateResponseSerializers(e){if(!e)return null;let t=this.responseSerializersCache.get(e);if(t)return t;let r=new Map;for(let[s,n]of Object.entries(e)){let c=Number(s),a=null;if(Q.isZodSchema(n)){let d=Q.toJSONSchema(n);a=this.getOrCreateSerializer(d,"fast_stringify_zod");}else G.isTypeBoxSchema(n)?a=this.getOrCreateSerializer(n,"fast_stringify_typebox"):typeof n=="object"&&n!==null&&(a=this.getOrCreateSerializer(n,"fast_stringify_json"));a&&r.set(c,a);}return this.responseSerializersCache.set(e,r),r}static storeJsonSchema(e,t){let r=this.getSchemaKey(e,t);this.ajv.getSchema(r)||this.ajv.addSchema(e,r);}static getJsonSchema(e,t){let r=this.schemaKeyCache.get(e);if(!r)return;let s=r.get(t);return s?this.ajv.getSchema(s)?.schema:void 0}static clearAllCaches(){this.ajv=new Ajv({validateSchema:false,strict:false}),this.serializerCache=new WeakMap,this.schemaKeyCache=new WeakMap,this.refCounter=0;}static getSchemaCount(){return Object.keys(this.ajv.schemas).length}static getCacheStats(){return {schemaCount:this.getSchemaCount(),totalRefsCreated:this.refCounter}}};var Qt=o=>{if(Q.isZodSchema(o)){try{let t=Q.toJSONSchema(o);M.storeJsonSchema(t,"serialize_zod"),M.getOrCompileValidator(t,"serialize_zod");}catch(t){E.warn({error:t,schemaType:"zod",context:"serialize_decorator"},"Failed to compile Zod schema for validation. Schema may contain unsupported types (e.g., z.instanceof). Runtime validation will still work, but Swagger documentation may be incomplete.");return}return}if(G.isTypeBoxSchema(o)){try{M.storeJsonSchema(o,"serialize_typebox"),M.getOrCompileValidator(o,"serialize_typebox");}catch(t){E.warn({error:t,schemaType:"typebox",context:"serialize_decorator"},"Failed to compile TypeBox schema for validation. Schema may be invalid or use unsupported features.");return}return}if(typeof o=="object"&&o!==null){try{M.storeJsonSchema(o,"serialize_json"),M.getOrCompileValidator(o,"serialize_json");}catch(t){E.warn({error:t,schemaType:"json",context:"serialize_decorator"},"Failed to compile JSON schema for validation. Schema may be invalid or malformed.");return}return}let e=JSON.stringify(o);try{let t={type:typeof o};M.storeJsonSchema(t,`serialize_primitive_${e}`),M.getOrCompileValidator(t,`serialize_primitive_${e}`);}catch(t){E.warn({error:t,schemaType:"primitive",cacheKey:e,context:"serialize_decorator"},"Failed to compile schema for validation. Schema format may be unsupported.");}},ht=o=>{if(Q.isZodSchema(o)){try{let t=Q.toJSONSchema(o);M.storeJsonSchema(t,"zod_schema"),M.getOrCompileValidator(t,"zod_schema");}catch(t){E.warn({error:t,schemaType:"zod",context:"request_validation"},"Failed to compile Zod schema for request validation. Schema may contain unsupported types (e.g., z.instanceof). Swagger documentation may be incomplete.");return}return}if(G.isTypeBoxSchema(o)){try{M.storeJsonSchema(o,"typebox_schema"),M.getOrCompileValidator(o,"typebox_schema");}catch(t){E.warn({error:t,schemaType:"typebox",context:"request_validation"},"Failed to compile TypeBox schema for request validation. Schema may be invalid or use unsupported features.");return}return}if(typeof o=="object"&&o!==null){try{M.storeJsonSchema(o,"json_schema"),M.getOrCompileValidator(o,"json_schema");}catch(t){E.warn({error:t,schemaType:"json",context:"request_validation"},"Failed to compile JSON schema for request validation. Schema may be invalid or malformed.");return}return}let e=JSON.stringify(o);try{let t={type:typeof o};M.storeJsonSchema(t,`primitive_${e}`),M.getOrCompileValidator(t,`primitive_${e}`);}catch(t){E.warn({error:t,schemaType:"primitive",cacheKey:e,context:"request_validation"},"Failed to compile schema for request validation. Schema format may be unsupported.");}},gt=(o,e)=>{o&&ht(o),e&&ht(e);},ft=o=>{if(!o||Object.keys(o).length===0)return;let e={};for(let[t,r]of Object.entries(o)){let s=Number(t);if(e[s]=r,Qt(r),Q.isZodSchema(r))try{let n=Q.toJSONSchema(r);M.getOrCreateSerializer(n,"fast_stringify_zod");}catch{}else G.isTypeBoxSchema(r)?M.getOrCreateSerializer(r,"fast_stringify_typebox"):typeof r=="object"&&r!==null&&M.getOrCreateSerializer(r,"fast_stringify_json");}return e};var yt=(o,e)=>async function(t,r,...s){try{if(e.body){let n=t.validate(e.body,!0);t.body=n;}if(e.query){let n=t.validateQuery(e.query,!0);t.query=n;}if(e.all){let n=t.validateAll(e.all,!0);t.body=n;}return o(t,r,...s)}catch(n){return r.badRequest(n)}};promisify(gzip);promisify(gunzip);var ve=class{staticChildren;paramChild;wildcardChild;middleware;handler;paramName;constructor(){this.staticChildren=new Map,this.paramChild=null,this.wildcardChild=null,this.middleware=null,this.handler=null,this.paramName=null;}},Ye=class o{trees;routes;middlewares;basePath;staticRouteCache;handlerResponseSchemas;constructor(e="",t=[]){this.trees=new Map,this.routes=[],this.middlewares=t,this.basePath=this.normalizeBasePath(e),this.staticRouteCache=new Map,this.handlerResponseSchemas=new Map;}getRoutes(){return this.routes.slice()}addOrUpdate(e,t,r,s,n,c,a,d=false){e=e.toUpperCase();let u=t.split("?")[0];gt(n?.body,n?.query);let l=ft(a),i=n&&(n.body||n.query||n.all),p=i?yt(s,n):s,h=i?n:void 0,m=this.trees.get(e);m||(m=new ve,this.trees.set(e,m));let g=u.replace(/^\/+|\/+$/g,""),f=g.length===0?[]:g.split("/"),x=true,P=[],T=m;for(let v of f){if(v==="*"){x=false,T.wildcardChild||(T.wildcardChild=new ve),T=T.wildcardChild;break}if(v.startsWith(":")){x=false;let $=v.slice(1);P.push($),T.paramChild||(T.paramChild={node:new ve,name:$}),T=T.paramChild.node;continue}T.staticChildren.has(v)||T.staticChildren.set(v,new ve),T=T.staticChildren.get(v);}if(T.middleware=r,T.handler=p,P.length>0&&(T.paramName=P.join(",")),l&&this.handlerResponseSchemas.set(s,l),x){let v="/"+g,$=`${e}:${v}`;this.staticRouteCache.set($,{middleware:r,handler:p,params:{},responseSchemas:l});}else {let v="/"+g.replace(/:[^/]+/g,"").replace(/\/+/g,"/"),$=`${e}:${v}`;this.staticRouteCache.delete($);}let b=this.routes.findIndex(v=>v.method===e&&v.path===t);if(b!==-1){if(!d)throw new Error(`Duplicate route detected: ${e} ${t} is already registered. Each route must be unique.`);this.routes[b].middleware=r,this.routes[b].handler=p,this.routes[b].swaggerOptions=c,this.routes[b].responses=a,this.routes[b].responseSchemas=l,this.routes[b].validationSchemas=h;return}this.routes.push({method:e,path:t,middleware:r,handler:p,swaggerOptions:c,responses:a,responseSchemas:l,validationSchemas:h});}find(e,t){e=e.toUpperCase();let r=t,s=t.indexOf("?");s!==-1&&(r=t.substring(0,s));let n=`${e}:${r}`,c=this.staticRouteCache.get(n);if(c)return c;let a=this.trees.get(e);if(!a)return null;let d=r.replace(/^\/+|\/+$/g,""),u=d.length===0?[]:d.split("/"),l={},i=a;for(let h=0;h<u.length;h++){let m=u[h];if(i.staticChildren.has(m)){i=i.staticChildren.get(m);continue}if(i.paramChild){l[i.paramChild.name]=m,i=i.paramChild.node;continue}if(i.wildcardChild){l["*"]=u.slice(h).join("/"),i=i.wildcardChild;break}return null}if(!i.handler||!i.middleware)return null;let p=this.handlerResponseSchemas.get(i.handler);return {middleware:i.middleware,handler:i.handler,params:l,responseSchemas:p}}extractOptionsAndHandler(e,t){if(typeof e=="function")return {middlewares:[],handler:e,swaggerOptions:void 0};let r=e,s=Array.isArray(r.middlewares)?r.middlewares:r.middlewares?[r.middlewares]:[];if(r.cache);return {middlewares:s,handler:t,body:r.body,query:r.query,all:r.all,responses:r.responses,swaggerOptions:r.swagger}}get(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:c,body:a,query:d,all:u,responses:l,swaggerOptions:i}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...n],h={body:a,query:d,all:u};this.addOrUpdate("GET",s,p,c,h,i,l);}post(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:c,body:a,query:d,all:u,responses:l,swaggerOptions:i}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...n],h={body:a,query:d,all:u};this.addOrUpdate("POST",s,p,c,h,i,l);}patch(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:c,body:a,query:d,all:u,responses:l,swaggerOptions:i}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...n],h={body:a,query:d,all:u};this.addOrUpdate("PATCH",s,p,c,h,i,l);}put(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:c,body:a,query:d,all:u,responses:l,swaggerOptions:i}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...n],h={body:a,query:d,all:u};this.addOrUpdate("PUT",s,p,c,h,i,l);}delete(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:c,body:a,query:d,all:u,responses:l,swaggerOptions:i}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...n],h={body:a,query:d,all:u};this.addOrUpdate("DELETE",s,p,c,h,i,l);}options(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:c,body:a,query:d,all:u,responses:l,swaggerOptions:i}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...n],h={body:a,query:d,all:u};this.addOrUpdate("OPTIONS",s,p,c,h,i,l);}head(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:c,body:a,query:d,all:u,responses:l,swaggerOptions:i}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...n],h={body:a,query:d,all:u};this.addOrUpdate("HEAD",s,p,c,h,i,l);}group(e,t,r){let s=Array.isArray(t)?t:typeof t=="function"?[]:t?[t]:[],n=Array.isArray(t)?r:typeof t=="function"?t:void 0,c=this.joinPath(e),a=new o(c,[...this.middlewares,...s]);n?.(a);for(let d of a.getRoutes())this.addOrUpdate(d.method,d.path,d.middleware,d.handler,d.validationSchemas,d.swaggerOptions,d.responses);}applyGlobalMiddlewaresToAllRoutes(e){for(let t of this.routes){let r=[...e,...t.middleware||[]];this.addOrUpdate(t.method,t.path,r,t.handler,void 0,void 0,void 0,true);}}normalizeBasePath(e){if(!e)return "";let t=e.replace(/\s+/g,"");return t=t.replace(/\/+/g,"/"),t.startsWith("/")||(t="/"+t),t.length>1&&(t=t.replace(/\/+$/g,"")),t}joinPath(e){let r=[this.basePath,e].filter(s=>typeof s=="string"&&s.length>0).join("/");return r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r.length>1&&(r=r.replace(/\/+$/g,"")),r}clearRoutes(){this.routes=[],this.staticRouteCache.clear(),this.handlerResponseSchemas.clear(),this.trees.clear();}};new Ye;var X=class{static scheduledJobs=[];static logger=E.child({scope:"CronService"});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 F("node-cron not installed as a dependency, it is required in order to run cron jobs with the @cron decorator")})).default;if(this.logger.info("Scheduling cron jobs"),!this.scheduledJobs.length){this.logger.info("No cron jobs to schedule");return}for(let{name:t,args:r}of this.scheduledJobs)this.logger.info(`Scheduling cron job: ${t}`),e.schedule(...r).on("execution:failed",n=>this.globalErrorHandler(n));this.logger.info("Cron jobs scheduled");}static globalErrorHandler(e){this.logger.error(e.execution?.error);}static async massiveImportCronJobs(e){let t=[];for(let r of e){let s=await y.glob(r,{cwd:N.getCwd()});t.push(...s);}await Promise.all(t.map(async r=>{await import(r).catch(s=>{this.logger.error(`Error importing cron job: ${r}`),E.error(s);});}));}};var re=class extends q{static commandName="cron-start";static description="Start cron job scheduler";static help=["Start the cron job scheduler to run scheduled tasks","Loads cron jobs from specified patterns and starts scheduling","Example: npx balda cron-start","Example: npx balda cron-start src/crons/**/*.ts --patterns src/schedules/**/*.ts"];static options={keepAlive:true};static pattern;static additionalPatterns;static async handle(){this.logger.info("Starting cron scheduler...");let e=[this.pattern];this.additionalPatterns&&this.additionalPatterns.length>0&&e.push(...this.additionalPatterns),this.logger.info(`Loading cron jobs from patterns: ${e.join(", ")}`),await X.massiveImportCronJobs(e);let t=X.scheduledJobs.length;if(t===0){this.logger.warn("No cron jobs found. Make sure your cron jobs are decorated with @cron decorator");return}this.logger.info(`Found ${t} cron job(s)`),X.run().then(()=>{this.logger.info("Cron scheduler started successfully. Press Ctrl+C to stop.");}).catch(r=>{this.logger.error("Error starting cron scheduler",r);});}};S([R({required:false,defaultValue:"src/crons/**/*.{ts,js}",description:"Primary glob pattern for cron jobs (default: src/crons/**/*.{ts,js})"})],re,"pattern"),S([C.array({aliases:["p"],name:"patterns",required:false,description:"Additional glob patterns for cron jobs"})],re,"additionalPatterns");var we=class extends q{static commandName="generate-command";static description="Generate a new command in the specified path";static help=["Generate a new cli command in the specified path","Example: npx balda generate-command my-command -p src/commands"];static path="src/commands";static name;static async handle(){if(D.getCommand(this.name)){let s=D.isBuiltInCommand(this.name)?"built-in":"user-defined";this.logger.error({commandName:this.name,type:s},`Command "${this.name}" already exists as a ${s} command. Cannot override existing commands.`);return}let t=this.getCommandTemplate();this.path=w.join(this.path,`${this.name}.ts`),await y.exists(w.join(process.cwd(),this.path))||await y.mkdir(w.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await y.writeFile(this.path,new TextEncoder().encode(t)),this.logger.info(`Command ${this.name} created successfully at ${this.path}`);}static getCommandTemplate(){return `import { Command, CommandOptions } from "balda";
8
8
 
9
9
  export default class extends Command {
10
10
  static commandName = "${this.name}";
@@ -499,7 +499,7 @@ definePGBossConfiguration({
499
499
  * console.log("Processing:", payload);
500
500
  * });
501
501
  */
502
- `}};S([C.string({description:"Queue provider type (bullmq, sqs, pgboss) - required",aliases:"t",name:"type",required:true})],ce,"queueType"),S([C.string({description:"Output directory for queue configuration, default is src/queue",aliases:"o",name:"output",required:false,defaultValue:"src/queue"})],ce,"outputPath");var xe=class extends q{static commandName="key-generate";static description="Generate application encryption key pairs";static help=["Generate secure RSA public/private key pairs for application encryption","Keys are automatically saved to .env file","Example: npx balda key-generate","Example: npx balda key-generate --type async"];static type;static async handle(){let e=this.type??"sync";if(!["sync","async"].includes(e)){this.logger.error(`Invalid key type: ${e}. Must be sync or async`);return}let{publicKey:t,privateKey:r}=Gt.generateKeyPairSync("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}}),s=e==="sync"?"APP_PUBLIC_KEY":"APP_PUBLIC_KEY_ASYNC",n=e==="sync"?"APP_PRIVATE_KEY":"APP_PRIVATE_KEY_ASYNC";console.log(`
502
+ `}};S([C.string({description:"Queue provider type (bullmq, sqs, pgboss) - required",aliases:"t",name:"type",required:true})],ce,"queueType"),S([C.string({description:"Output directory for queue configuration, default is src/queue",aliases:"o",name:"output",required:false,defaultValue:"src/queue"})],ce,"outputPath");var xe=class extends q{static commandName="key-generate";static description="Generate application encryption key pairs";static help=["Generate secure RSA public/private key pairs for application encryption","Keys are automatically saved to .env file","Example: npx balda key-generate","Example: npx balda key-generate --type async"];static type;static async handle(){let e=this.type??"sync";if(!["sync","async"].includes(e)){this.logger.error(`Invalid key type: ${e}. Must be sync or async`);return}let{publicKey:t,privateKey:r}=Xt.generateKeyPairSync("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}}),s=e==="sync"?"APP_PUBLIC_KEY":"APP_PUBLIC_KEY_ASYNC",n=e==="sync"?"APP_PRIVATE_KEY":"APP_PRIVATE_KEY_ASYNC";console.log(`
503
503
  \u2728 Generated ${e==="sync"?"Sync":"Async"} Key Pair:
504
504
  `),console.log(`\x1B[33mPublic Key (${s}):\x1B[0m`),console.log(`\x1B[32m${t}\x1B[0m`),console.log(`\x1B[33mPrivate Key (${n}):\x1B[0m`),console.log(`\x1B[32m${r}\x1B[0m`),await this.saveKeyToEnvFile(s,t),await this.saveKeyToEnvFile(n,r),console.log(`\x1B[90m\u{1F4A1} Keys saved to .env file as ${s} and ${n}\x1B[0m
505
505
  `);}static async saveKeyToEnvFile(e,t){let r=Ae.join(N.getCwd(),".env"),s=`${e}="${t}"`;if(Ce.existsSync(r)){let n=Ce.readFileSync(r,"utf-8"),c=new RegExp(`^${e}=.*$`,"m");if(c.test(n)){let a=n.replace(c,s);Ce.writeFileSync(r,a),this.logger.info(`Updated ${e} in .env file`);return}Ce.appendFileSync(r,`