balda-js 0.0.63 → 0.0.65

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,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import {glob}from'glob';import ce from'pino';import z from'path';import {execSync}from'child_process';import M from'fs';var ne=Object.defineProperty;var m=(r,e,t,s)=>{for(var i=void 0,a=r.length-1,o;a>=0;a--)(o=r[a])&&(i=(o(e,t,i))||i);return i&&ne(e,t,i),i};var V=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")}},f=new V;var _=class{getCliArgs(){switch(f.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 s=e[t],i=s.split("/").pop()||s;if(!s.startsWith("-")){if(i==="yarn"&&t+1<e.length&&e[t+1]==="run"||i==="npx"&&t+1<e.length)return t+1;if(i==="yarn"||i==="pnpm")return t;if(i==="npm"&&t+1<e.length&&e[t+1]==="run"||i==="bun"&&t+1<e.length&&e[t+1]==="run")return t+1;if(/\.(js|ts|mjs|cjs)$/.test(s))return t;if(/^(tsx|ts-node|node|bun)$/.test(i)){for(let a=t+1;a<e.length;a++)if(!e[a].startsWith("-")&&/\.(js|ts|mjs|cjs)$/.test(e[a]))return a;return t}}}for(let t=e.length-1;t>=0;t--)if(!e[t].startsWith("-"))return t;return 1}},E=new _;var G=(r,e)=>{let t=Array(e.length+1).fill(null).map(()=>Array(r.length+1).fill(null));for(let s=0;s<=r.length;s++)t[0][s]=s;for(let s=0;s<=e.length;s++)t[s][0]=s;for(let s=1;s<=e.length;s++)for(let i=1;i<=r.length;i++){let a=r[i-1]===e[s-1]?0:1;t[s][i]=Math.min(t[s][i-1]+1,t[s-1][i]+1,t[s-1][i-1]+a);}return t[e.length][r.length]},Q=r=>r.toLowerCase().replace(/[-_.]/g,"_").replace(/([A-Z])/g,"_$1").replace(/^_+/,"").replace(/_+$/,"").toLowerCase();var oe=r=>{if(!r||r==="-"||r==="--")return null;let e=r.indexOf("=");if(e>0){let t=r.substring(0,e),s=r.substring(e+1);return {name:t,value:X(s)}}return {name:r,value:true}},X=r=>{if(r.toLowerCase()==="true")return true;if(r.toLowerCase()==="false")return false;let e=Number(r);return !Number.isNaN(e)&&Number.isFinite(e)?e:r},N=()=>{let r=E.getCliArgs(),e=[],t={};if(!r||!r.length)return {args:e,flags:t};for(let s=0;s<r.length;s++){let i=r[s];if(!(!i||typeof i!="string")){if(i.startsWith("-")){let a=oe(i);if(a){if(a.value===true&&s+1<r.length){let o=r[s+1];o&&typeof o=="string"&&!o.startsWith("-")&&(a.value=X(o),s++);}t[a.name]=a.value;}continue}e.push(i);}}return {args:e,flags:t}},K=(r,e)=>{if(!r||typeof r!="string"||!e||!Array.isArray(e)||e.length===0)return "";let t=r.toLowerCase().trim(),s=e.filter(o=>{let h=o.toLowerCase();if(h===t||h.includes(t)||t.includes(h))return true;let p=G(h,t),n=Math.max(t.length,h.length)*.4;return p<=n});if(s.length===0)return "";let a=s.slice(0,3).map(o=>`\x1B[36m${o}\x1B[0m`).join(", ");return `\x1B[31m\u2717\x1B[0m Command \x1B[33m${r}\x1B[0m not found
3
- \x1B[32m\u{1F4A1}\x1B[0m Did you mean: ${a}?`},I=()=>E.getCliArgs()[0]||null;var B=class{exit(e){switch(f.type){case "bun":case "node":process.exit(e);case "deno":Deno.exit(e);default:throw new Error("Unsupported runtime")}}},v=new B;var x=class{static metadata=new WeakMap;static set(e,t,s){this.metadata.has(e)||this.metadata.set(e,new Map),this.metadata.get(e).set(t,s);}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 k="VALIDATION_ERROR";var ee=N().args.slice(1),j=r=>(e,t)=>{let s=I();if(!s||s!==e.commandName)return;let i=t;x.set(e,t,{type:"arg",name:i,description:r.description});let a=ee.length?ee.shift():r.defaultValue;if(r.required&&!a){let o=x.get(e,k);x.set(e,k,[...o||[],{type:"arg",name:i,message:"Required argument not provided"}]);return}r.parse&&a&&(a=r.parse(a)),Object.defineProperty(e,t,{value:a,enumerable:true,configurable:true,writable:true});};var le=()=>ce({level:"info",formatters:{level:e=>({level:e})}}),R=le();var y=class{static commandName=this.name;static description="";static help=[];static options={keepAlive:false};static args=N().args.slice(1);static flags=N().flags;static logger=R;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(n=>t.includes(n)))return;let i=this.commandName,a=this.description||"No description available",o=this.help||[],h=this.options,p=this.generateHelpOutput({name:i,description:a,helpText:o,options:h,args:this.args,flags:this.flags},this);console.log(p),v.exit(0);}static generateHelpOutput=(e,t)=>{let{name:s,description:i,helpText:a,options:o,args:h,flags:p}=e,n={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"},u=[`${n.title}${s}${n.reset}`,`${n.description}${i}${n.reset}`,"",`${n.subtitle}Usage:${n.reset}`,` ${n.code}${s}${n.reset} [options] [arguments]`,"",`${n.subtitle}Options:${n.reset}`,` ${n.flag}-h, --help${n.reset} Show this help message`,"",`${n.subtitle}Command Options:${n.reset}`,` ${n.flag}keepAlive${n.reset} ${o?.keepAlive??false?n.success+"Enabled"+n.reset:n.error+"Disabled"+n.reset}`,""];if(a){let c=Array.isArray(a)?a:[a];u.push(`${n.subtitle}Help:${n.reset}`),c.forEach(b=>{u.push(` ${n.description}${b}${n.reset}`);}),u.push("");}let O=x.getAll(t),J=Array.from(O.values()).filter(c=>c.type==="arg"),Z=Array.from(O.values()).filter(c=>c.type==="flag");return J.length&&(u.push(`${n.subtitle}Available Arguments:${n.reset}`),J.forEach(c=>{let b=c.required?` ${n.error}(required)${n.reset}`:"",D=c.description?` ${n.description}${c.description}${n.reset}`:"";u.push(` ${n.code}${c.name}${n.reset}${b}${D}`);}),u.push("")),Z.length&&(u.push(`${n.subtitle}Available Flags:${n.reset}`),Z.forEach(c=>{c.aliases&&!Array.isArray(c.aliases)&&(c.aliases=[c.aliases]);let b=c.aliases.length?` ${n.flag}(${c.aliases.join(", ")})${n.reset}`:"",D=c.required?` ${n.error}(required)${n.reset}`:"",ie=c.description?` ${n.description}${c.description}${n.reset}`:"";u.push(` ${n.flag}--${c.name}${b}${n.reset}${D}${ie}`);}),u.push("")),((h?.length??0)>0||p&&Object.keys(p).length>0)&&(u.push(`${n.subtitle}Current Context:${n.reset}`),h?.length&&u.push(` ${n.info}Provided Arguments:${n.reset} ${n.code}${h.join(" ")}${n.reset}`),p&&Object.keys(p).length>0&&(u.push(` ${n.info}Provided Flags:${n.reset}`),Object.keys(p).forEach(c=>{let b=p[c],D=b!=null?` = ${n.code}${b}${n.reset}`:"";u.push(` ${n.flag}${c}${n.reset}${D}`);})),u.push("")),a&&(Array.isArray(a)?a.some(c=>c.includes("example")):a.includes("example"))&&(u.push(`${n.subtitle}Examples:${n.reset}`),(Array.isArray(a)?a.filter(b=>b.includes("example")):[a.split("example")[1].trim()]).forEach(b=>{u.push(` ${n.code}${b}${n.reset}`);}),u.push("")),u.join(`
4
- `)};static validateContext=e=>{let t=Array.from(x.get(e,k)||[]);if(t.length){let s={error:"\x1B[0;31m",title:"\x1B[1;31m",reset:"\x1B[0m",info:"\x1B[0;34m",code:"\x1B[0;32m"};console.error(`${s.title}\u274C Validation Errors:${s.reset}`),console.error(""),t.forEach((i,a)=>{let o=`${s.info}${a+1}.${s.reset}`,h=`${s.error}${i.type.toUpperCase()}${s.reset}`,p=`${s.code}${i.name}${s.reset}`;console.error(` ${o} ${h} ${p}: ${s.error}${i.message}${s.reset}`);}),console.error(""),console.error(`${s.info}\u{1F4A1} Tip: Use --help for usage information${s.reset}`),v.exit(1);}}};var U=class{async mkdir(e,t){switch(f.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(f.type){case "node":return (await import('fs')).existsSync(e);case "bun":return Bun.file(e).exists();case "deno":return Deno.stat(e).then(()=>true).catch(()=>false);default:throw new Error("Unsupported runtime")}}async readFile(e){switch(f.type){case "node":let s=await(await import('fs/promises')).readFile(e);return new Uint8Array(s);case "bun":let i=await Bun.file(e).arrayBuffer();return new Uint8Array(i);case "deno":return new Uint8Array(await Deno.readFile(e))}}async writeFile(e,t){switch(f.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(f.type){case "node":let s=await(await import('fs/promises')).stat(e);return {isDirectory:s.isDirectory(),isFile:s.isFile(),isSymbolicLink:s.isSymbolicLink(),size:s.size};case "bun":let i=await Bun.file(e).stat();return {isDirectory:i.isDirectory(),isFile:i.isFile(),isSymbolicLink:i.isSymbolicLink(),size:i.size};case "deno":let a=await Deno.stat(e);return {isDirectory:a.isDirectory,isFile:a.isFile,isSymbolicLink:false,size:a.size}}}async unlink(e){switch(f.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")}}},l=new U;var W=class{join(...e){switch(f.type){case "node":case "bun":case "deno":return z.join(...e);default:throw new Error("Unsupported runtime")}}extName(e){switch(f.type){case "bun":case "node":case "deno":return z.extname(e);default:throw new Error("Unsupported runtime")}}resolve(...e){switch(f.type){case "bun":case "node":case "deno":return z.resolve(...e);default:throw new Error("Unsupported runtime")}}},d=new W;var S=class extends y{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=d.join(this.path,`${this.name}.ts`),await l.exists(d.join(process.cwd(),this.path))||await l.mkdir(d.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await l.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";
2
+ import {glob}from'glob';import ce from'pino';import z from'path';import {execSync}from'child_process';import M from'fs';var ne=Object.defineProperty;var p=(r,e,t,s)=>{for(var i=void 0,a=r.length-1,o;a>=0;a--)(o=r[a])&&(i=(o(e,t,i))||i);return i&&ne(e,t,i),i};var V=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")}},h=new V;var B=class{getCliArgs(){switch(h.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 s=e[t],i=s.split("/").pop()||s;if(!s.startsWith("-")){if(i==="yarn"&&t+1<e.length&&e[t+1]==="run"||i==="npx"&&t+1<e.length)return t+1;if(i==="yarn"||i==="pnpm")return t;if(i==="npm"&&t+1<e.length&&e[t+1]==="run"||i==="bun"&&t+1<e.length&&e[t+1]==="run")return t+1;if(/\.(js|ts|mjs|cjs)$/.test(s))return t;if(/^(tsx|ts-node|node|bun)$/.test(i)){for(let a=t+1;a<e.length;a++)if(!e[a].startsWith("-")&&/\.(js|ts|mjs|cjs)$/.test(e[a]))return a;return t}}}for(let t=e.length-1;t>=0;t--)if(!e[t].startsWith("-"))return t;return 1}},D=new B;var Z=(r,e)=>{let t=Array(e.length+1).fill(null).map(()=>Array(r.length+1).fill(null));for(let s=0;s<=r.length;s++)t[0][s]=s;for(let s=0;s<=e.length;s++)t[s][0]=s;for(let s=1;s<=e.length;s++)for(let i=1;i<=r.length;i++){let a=r[i-1]===e[s-1]?0:1;t[s][i]=Math.min(t[s][i-1]+1,t[s-1][i]+1,t[s-1][i-1]+a);}return t[e.length][r.length]},G=r=>r.toLowerCase().replace(/[-_.]/g,"_").replace(/([A-Z])/g,"_$1").replace(/^_+/,"").replace(/_+$/,"").toLowerCase();var oe=r=>{if(!r||r==="-"||r==="--")return null;let e=r.indexOf("=");if(e>0){let t=r.substring(0,e),s=r.substring(e+1);return {name:t,value:X(s)}}return {name:r,value:true}},X=r=>{if(r.toLowerCase()==="true")return true;if(r.toLowerCase()==="false")return false;let e=Number(r);return !Number.isNaN(e)&&Number.isFinite(e)?e:r},C=()=>{let r=D.getCliArgs(),e=[],t={};if(!r||!r.length)return {args:e,flags:t};for(let s=0;s<r.length;s++){let i=r[s];if(!(!i||typeof i!="string")){if(i.startsWith("-")){let a=oe(i);if(a){if(a.value===true&&s+1<r.length){let o=r[s+1];o&&typeof o=="string"&&!o.startsWith("-")&&(a.value=X(o),s++);}t[a.name]=a.value;}continue}e.push(i);}}return {args:e,flags:t}},K=(r,e)=>{if(!r||typeof r!="string"||!e||!Array.isArray(e)||e.length===0)return "";let t=r.toLowerCase().trim(),s=e.filter(o=>{let f=o.toLowerCase();if(f===t||f.includes(t)||t.includes(f))return true;let m=Z(f,t),n=Math.max(t.length,f.length)*.4;return m<=n});if(s.length===0)return "";let a=s.slice(0,3).map(o=>`\x1B[36m${o}\x1B[0m`).join(", ");return `\x1B[31m\u2717\x1B[0m Command \x1B[33m${r}\x1B[0m not found
3
+ \x1B[32m\u{1F4A1}\x1B[0m Did you mean: ${a}?`},I=()=>D.getCliArgs()[0]||null;var _=class{exit(e){switch(h.type){case "bun":case "node":process.exit(e);case "deno":Deno.exit(e);default:throw new Error("Unsupported runtime")}}},$=new _;var x=class{static metadata=new WeakMap;static set(e,t,s){this.metadata.has(e)||this.metadata.set(e,new Map),this.metadata.get(e).set(t,s);}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 k="VALIDATION_ERROR";var ee=C().args.slice(1),j=r=>(e,t)=>{let s=I();if(!s||s!==e.commandName)return;let i=t;x.set(e,t,{type:"arg",name:i,description:r.description});let a=ee.length?ee.shift():r.defaultValue;if(r.required&&!a){let o=x.get(e,k);x.set(e,k,[...o||[],{type:"arg",name:i,message:"Required argument not provided"}]);return}r.parse&&a&&(a=r.parse(a)),Object.defineProperty(e,t,{value:a,enumerable:true,configurable:true,writable:true});};var le=()=>ce({level:"info",formatters:{level:e=>({level:e})}}),R=le();var y=class{static commandName=this.name;static description="";static help=[];static options={keepAlive:false};static args=C().args.slice(1);static flags=C().flags;static logger=R;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(n=>t.includes(n)))return;let i=this.commandName,a=this.description||"No description available",o=this.help||[],f=this.options,m=this.generateHelpOutput({name:i,description:a,helpText:o,options:f,args:this.args,flags:this.flags},this);console.log(m),$.exit(0);}static generateHelpOutput=(e,t)=>{let{name:s,description:i,helpText:a,options:o,args:f,flags:m}=e,n={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"},u=[`${n.title}${s}${n.reset}`,`${n.description}${i}${n.reset}`,"",`${n.subtitle}Usage:${n.reset}`,` ${n.code}${s}${n.reset} [options] [arguments]`,"",`${n.subtitle}Options:${n.reset}`,` ${n.flag}-h, --help${n.reset} Show this help message`,"",`${n.subtitle}Command Options:${n.reset}`,` ${n.flag}keepAlive${n.reset} ${o?.keepAlive??false?n.success+"Enabled"+n.reset:n.error+"Disabled"+n.reset}`,""];if(a){let c=Array.isArray(a)?a:[a];u.push(`${n.subtitle}Help:${n.reset}`),c.forEach(b=>{u.push(` ${n.description}${b}${n.reset}`);}),u.push("");}let E=x.getAll(t),J=Array.from(E.values()).filter(c=>c.type==="arg"),Q=Array.from(E.values()).filter(c=>c.type==="flag");return J.length&&(u.push(`${n.subtitle}Available Arguments:${n.reset}`),J.forEach(c=>{let b=c.required?` ${n.error}(required)${n.reset}`:"",O=c.description?` ${n.description}${c.description}${n.reset}`:"";u.push(` ${n.code}${c.name}${n.reset}${b}${O}`);}),u.push("")),Q.length&&(u.push(`${n.subtitle}Available Flags:${n.reset}`),Q.forEach(c=>{c.aliases&&!Array.isArray(c.aliases)&&(c.aliases=[c.aliases]);let b=c.aliases.length?` ${n.flag}(${c.aliases.join(", ")})${n.reset}`:"",O=c.required?` ${n.error}(required)${n.reset}`:"",ie=c.description?` ${n.description}${c.description}${n.reset}`:"";u.push(` ${n.flag}--${c.name}${b}${n.reset}${O}${ie}`);}),u.push("")),((f?.length??0)>0||m&&Object.keys(m).length>0)&&(u.push(`${n.subtitle}Current Context:${n.reset}`),f?.length&&u.push(` ${n.info}Provided Arguments:${n.reset} ${n.code}${f.join(" ")}${n.reset}`),m&&Object.keys(m).length>0&&(u.push(` ${n.info}Provided Flags:${n.reset}`),Object.keys(m).forEach(c=>{let b=m[c],O=b!=null?` = ${n.code}${b}${n.reset}`:"";u.push(` ${n.flag}${c}${n.reset}${O}`);})),u.push("")),a&&(Array.isArray(a)?a.some(c=>c.includes("example")):a.includes("example"))&&(u.push(`${n.subtitle}Examples:${n.reset}`),(Array.isArray(a)?a.filter(b=>b.includes("example")):[a.split("example")[1].trim()]).forEach(b=>{u.push(` ${n.code}${b}${n.reset}`);}),u.push("")),u.join(`
4
+ `)};static validateContext=e=>{let t=Array.from(x.get(e,k)||[]);if(t.length){let s={error:"\x1B[0;31m",title:"\x1B[1;31m",reset:"\x1B[0m",info:"\x1B[0;34m",code:"\x1B[0;32m"};console.error(`${s.title}\u274C Validation Errors:${s.reset}`),console.error(""),t.forEach((i,a)=>{let o=`${s.info}${a+1}.${s.reset}`,f=`${s.error}${i.type.toUpperCase()}${s.reset}`,m=`${s.code}${i.name}${s.reset}`;console.error(` ${o} ${f} ${m}: ${s.error}${i.message}${s.reset}`);}),console.error(""),console.error(`${s.info}\u{1F4A1} Tip: Use --help for usage information${s.reset}`),$.exit(1);}}};var U=class{async mkdir(e,t){switch(h.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(h.type){case "node":return (await import('fs')).existsSync(e);case "bun":return Bun.file(e).exists();case "deno":return Deno.stat(e).then(()=>true).catch(()=>false);default:throw new Error("Unsupported runtime")}}async readFile(e){switch(h.type){case "node":let s=await(await import('fs/promises')).readFile(e);return new Uint8Array(s);case "bun":let i=await Bun.file(e).arrayBuffer();return new Uint8Array(i);case "deno":return new Uint8Array(await Deno.readFile(e))}}async writeFile(e,t){switch(h.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(h.type){case "node":let s=await(await import('fs/promises')).stat(e);return {isDirectory:s.isDirectory(),isFile:s.isFile(),isSymbolicLink:s.isSymbolicLink(),size:s.size};case "bun":let i=await Bun.file(e).stat();return {isDirectory:i.isDirectory(),isFile:i.isFile(),isSymbolicLink:i.isSymbolicLink(),size:i.size};case "deno":let a=await Deno.stat(e);return {isDirectory:a.isDirectory,isFile:a.isFile,isSymbolicLink:false,size:a.size}}}async unlink(e){switch(h.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")}}},l=new U;var W=class{join(...e){switch(h.type){case "node":case "bun":case "deno":return z.join(...e);default:throw new Error("Unsupported runtime")}}extName(e){switch(h.type){case "bun":case "node":case "deno":return z.extname(e);default:throw new Error("Unsupported runtime")}}resolve(...e){switch(h.type){case "bun":case "node":case "deno":return z.resolve(...e);default:throw new Error("Unsupported runtime")}}},d=new W;var S=class extends y{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=d.join(this.path,`${this.name}.ts`),await l.exists(d.join(process.cwd(),this.path))||await l.mkdir(d.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await l.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";
5
5
 
6
6
  export default class extends Command {
7
7
  static commandName = "${this.name}";
@@ -15,7 +15,7 @@ export default class extends Command {
15
15
  static async handle(): Promise<void> {
16
16
  // Implement your command logic here
17
17
  }
18
- }`}};m([j({description:"The name of the command to generate",required:true})],S,"name");var C=r=>(e,t)=>{let s=I();if(!s||s!==e.commandName)return;let i=r.name||t,a=N().flags,o=r.aliases||[],h=[i,...o],p=r.defaultValue;for(let n of h){let u=[n,`-${n}`,`--${n}`];for(let O of u)if(O in a){p=a[O],r.type==="boolean"?p=!!p:r.type==="number"&&(p=Number(p)),r.parse&&(p=r.parse(p));break}if(p!==r.defaultValue)break}if(x.set(e,t,{type:"flag",name:i,aliases:o||[],description:r.description}),r.required&&!p){let n=x.get(e,k);x.set(e,k,[...n||[],{type:"flag",name:i,message:"Required flag not provided"}]);return}Object.defineProperty(e,t,{value:p,enumerable:true,configurable:true,writable:true});};C.boolean=r=>C({...r,type:"boolean"});C.string=r=>C({...r,type:"string"});C.number=r=>C({...r,type:"number"});var g=C;var F=class extends y{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=d.join(this.pluginPath,`${this.pluginName}.ts`),await l.exists(d.join(process.cwd(),this.pluginPath))||await l.mkdir(d.join(process.cwd(),this.pluginPath.split("/").slice(0,-1).join("/")),{recursive:true}),await l.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";
18
+ }`}};p([j({description:"The name of the command to generate",required:true})],S,"name");var F=r=>(e,t)=>{let s=I();if(!s||s!==e.commandName)return;let i=r.name||t,a=C().flags,o=r.aliases||[],f=[i,...o],m=r.defaultValue;for(let n of f){let u=[n,`-${n}`,`--${n}`];for(let E of u)if(E in a){m=a[E],r.type==="boolean"?m=!!m:r.type==="number"&&(m=Number(m)),r.parse&&(m=r.parse(m));break}if(m!==r.defaultValue)break}if(x.set(e,t,{type:"flag",name:i,aliases:o||[],description:r.description}),r.required&&!m){let n=x.get(e,k);x.set(e,k,[...n||[],{type:"flag",name:i,message:"Required flag not provided"}]);return}Object.defineProperty(e,t,{value:m,enumerable:true,configurable:true,writable:true});};F.boolean=r=>F({...r,type:"boolean"});F.string=r=>F({...r,type:"string"});F.number=r=>F({...r,type:"number"});var g=F;var T=class extends y{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=d.join(this.pluginPath,`${this.pluginName}.ts`),await l.exists(d.join(process.cwd(),this.pluginPath))||await l.mkdir(d.join(process.cwd(),this.pluginPath.split("/").slice(0,-1).join("/")),{recursive:true}),await l.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";
19
19
 
20
20
  export default class extends BasePlugin {
21
21
  async handle(): Promise<ServerRouteMiddleware> {
@@ -24,14 +24,15 @@ export default class extends BasePlugin {
24
24
  await next();
25
25
  };
26
26
  }
27
- }`}};m([j({description:"The name of the plugin to generate",required:true})],F,"pluginName"),m([g({description:"The path to the plugin to generate, default is src/plugins",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/plugins"})],F,"pluginPath");var H=class{getCwd(){switch(f.type){case "node":case "bun":return process.cwd();case "deno":return Deno.cwd();default:throw new Error("Unsupported runtime")}}},te=new H;var T=class extends y{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=d.join(this.path,`${this.fileName}.ts`),await l.exists(d.join(process.cwd(),this.path))||await l.mkdir(d.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await l.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";
27
+ }`}};p([j({description:"The name of the plugin to generate",required:true})],T,"pluginName"),p([g({description:"The path to the plugin to generate, default is src/plugins",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/plugins"})],T,"pluginPath");var H=class{getCwd(){switch(h.type){case "node":case "bun":return process.cwd();case "deno":return Deno.cwd();default:throw new Error("Unsupported runtime")}}},te=new H;var P=class extends y{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=d.join(this.path,`${this.fileName}.ts`),await l.exists(d.join(process.cwd(),this.path))||await l.mkdir(d.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await l.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Cron job ${this.fileName} created successfully at ${this.path}`);}static getCronTemplate(){return `import { BaseCron, cron } from "balda-js";
28
28
 
29
- export default class {
29
+ export default class extends BaseCron {
30
30
  @cron("* * * * *")
31
31
  handle() {
32
+ this.logger.info("Running cron job");
32
33
  // Implement your cron job logic here
33
34
  }
34
- }`}};m([j({description:"The name of the cron job file to generate",required:true})],T,"fileName"),m([g({description:"The path to the cron job to generate, default is src/cron",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/cron"})],T,"path");var re=async()=>await l.exists(d.join(process.cwd(),"yarn.lock"))?["yarn","add","-D"]:await l.exists(d.join(process.cwd(),"pnpm-lock.yaml"))?["pnpm","add","-D"]:await l.exists(d.join(process.cwd(),"package-lock.json"))?["npm","install","-D"]:await l.exists(d.join(process.cwd(),"bun.lockb"))?["bun","add","-D"]:await l.exists(d.join(process.cwd(),"deno.lock"))?["deno","add","-D"]:["npm","install","-D"];var q=class extends y{static commandName="init";static description="Initialize a new balda project in the current directory";static help=["Initialize a new balda project, it is given for granted that balda-js is installed in the project as a dependency","All the files are created in the /src directory (created if not exists)","It adds a server.ts for the file instance and a index.ts for the entry point with a dummy hello world route","Example: npx balda init -p ./src -t true"];static srcPath;static typescript;static devDependencies=["esbuild","esbuild-plugin-copy","tsx","typescript"];static async handle(){this.logger.info("Initializing project...");let[e,t,s]=await re();["npm","yarn","pnpm"].includes(e)&&(this.logger.info(`Installing dev dependencies with ${e}...`),execSync(`${e} ${t} ${this.devDependencies.join(" ")} -${s}`,{stdio:"inherit"}));let i=this.typescript?"ts":"js",a=this.getServerTemplate(),o=this.getIndexTemplate();l.exists(this.srcPath)||await l.mkdir(this.srcPath,{recursive:true}),this.logger.info(`Creating server.${i} file...`),await l.writeFile(`${this.srcPath}/server.${i}`,new TextEncoder().encode(a)),this.logger.info(`Creating index.${i} file...`),await l.writeFile(`${this.srcPath}/index.${i}`,new TextEncoder().encode(o)),this.logger.info("Project initialized successfully!");}static getServerTemplate(){return `import { Server } from "balda-js";
35
+ }`}};p([j({description:"The name of the cron job file to generate",required:true})],P,"fileName"),p([g({description:"The path to the cron job to generate, default is src/cron",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/cron"})],P,"path");var re=async()=>await l.exists(d.join(process.cwd(),"yarn.lock"))?["yarn","add","-D"]:await l.exists(d.join(process.cwd(),"pnpm-lock.yaml"))?["pnpm","add","-D"]:await l.exists(d.join(process.cwd(),"package-lock.json"))?["npm","install","-D"]:await l.exists(d.join(process.cwd(),"bun.lockb"))?["bun","add","-D"]:await l.exists(d.join(process.cwd(),"deno.lock"))?["deno","add","-D"]:["npm","install","-D"];var q=class extends y{static commandName="init";static description="Initialize a new balda project in the current directory";static help=["Initialize a new balda project, it is given for granted that balda-js is installed in the project as a dependency","All the files are created in the /src directory (created if not exists)","It adds a server.ts for the file instance and a index.ts for the entry point with a dummy hello world route","Example: npx balda init -p ./src -t true"];static srcPath;static typescript;static devDependencies=["esbuild","esbuild-plugin-copy","tsx","typescript"];static async handle(){this.logger.info("Initializing project...");let[e,t,s]=await re();["npm","yarn","pnpm"].includes(e)&&(this.logger.info(`Installing dev dependencies with ${e}...`),execSync(`${e} ${t} ${this.devDependencies.join(" ")} -${s}`,{stdio:"inherit"}));let i=this.typescript?"ts":"js",a=this.getServerTemplate(),o=this.getIndexTemplate();l.exists(this.srcPath)||await l.mkdir(this.srcPath,{recursive:true}),this.logger.info(`Creating server.${i} file...`),await l.writeFile(`${this.srcPath}/server.${i}`,new TextEncoder().encode(a)),this.logger.info(`Creating index.${i} file...`),await l.writeFile(`${this.srcPath}/index.${i}`,new TextEncoder().encode(o)),this.logger.info("Project initialized successfully!");}static getServerTemplate(){return `import { Server } from "balda-js";
35
36
 
36
37
  const serverInstance = new Server({
37
38
  port: 80,
@@ -49,11 +50,11 @@ export { serverInstance as server };
49
50
  server.listen(({ url }) => {
50
51
  console.log(\`Server is running on \${url}\`);
51
52
  });
52
- `}};m([g.string({description:"The path to the project, default is the current directory /src",aliases:"p",name:"path",required:false,defaultValue:"./src"})],q,"srcPath"),m([g.boolean({description:"Whether to use typescript, default is true",aliases:"t",name:"typescript",required:false,defaultValue:true})],q,"typescript");var L=class extends y{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=P.getCommands();console.log(`
53
+ `}};p([g.string({description:"The path to the project, default is the current directory /src",aliases:"p",name:"path",required:false,defaultValue:"./src"})],q,"srcPath"),p([g.boolean({description:"Whether to use typescript, default is true",aliases:"t",name:"typescript",required:false,defaultValue:true})],q,"typescript");var L=class extends y{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=A.getCommands();console.log(`
53
54
  \u2728 Available Balda Commands:
54
55
  `);let t=Math.max(...e.map(s=>s.commandName.length));for(let s of e){let i=s.commandName.padEnd(t+2),a=s.description||"No description available";console.log(` \x1B[36m${i}\x1B[0m ${a}`);}console.log(`
55
56
  \x1B[90mRun 'npx balda <command> -h' for more information on a specific command.\x1B[0m
56
- `);}};var A=class extends y{static commandName="generate-queue";static description="Generate a new queue in the specified path";static help=["Generate a new queue in the specified path","Example: npx balda generate-queue my-queue -p src/queues --provider bullmq"];static queueName;static path;static provider;static async handle(){let e=this.queueName.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/),t=this.getQueueTemplate(!!e);this.path=d.join(this.path,`${Q(this.queueName)}.ts`),await l.exists(d.join(process.cwd(),this.path))||await l.mkdir(d.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await l.writeFile(this.path,new TextEncoder().encode(t)),this.logger.info(`Queue ${this.queueName} created successfully at ${this.path}`);}static getQueueTemplate(e){return `import { queue, logger } from "balda-js";
57
+ `);}};var N=class extends y{static commandName="generate-queue";static description="Generate a new queue in the specified path";static help=["Generate a new queue in the specified path","Example: npx balda generate-queue my-queue -p src/queues --provider bullmq"];static queueName;static path;static provider;static async handle(){let e=this.queueName.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/),t=this.getQueueTemplate(!!e);this.path=d.join(this.path,`${G(this.queueName)}.ts`),await l.exists(d.join(process.cwd(),this.path))||await l.mkdir(d.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await l.writeFile(this.path,new TextEncoder().encode(t)),this.logger.info(`Queue ${this.queueName} created successfully at ${this.path}`);}static getQueueTemplate(e){return `import { BaseQueue, queue } from "balda-js";
57
58
 
58
59
  export type Payload = {
59
60
  // Add your payload here
@@ -65,14 +66,16 @@ declare module "balda-js" {
65
66
  }
66
67
  }
67
68
 
68
- export default class {
69
- private logger = logger.child({ queue: '${this.queueName}' });
70
-
69
+ export default class extends BaseQueue {
71
70
  @queue('${this.provider}', '${this.queueName}')
72
71
  async handle(payload: Payload) {
73
72
  // Implement your queue logic here
74
73
  this.logger.info({ payload }, 'Payload received');
75
74
  return Promise.resolve();
76
75
  }
77
- }`}};m([j({description:"The name of the queue to generate",required:true})],A,"queueName"),m([g({description:"The path to the queue to generate, default is src/queues",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/queues"})],A,"path"),m([g({description:"The provider of the queue to generate, default is bullmq",type:"string",aliases:["pr"],name:"provider",required:false,defaultValue:"bullmq"})],A,"provider");var w=class extends y{static commandName="build";static description="Build the project for production, node.js only";static help=["Build the project for production, node.js only","It will create a production build of the project in the dist directory","Must have a tsconfig.json file in the root of the project","Must have esbuild installed as a dependency while running the command","Must have esbuild-plugin-copy installed as a dependency while running the command if you want to copy assets to the output directory","Example: npx balda build -t ./tsconfig.json -a ./assets"];static clearDist;static entry;static output;static tsconfig;static assets;static format;static packages;static sourcemap;static async handle(){typeof process===void 0&&(this.logger.error("Build command is only supported in node.js"),process.exit(1)),["esm","cjs"].includes(this.format)||(this.logger.error("Invalid format, must be 'esm' or 'cjs'"),process.exit(1)),["bundle","external"].includes(this.packages)||(this.logger.error("Invalid packages, must be 'bundle' or 'external'"),process.exit(1));let e=await import('esbuild').catch(o=>{throw this.logger.error("esbuild is not installed, please install it with `npm install -D esbuild` to use the build command"),new Error("esbuild is not installed")}),t=z.join(this.output,"assets"),s=[];if(this.assets){let{copy:o}=await import('esbuild-plugin-copy').catch(h=>{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")});M.existsSync(t)||M.mkdirSync(t,{recursive:true}),s.push(o({assets:{from:this.assets,to:t}}));}this.clearDist&&M.existsSync(this.output)&&(this.logger.info("Clearing dist directory..."),M.rmSync(this.output,{recursive:true})),this.logger.info("Building project...");let i=z.join(this.output,"server.js"),a=await e.build({tsconfig:this.tsconfig,entryPoints:[this.entry],bundle:true,platform:"node",outfile:i,minify:true,sourcemap:this.sourcemap,plugins:s,format:this.format,packages:this.packages});a.errors.length&&(this.logger.error(JSON.stringify({message:"Failed to build the project",errors:a.errors},null,2)),process.exit(1)),a.warnings.length&&this.logger.warn(JSON.stringify({message:"Failed to build the project",warnings:a.warnings},null,2)),this.logger.info(JSON.stringify({message:`Project built successfully in ${i}`,output:i,assets:!!this.assets},null,2)),process.exit(0);}};m([g({type:"boolean",aliases:["c"],name:"clear-dist",required:false,defaultValue:false,description:"Whether to clear the dist directory before building the project"})],w,"clearDist"),m([g({type:"string",aliases:["e"],name:"entry",required:false,defaultValue:"./src/index.ts",description:"The entry point of the project, default is ./src/index.ts"})],w,"entry"),m([g({type:"string",aliases:["o"],name:"output",required:false,defaultValue:"./dist",description:"The path to the output directory, default is ./dist"})],w,"output"),m([g({type:"string",aliases:["t"],name:"tsconfig",required:false,defaultValue:"./tsconfig.json",description:"The path to the tsconfig.json file, default is ./tsconfig.json"})],w,"tsconfig"),m([g({type:"string",aliases:["a"],name:"assets",required:false,description:"The path to the assets directory that will be loaded in the production build"})],w,"assets"),m([g({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'"})],w,"format"),m([g({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'"})],w,"packages"),m([g({type:"boolean",aliases:["s"],name:"sourcemap",required:false,defaultValue:true,description:"Whether to generate sourcemaps or not, default is true"})],w,"sourcemap");var $=class r{commands;static commandsPattern="src/commands/**/*.{ts,js}";static logger=R;constructor(){this.commands=new Map;}static getInstance(){return new r}static setCommandsPattern(e){this.commandsPattern=e;}getCommand(e){return this.commands.get(e)??null}getCommands(){return Array.from(this.commands.values())}async loadCommands(e){r.logger.info(`Loading commands from ${e}`);let t=await glob(e,{absolute:true,cwd:te.getCwd()});if(t.some(i=>i.endsWith(".ts")))try{let{register:i}=await import('module');i("ts-node/esm",import.meta.url);}catch{r.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 i of t){let a=await import(i).then(o=>o.default?o.default:o).catch(o=>(r.logger.error(`Error loading command ${i}: ${o}`),null));a&&this.commands.set(a.commandName,a);}let s=[F,S,T,A,q,L,w];for(let i of s)this.commands.set(i.commandName,i);}},P=$.getInstance();var Y=async()=>{await P.loadCommands($.commandsPattern);let r=E.getCliArgs()[0];if(!r){console.error(`No command provided, available commands: ${P.getCommands().map(i=>i.commandName).join(", ")}`),v.exit(1);return}let e=P.getCommand(r);if(!e){console.error(K(r,P.getCommands().map(i=>i.commandName))||`Command ${r} not found`),v.exit(1);return}let t=e;t.handleHelpFlag(t.flags),t.validateContext(t),await t.handle(),(e.options?.keepAlive??false)||v.exit(0);};typeof process<"u"?Y().catch(async r=>{if(r?.message?.includes("SyntaxError")||r?.code==="ERR_UNKNOWN_FILE_EXTENSION")try{let{register:e}=await import('module');e("ts-node/esm",import.meta.url),Y().catch(t=>{$.logger.error(t),process.exit(1);});}catch{$.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);}else $.logger.error(r),process.exit(1);}):Y().catch(r=>{$.logger.error(r),v.exit(1);});export{Y as cli};//# sourceMappingURL=cli.js.map
76
+ }`}};p([j({description:"The name of the queue to generate",required:true})],N,"queueName"),p([g({description:"The path to the queue to generate, default is src/queues",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/queues"})],N,"path"),p([g({description:"The provider of the queue to generate, default is bullmq",type:"string",aliases:["pr"],name:"provider",required:false,defaultValue:"bullmq"})],N,"provider");var w=class extends y{static commandName="build";static description="Build the project for production, node.js only";static help=["Build the project for production, node.js only","It will create a production build of the project in the dist directory","Must have a tsconfig.json file in the root of the project","Must have esbuild installed as a dependency while running the command","Must have esbuild-plugin-copy installed as a dependency while running the command if you want to copy assets to the output directory","Example: npx balda build -t ./tsconfig.json -a ./assets"];static clearDist;static entry;static output;static tsconfig;static assets;static format;static packages;static sourcemap;static async handle(){typeof process===void 0&&(this.logger.error("Build command is only supported in node.js"),process.exit(1)),["esm","cjs"].includes(this.format)||(this.logger.error("Invalid format, must be 'esm' or 'cjs'"),process.exit(1)),["bundle","external"].includes(this.packages)||(this.logger.error("Invalid packages, must be 'bundle' or 'external'"),process.exit(1));let e=await import('esbuild').catch(o=>{throw this.logger.error("esbuild is not installed, please install it with `npm install -D esbuild` to use the build command"),new Error("esbuild is not installed")}),t=z.join(this.output,"assets"),s=[];if(this.assets){let{copy:o}=await import('esbuild-plugin-copy').catch(f=>{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")});M.existsSync(t)||M.mkdirSync(t,{recursive:true}),s.push(o({assets:{from:this.assets,to:t}}));}this.clearDist&&M.existsSync(this.output)&&(this.logger.info("Clearing dist directory..."),M.rmSync(this.output,{recursive:true})),this.logger.info("Building project...");let i=z.join(this.output,"server.js"),a=await e.build({tsconfig:this.tsconfig,entryPoints:[this.entry],bundle:true,platform:"node",outfile:i,minify:true,sourcemap:this.sourcemap,plugins:s,format:this.format,packages:this.packages});a.errors.length&&(this.logger.error(JSON.stringify({message:"Failed to build the project",errors:a.errors},null,2)),process.exit(1)),a.warnings.length&&this.logger.warn(JSON.stringify({message:"Failed to build the project",warnings:a.warnings},null,2)),this.logger.info(JSON.stringify({message:`Project built successfully in ${i}`,output:i,assets:!!this.assets},null,2)),process.exit(0);}};p([g({type:"boolean",aliases:["c"],name:"clear-dist",required:false,defaultValue:false,description:"Whether to clear the dist directory before building the project"})],w,"clearDist"),p([g({type:"string",aliases:["e"],name:"entry",required:false,defaultValue:"./src/index.ts",description:"The entry point of the project, default is ./src/index.ts"})],w,"entry"),p([g({type:"string",aliases:["o"],name:"output",required:false,defaultValue:"./dist",description:"The path to the output directory, default is ./dist"})],w,"output"),p([g({type:"string",aliases:["t"],name:"tsconfig",required:false,defaultValue:"./tsconfig.json",description:"The path to the tsconfig.json file, default is ./tsconfig.json"})],w,"tsconfig"),p([g({type:"string",aliases:["a"],name:"assets",required:false,description:"The path to the assets directory that will be loaded in the production build"})],w,"assets"),p([g({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'"})],w,"format"),p([g({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'"})],w,"packages"),p([g({type:"boolean",aliases:["s"],name:"sourcemap",required:false,defaultValue:true,description:"Whether to generate sourcemaps or not, default is true"})],w,"sourcemap");var v=class r{commands;static commandsPattern="src/commands/**/*.{ts,js}";static logger=R;constructor(){this.commands=new Map;}static getInstance(){return new r}static setCommandsPattern(e){this.commandsPattern=e;}getCommand(e){return this.commands.get(e)??null}getCommands(){return Array.from(this.commands.values())}async loadCommands(e){r.logger.info(`Loading commands from ${e}`);let t=await glob(e,{absolute:true,cwd:te.getCwd()});if(t.some(i=>i.endsWith(".ts")))try{let{register:i}=await import('module');i("ts-node/esm",import.meta.url);}catch{r.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 i of t){let a=await import(i).then(o=>o.default?o.default:o).catch(o=>(r.logger.error(`Error loading command ${i}: ${o}`),null));a&&this.commands.set(a.commandName,a);}let s=[T,S,P,N,q,L,w];for(let i of s)this.commands.set(i.commandName,i);}},A=v.getInstance();var Y=async()=>{await A.loadCommands(v.commandsPattern);let r=D.getCliArgs()[0];if(r==="-h"||r==="--help"){let i=A.getCommands().filter(o=>o.commandName);console.log(`
77
+ \u2728 Available Balda Commands:
78
+ `);let a=Math.max(...i.map(o=>o.commandName.length));for(let o of i){let f=o.commandName.padEnd(a+2),m=o.description||"No description available";console.log(` \x1B[36m${f}\x1B[0m ${m}`);}console.log(`
79
+ \x1B[90mRun 'npx balda <command> -h' for more information on a specific command.\x1B[0m
80
+ `),$.exit(0);return}if(!r){console.error(`No command provided, available commands: ${A.getCommands().map(i=>i.commandName).join(", ")}`),$.exit(1);return}let e=A.getCommand(r);if(!e){console.error(K(r,A.getCommands().map(i=>i.commandName))||`Command ${r} not found`),$.exit(1);return}let t=e;t.handleHelpFlag(t.flags),t.validateContext(t),await t.handle(),(e.options?.keepAlive??false)||$.exit(0);};typeof process<"u"?Y().catch(async r=>{if(r?.message?.includes("SyntaxError")||r?.code==="ERR_UNKNOWN_FILE_EXTENSION")try{let{register:e}=await import('module');e("ts-node/esm",import.meta.url),Y().catch(t=>{v.logger.error(t),process.exit(1);});}catch{v.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);}else v.logger.error(r),process.exit(1);}):Y().catch(r=>{v.logger.error(r),$.exit(1);});export{Y as cli};//# sourceMappingURL=cli.js.map
78
81
  //# sourceMappingURL=cli.js.map