balda 0.0.1

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 ADDED
@@ -0,0 +1,306 @@
1
+ #!/usr/bin/env node
2
+ import {glob}from'glob';import we from'pino';import X from'fs';import J from'path';import {execSync}from'child_process';import*as ge from'readline';var ye=Object.defineProperty;var p=(r,e,t,s)=>{for(var i=void 0,n=r.length-1,c;n>=0;n--)(c=r[n])&&(i=(c(e,t,i))||i);return i&&ye(e,t,i),i};var te=class{type;constructor(){this.type=this.getRunTime();}getRunTime(){if(typeof Bun<"u")return "bun";if(typeof Deno<"u")return "deno";if(typeof process<"u")return "node";throw new Error("No environment detected")}},y=new te;var se=class{getCliArgs(){switch(y.type){case "bun":return this.getBunArgs();case "node":return this.getNodeArgs();case "deno":return Deno.args;default:throw new Error("Unsupported runtime")}}getCliCaller(){switch(y.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 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 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}},B=new se;var le=(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 n=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]+n);}return t[e.length][r.length]},Y=r=>r.toLowerCase().replace(/[-_.]/g,"_").replace(/([A-Z])/g,"_$1").replace(/^_+/,"").replace(/_+$/,"").toLowerCase(),K=r=>r.split(/[-_.]/g).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),me=r=>r.split(/[-_.]/g).map(e=>e.toLowerCase()).join("-");var xe=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:de(s)}}return {name:r,value:true}},de=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},k=()=>{let r=B.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 n=xe(i);if(n){if(n.value===true&&s+1<r.length){let c=r[s+1];c&&typeof c=="string"&&!c.startsWith("-")&&(n.value=de(c),s++);}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(i);}}return {args:e,flags:t}},pe=(r,e)=>{if(!r||typeof r!="string"||!e||!Array.isArray(e)||e.length===0)return "";let t=r.toLowerCase().trim(),s=e.filter(c=>{let a=c.toLowerCase();if(a===t||a.includes(t)||t.includes(a))return true;let l=le(a,t),o=Math.max(t.length,a.length)*.4;return l<=o});if(s.length===0)return "";let n=s.slice(0,3).map(c=>`\x1B[36m${c}\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: ${n}?`},H=()=>B.getCliArgs()[0]||null;var ve=()=>we({level:"info",formatters:{level:e=>({level:e})}}),Z=ve();var re=class{getCwd(){switch(y.type){case "node":case "bun":return process.cwd();case "deno":return Deno.cwd();default:throw new Error("Unsupported runtime")}}},W=new re;var w=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 R="VALIDATION_ERROR";var ue=k().args.slice(1),x=r=>(e,t)=>{let s=H();if(!s||s!==e.commandName)return;let i=t;w.set(e,t,{type:"arg",name:i,description:r.description});let n=ue.length?ue.shift():r.defaultValue;if(r.required&&!n){let c=w.get(e,R);w.set(e,R,[...c||[],{type:"arg",name:i,message:"Required argument not provided"}]);return}r.parse&&n&&(n=r.parse(n)),Object.defineProperty(e,t,{value:n,enumerable:true,configurable:true,writable:true});};var A=r=>(e,t)=>{let s=H();if(!s||s!==e.commandName)return;let i=r.name||t,n=k().flags,c=r.aliases||[],a=[i,...c],l=r.defaultValue;for(let o of a){let g=[o,`-${o}`,`--${o}`];for(let T of g)if(T in n){let P=n[T];r.type==="list"?l=(Array.isArray(P)?P:[P]).map(f=>{let b=String(f);return r.parse?r.parse(b):b}):(l=P,r.type==="boolean"?l=!!l:r.type==="number"&&(l=Number(l)),r.parse&&(l=r.parse(l)));break}if(l!==r.defaultValue)break}if(w.set(e,t,{type:"flag",name:i,aliases:c||[],description:r.description}),r.required&&(r.type==="list"?!l||Array.isArray(l)&&l.length===0:!l)){let g=w.get(e,R);w.set(e,R,[...g||[],{type:"flag",name:i,message:"Required flag not provided"}]);return}Object.defineProperty(e,t,{value:l,enumerable:true,configurable:true,writable:true});};A.boolean=r=>A({...r,type:"boolean"});A.string=r=>A({...r,type:"string"});A.number=r=>A({...r,type:"number"});A.list=r=>A({...r,type:"list"});var u=A;var ie=class{exit(e){switch(y.type){case "bun":case "node":process.exit(e);case "deno":Deno.exit(e);default:throw new Error("Unsupported runtime")}}},N=new ie;var h=class{static commandName=this.name;static calledBy=this.name;static description="";static help=[];static options={keepAlive:false};static args=k().args.slice(1);static flags=k().flags;static logger=Z;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(o=>t.includes(o)))return;let i=this.commandName,n=this.description||"No description available",c=this.help||[],a=this.options,l=this.generateHelpOutput({name:i,description:n,helpText:c,options:a,args:this.args,flags:this.flags},this);console.log(l),N.exit(0);}static generateHelpOutput=(e,t)=>{let{name:s,description:i,helpText:n,options:c,args:a,flags:l}=e,o={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"},g=[`${o.title}${s}${o.reset}`,`${o.description}${i}${o.reset}`,"",`${o.subtitle}Usage:${o.reset}`,` ${o.code}${s}${o.reset} [options] [arguments]`,"",`${o.subtitle}Options:${o.reset}`,` ${o.flag}-h, --help${o.reset} Show this help message`,"",`${o.subtitle}Command Options:${o.reset}`,` ${o.flag}keepAlive${o.reset} ${c?.keepAlive??false?o.success+"Enabled"+o.reset:o.error+"Disabled"+o.reset}`,""];if(n){let f=Array.isArray(n)?n:[n];g.push(`${o.subtitle}Help:${o.reset}`),f.forEach(b=>{g.push(` ${o.description}${b}${o.reset}`);}),g.push("");}let T=w.getAll(t),P=Array.from(T.values()).filter(f=>f.type==="arg"),ee=Array.from(T.values()).filter(f=>f.type==="flag");return P.length&&(g.push(`${o.subtitle}Available Arguments:${o.reset}`),P.forEach(f=>{let b=f.required?` ${o.error}(required)${o.reset}`:"",Q=f.description?` ${o.description}${f.description}${o.reset}`:"";g.push(` ${o.code}${f.name}${o.reset}${b}${Q}`);}),g.push("")),ee.length&&(g.push(`${o.subtitle}Available Flags:${o.reset}`),ee.forEach(f=>{f.aliases&&!Array.isArray(f.aliases)&&(f.aliases=[f.aliases]);let b=f.aliases.length?` ${o.flag}(${f.aliases.join(", ")})${o.reset}`:"",Q=f.required?` ${o.error}(required)${o.reset}`:"",he=f.description?` ${o.description}${f.description}${o.reset}`:"";g.push(` ${o.flag}--${f.name}${b}${o.reset}${Q}${he}`);}),g.push("")),((a?.length??0)>0||l&&Object.keys(l).length>0)&&(g.push(`${o.subtitle}Current Context:${o.reset}`),a?.length&&g.push(` ${o.info}Provided Arguments:${o.reset} ${o.code}${a.join(" ")}${o.reset}`),l&&Object.keys(l).length>0&&(g.push(` ${o.info}Provided Flags:${o.reset}`),Object.keys(l).forEach(f=>{let b=l[f],Q=b!=null?` = ${o.code}${b}${o.reset}`:"";g.push(` ${o.flag}${f}${o.reset}${Q}`);})),g.push("")),n&&(Array.isArray(n)?n.some(f=>f.includes("example")):n.includes("example"))&&(g.push(`${o.subtitle}Examples:${o.reset}`),(Array.isArray(n)?n.filter(b=>b.includes("example")):[n.split("example")[1].trim()]).forEach(b=>{g.push(` ${o.code}${b}${o.reset}`);}),g.push("")),g.join(`
4
+ `)};static validateContext=e=>{let t=Array.from(w.get(e,R)||[]);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,n)=>{let c=`${s.info}${n+1}.${s.reset}`,a=`${s.error}${i.type.toUpperCase()}${s.reset}`,l=`${s.code}${i.name}${s.reset}`;console.error(` ${c} ${a} ${l}: ${s.error}${i.message}${s.reset}`);}),console.error(""),console.error(`${s.info}\u{1F4A1} Tip: Use --help for usage information${s.reset}`),N.exit(1);}}};var ne=class{async mkdir(e,t){switch(y.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(y.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(y.type){case "node":let i=await(await import('fs/promises')).readFile(e,{encoding:t?.encoding??null});return t?.encoding==="utf8"?i:new Uint8Array(i);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(y.type){case "node":await(await import('fs/promises')).writeFile(e,t);break;case "bun":await Bun.write(e,t);break;case "deno":await Deno.writeFile(e,t);break}}async stat(e){switch(y.type){case "node":let s=await(await import('fs/promises')).stat(e);return {isDirectory:s.isDirectory(),isFile:s.isFile(),isSymbolicLink:s.isSymbolicLink(),size:s.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(y.type){case "node":await(await import('fs/promises')).unlink(e);break;case "bun":await Bun.file(e).delete();break;case "deno":await Deno.remove(e);break;default:throw new Error("Unsupported runtime")}}async streamFile(e){switch(y.type){case "node":let t=await import('fs'),{Readable:s}=await import('stream'),i=t.createReadStream(e);return s.toWeb(i);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(y.type){case "bun":case "node":return (await import('fs/promises')).readdir(e);case "deno":let s=[];for await(let i of Deno.readDir(e))s.push(i.name);return s;default:throw new Error("Unsupported runtime")}}},m=new ne;var oe=class{basename(e){switch(y.type){case "node":case "bun":case "deno":return J.basename(e);default:throw new Error("Unsupported runtime")}}join(...e){switch(y.type){case "node":case "bun":case "deno":return J.join(...e);default:throw new Error("Unsupported runtime")}}extName(e){switch(y.type){case "bun":case "node":case "deno":return J.extname(e);default:throw new Error("Unsupported runtime")}}resolve(...e){switch(y.type){case "bun":case "node":case "deno":return J.resolve(...e);default:throw new Error("Unsupported runtime")}}},d=new oe;var V=async r=>{let e=d.join(process.cwd(),"node_modules");if(!await m.exists(e))return r;let s=[];for(let i of r){let n=d.join(e,i);await m.exists(n)||s.push(i);}return s},q=async()=>await m.exists(d.join(process.cwd(),"yarn.lock"))?["yarn","add","-D"]:await m.exists(d.join(process.cwd(),"pnpm-lock.yaml"))?["pnpm","add","-D"]:await m.exists(d.join(process.cwd(),"package-lock.json"))?["npm","install","-D"]:await m.exists(d.join(process.cwd(),"bun.lockb"))?["bun","add","-D"]:await m.exists(d.join(process.cwd(),"deno.lock"))?["deno","add","-D"]:["npm","install","-D"],C=async(r,e,t,s,i=true)=>{let n=ge.createInterface({input:process.stdin,output:process.stdout}),c=t.join(", "),a=`Do you want to install the following ${i?"dev":""} dependencies using ${e}?
5
+ ${c}
6
+ (y/n): `;return new Promise(l=>{n.question(a,o=>{if(n.close(),o.toLowerCase()==="y"||o.toLowerCase()==="yes"){execSync(r,s),l(true);return}l(false);});})};var v=class extends h{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,l,o]=await q();await C(`${a} ${l} esbuild ${o}`,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")}),s=J.join(this.output,"assets"),i=[];if(this.assets){let{copy:a}=await import('esbuild-plugin-copy').catch(l=>{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")});X.existsSync(s)||X.mkdirSync(s,{recursive:true}),i.push(a({assets:{from:this.assets,to:s}}));}this.clearDist&&X.existsSync(this.output)&&(this.logger.info("Clearing dist directory..."),X.rmSync(this.output,{recursive:true})),this.logger.info("Building project...");let n=J.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:i,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);}};p([u({type:"boolean",aliases:["c"],name:"clear-dist",required:false,defaultValue:false,description:"Whether to clear the dist directory before building the project"})],v,"clearDist"),p([u({type:"string",aliases:["e"],name:"entry",required:false,defaultValue:"./src/index.ts",description:"The entry point of the project, default is ./src/index.ts"})],v,"entry"),p([u({type:"string",aliases:["o"],name:"output",required:false,defaultValue:"./dist",description:"The path to the output directory, default is ./dist"})],v,"output"),p([u({type:"string",aliases:["t"],name:"tsconfig",required:false,defaultValue:"./tsconfig.json",description:"The path to the tsconfig.json file, default is ./tsconfig.json"})],v,"tsconfig"),p([u({type:"string",aliases:["a"],name:"assets",required:false,description:"The path to the assets directory that will be loaded in the production build"})],v,"assets"),p([u({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'"})],v,"format"),p([u({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'"})],v,"packages"),p([u({type:"boolean",aliases:["s"],name:"sourcemap",required:false,defaultValue:true,description:"Whether to generate sourcemaps or not, default is true"})],v,"sourcemap");var z=class extends h{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($.getCommand(this.name)){let i=$.isBuiltInCommand(this.name)?"built-in":"user-defined";this.logger.error({commandName:this.name,type:i},`Command "${this.name}" already exists as a ${i} command. Cannot override existing commands.`);return}let t=this.getCommandTemplate();this.path=d.join(this.path,`${this.name}.ts`),await m.exists(d.join(process.cwd(),this.path))||await m.mkdir(d.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await m.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
+
8
+ export default class extends Command {
9
+ static commandName = "${this.name}";
10
+ static description = "Command description";
11
+
12
+ static options: CommandOptions = {
13
+ // Define your command options here
14
+ keepAlive: false,
15
+ };
16
+
17
+ static async handle(): Promise<void> {
18
+ // Implement your command logic here
19
+ }
20
+ }`}};p([x({description:"The name of the command to generate",required:true})],z,"name");var F=class extends h{static commandName="generate-controller";static description="Generate a new controller in the specified path";static help=["Generate a new controller in the specified path","Example: npx balda generate-controller user -p src/controllers"];static controllerName;static path;static async handle(){let e=this.getControllerTemplate(),t=`${this.controllerName.toLowerCase()}.ts`;this.path=d.join(this.path,t),await m.exists(d.join(process.cwd(),this.path))||await m.mkdir(d.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await m.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Controller ${this.controllerName} created successfully at ${this.path}`);}static getControllerTemplate(){let e=K(this.controllerName);return `import { controller, get, post, put, del, Request, Response } from "balda";
21
+
22
+ @controller("/${me(this.controllerName)}")
23
+ export default class ${e}Controller {
24
+ @get("/")
25
+ async index(req: Request, res: Response) {
26
+ return { message: "List all ${this.controllerName.toLowerCase()}s" };
27
+ }
28
+
29
+ @get("/:id")
30
+ async show(req: Request, res: Response) {
31
+ return { message: \`Get ${this.controllerName.toLowerCase()} with id \${req.params.id}\` };
32
+ }
33
+
34
+ @post("/")
35
+ async create(req: Request, res: Response) {
36
+ return { message: \`Create ${this.controllerName.toLowerCase()}\`, data: req.body };
37
+ }
38
+
39
+ @put("/:id")
40
+ async update(req: Request, res: Response) {
41
+ return { message: \`Update ${this.controllerName.toLowerCase()} with id \${req.params.id}\`, data: req.body };
42
+ }
43
+
44
+ @del("/:id")
45
+ async destroy(req: Request, res: Response) {
46
+ return { message: \`Delete ${this.controllerName.toLowerCase()} with id \${req.params.id}\` };
47
+ }
48
+ }`}};p([x({description:"The name of the controller to generate",required:true})],F,"controllerName"),p([u({description:"The path to the controller to generate, default is src/controllers",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/controllers"})],F,"path");var M=class extends h{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 m.exists(d.join(process.cwd(),this.path))||await m.mkdir(d.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await m.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Cron job ${this.fileName} created successfully at ${this.path}`);}static getCronTemplate(){return `import { BaseCron, cron } from "balda";
49
+
50
+ export default class extends BaseCron {
51
+ @cron("* * * * *")
52
+ handle() {
53
+ this.logger.info("Running cron job");
54
+ // Implement your cron job logic here
55
+ }
56
+ }`}};p([x({description:"The name of the cron job file to generate",required:true})],M,"fileName"),p([u({description:"The path to the cron job to generate, default is src/cron",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/cron"})],M,"path");var I=class extends h{static commandName="generate-middleware";static description="Generate a new middleware in the specified path";static help=["Generate a new middleware in the specified path","Example: npx balda generate-middleware auth -p src/middlewares"];static middlewareName;static path;static async handle(){let e=this.getMiddlewareTemplate(),t=`${this.middlewareName.toLowerCase()}.ts`;this.path=d.join(this.path,t),await m.exists(d.join(process.cwd(),this.path))||await m.mkdir(d.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await m.writeFile(this.path,new TextEncoder().encode(e)),this.logger.info(`Middleware ${this.middlewareName} created successfully at ${this.path}`);}static getMiddlewareTemplate(){let e=K(this.middlewareName);return `import type { Request, Response, NextFunction, ServerRouteMiddleware } from "balda";
57
+
58
+ /**
59
+ * ${e} middleware
60
+ * @description Add your middleware logic here
61
+ */
62
+ export const ${e}: ServerRouteMiddleware = async () => {
63
+ return async (req: Request, res: Response, next: NextFunction) => {
64
+ // Add your middleware logic here
65
+ return next();
66
+ };
67
+ };`}};p([x({description:"The name of the middleware to generate",required:true})],I,"middlewareName"),p([u({description:"The path to the middleware to generate, default is src/middlewares",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/middlewares"})],I,"path");var O=class extends h{static commandName="generate-mqtt";static description="Generate a new MQTT handler in the specified path";static help=["Generate a new MQTT handler in the specified path","Example: npx balda generate-mqtt temperature-handler -p src/mqtt"];static path;static topic;static async handle(){let e=this.topic.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/),t=this.getMqttTemplate(!!e);this.path=d.join(this.path,`${Y(this.topic.replace(/\//g,"_"))}.ts`),await m.exists(d.join(process.cwd(),this.path))||await m.mkdir(d.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await m.writeFile(this.path,new TextEncoder().encode(t)),this.logger.info(`MQTT handler for topic ${this.topic} created successfully at ${this.path}`);}static getMqttTemplate(e){return `import { BaseMqtt, mqtt } from "balda";
68
+
69
+ /**
70
+ * Define your MQTT topics interface for type safety
71
+ */
72
+ declare module "balda" {
73
+ interface MqttTopics {
74
+ ${e?`${this.topic}: string;`:`'${this.topic}': string;`}
75
+ }
76
+ }
77
+
78
+ export default class extends BaseMqtt {
79
+ @mqtt.subscribe("${this.topic}")
80
+ async handle(message: string) {
81
+ this.logger.info({ message }, "Message received");
82
+ // Implement your MQTT handler logic here
83
+ }
84
+ }`}};p([u({description:"The path to the MQTT handler to generate, default is src/mqtt",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/mqtt"})],O,"path"),p([x({description:"The MQTT topic to subscribe to",required:true})],O,"topic");var _=class extends h{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 m.exists(d.join(process.cwd(),this.pluginPath))||await m.mkdir(d.join(process.cwd(),this.pluginPath.split("/").slice(0,-1).join("/")),{recursive:true}),await m.writeFile(this.pluginPath,new TextEncoder().encode(e)),this.logger.info(`Plugin ${this.name} created successfully at ${this.pluginPath}`);}static getPluginTemplate(){return `import { BasePlugin, Request, Response, NextFunction, ServerRouteMiddleware } from "balda";
85
+
86
+ export default class extends BasePlugin {
87
+ async handle(): Promise<ServerRouteMiddleware> {
88
+ return async (req: Request, res: Response, next: NextFunction) => {
89
+ console.log("${this.pluginName} plugin is running");
90
+ await next();
91
+ };
92
+ }
93
+ }`}};p([x({description:"The name of the plugin to generate",required:true})],_,"pluginName"),p([u({description:"The path to the plugin to generate, default is src/plugins",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/plugins"})],_,"pluginPath");var E=class extends h{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,`${Y(this.queueName)}.ts`),await m.exists(d.join(process.cwd(),this.path))||await m.mkdir(d.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await m.writeFile(this.path,new TextEncoder().encode(t)),this.logger.info(`Queue ${this.queueName} created successfully at ${this.path}`);}static getQueueTemplate(e){return `import { BaseQueue, queue } from "balda";
94
+
95
+ export type Payload = {
96
+ // Add your payload here
97
+ };
98
+
99
+ declare module "balda" {
100
+ export interface QueueTopic {
101
+ ${e?this.queueName:`'${this.queueName}'`}: Payload;
102
+ }
103
+ }
104
+
105
+ export default class extends BaseQueue {
106
+ @queue('${this.provider}', '${this.queueName}')
107
+ async handle(payload: Payload) {
108
+ // Implement your queue logic here
109
+ this.logger.info({ payload }, 'Payload received');
110
+ return Promise.resolve();
111
+ }
112
+ }`}};p([x({description:"The name of the queue to generate",required:true})],E,"queueName"),p([u({description:"The path to the queue to generate, default is src/queues",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/queues"})],E,"path"),p([u({description:"The provider of the queue to generate, default is bullmq",type:"string",aliases:["pr"],name:"provider",required:false,defaultValue:"bullmq"})],E,"provider");var S=class extends h{static commandName="init";static description="Initialize a new balda project in the current directory";static help=["Initialize a new balda project, it is given for granted that balda is installed in the project as a dependency","All the files are created in the /src directory (created if not exists)","It adds a server.ts for the file instance and a index.ts for the entry point with a dummy hello world route","Example: npx balda init -p ./src -t true"];static srcPath;static typescript;static mqtt;static cron;static devDependencies=["esbuild","esbuild-plugin-copy","tsx","typescript"];static async handle(){this.logger.info("Initializing project...");let[e,t,s]=await q();if(["npm","yarn","pnpm"].includes(e)){let a=await V(this.devDependencies);if(a.length&&(this.logger.info(`Found ${a.length} missing dev dependencies`),!await C(`${e} ${t} ${a.join(" ")} -${s}`,e,a,{stdio:"inherit"}))){this.logger.info("Installation cancelled by user. Project initialization aborted.");return}a.length||this.logger.info("All dev dependencies are already installed");}if(this.mqtt&&["npm","yarn","pnpm"].includes(e)){let a=await V(["mqtt"]);a.length&&(await C(`${e} ${t} mqtt`,e,["mqtt"],{stdio:"inherit"},false)||(this.logger.info("MQTT installation cancelled by user. Skipping MQTT scaffolding."),this.mqtt=false)),a.length||this.logger.info("MQTT package is already installed");}if(this.cron&&["npm","yarn","pnpm"].includes(e)){let a=await V(["node-cron"]);a.length>0&&(await C(`${e} ${t} node-cron`,e,["node-cron"],{stdio:"inherit"},false)||(this.logger.info("node-cron installation cancelled by user. Skipping Cron scaffolding."),this.cron=false)),a.length||this.logger.info("node-cron package is already installed");}let i=this.typescript?"ts":"js",n=this.getServerTemplate(),c=this.getIndexTemplate();if(m.exists(this.srcPath)||await m.mkdir(this.srcPath,{recursive:true}),this.logger.info(`Creating server.${i} file...`),await m.writeFile(`${this.srcPath}/server.${i}`,new TextEncoder().encode(n)),this.logger.info(`Creating index.${i} file...`),await m.writeFile(`${this.srcPath}/index.${i}`,new TextEncoder().encode(c)),this.mqtt){let a=d.join(this.srcPath,"mqtt");await m.exists(a)||await m.mkdir(a,{recursive:true});let l=this.getMqttConfigTemplate();this.logger.info(`Creating mqtt/mqtt.config.${i} file...`),await m.writeFile(d.join(a,`mqtt.config.${i}`),new TextEncoder().encode(l));}if(this.cron){let a=d.join(this.srcPath,"cron");await m.exists(a)||await m.mkdir(a,{recursive:true});let l=this.getCronConfigTemplate();this.logger.info(`Creating cron/cron.config.${i} file...`),await m.writeFile(d.join(a,`cron.config.${i}`),new TextEncoder().encode(l));}this.logger.info("Project initialized successfully!");}static getServerTemplate(){return `import { Server } from "balda";
113
+
114
+ const serverInstance = new Server({
115
+ port: 80,
116
+ host: "0.0.0.0",
117
+ plugins: {
118
+ json: {
119
+ sizeLimit: "100kb",
120
+ },
121
+ },
122
+ });
123
+
124
+ export { serverInstance as server };
125
+ `}static getIndexTemplate(){let e=['import { server } from "./server.js";'],t=[];this.mqtt&&(e.push('import "./mqtt/mqtt.config.js";'),e.push('import { MqttService } from "balda";'),t.push(`
126
+ // Initialize MQTT service
127
+ await MqttService.connect({
128
+ host: "localhost",
129
+ port: 1883,
130
+ protocol: "mqtt",
131
+ });
132
+ console.log("MQTT service connected");`)),this.cron&&(e.push('import "./cron/cron.config.js";'),e.push('import { CronService } from "balda";'),t.push(`
133
+ // Initialize Cron service
134
+ await CronService.run();
135
+ console.log("Cron service started");`));let s=e.join(`
136
+ `),i=t.length>0?t.join(`
137
+ `):"";return `${s}
138
+ ${i?`
139
+ ${i}
140
+ `:""}
141
+ server.listen(({ url }) => {
142
+ console.log(\`Server is running on \${url}\`);
143
+ });
144
+ `}static getMqttConfigTemplate(){return `// MQTT Configuration
145
+ // This file is imported to set up MQTT connection options
146
+ // Add your MQTT handlers in separate files within this directory
147
+ // Use: npx balda generate-mqtt <handler-name> to create new handlers
148
+ `}static getCronConfigTemplate(){return `// Cron Configuration
149
+ // This file is imported to set up Cron jobs
150
+ // Add your cron jobs in separate files within this directory
151
+ // Use: npx balda generate-cron <job-name> to create new cron jobs
152
+ `}};p([u.string({description:"The path to the project, default is the current directory /src",aliases:"p",name:"path",required:false,defaultValue:"./src"})],S,"srcPath"),p([u.boolean({description:"Whether to use typescript, default is true",aliases:"t",name:"typescript",required:false,defaultValue:true})],S,"typescript"),p([u.boolean({description:"Initialize MQTT service connection",aliases:"m",name:"mqtt",required:false,defaultValue:false})],S,"mqtt"),p([u.boolean({description:"Initialize Cron service",aliases:"c",name:"cron",required:false,defaultValue:false})],S,"cron");var D=class extends h{static commandName="init-queue";static description="Initialize queue provider configuration with required dependencies";static help=["Initialize a queue provider configuration file with basic credentials","Automatically installs required packages for the selected provider","Only scaffolds the connection, handlers should be created with generate-queue command","Example: npx balda init-queue -t bullmq -o src/queue"];static queueType;static outputPath;static queueDependencies={bullmq:["bullmq","ioredis"],sqs:["@aws-sdk/client-sqs","sqs-consumer"],pgboss:["pg-boss","pg"]};static async handle(){if(this.logger.info(`Initializing ${this.queueType} queue provider...`),!["bullmq","sqs","pgboss"].includes(this.queueType)){this.logger.error(`Invalid queue type: ${this.queueType}. Must be one of: bullmq, sqs, pgboss`);return}let[e,t]=await q();if(["npm","yarn","pnpm"].includes(e)){let c=this.queueDependencies[this.queueType],a=await V(c);if(a.length>0&&(this.logger.info(`Found ${a.length} missing dependencies for ${this.queueType}`),!await C(`${e} ${t} ${a.join(" ")}`,e,a,{stdio:"inherit"},false))){this.logger.info("Installation cancelled by user. Queue initialization aborted.");return}a.length===0&&this.logger.info(`All ${this.queueType} dependencies are already installed`);}let s=this.getConfigTemplate(),i=`${this.queueType}.config.ts`,n=d.join(this.outputPath,i);await m.exists(this.outputPath)||await m.mkdir(this.outputPath,{recursive:true}),this.logger.info(`Creating ${i} file at ${this.outputPath}...`),await m.writeFile(n,new TextEncoder().encode(s)),this.logger.info(`Queue configuration initialized successfully at ${n}`),this.logger.info("Remember to update the configuration with your actual credentials"),this.logger.info("Use 'npx balda generate-queue' to create queue handlers");}static getConfigTemplate(){return this.queueType==="bullmq"?this.getBullMQTemplate():this.queueType==="sqs"?this.getSQSTemplate():this.queueType==="pgboss"?this.getPGBossTemplate():""}static getBullMQTemplate(){return `import { defineBullMQConfiguration } from "balda";
153
+
154
+ defineBullMQConfiguration({
155
+ connection: {
156
+ host: process.env.REDIS_HOST || "localhost",
157
+ port: parseInt(process.env.REDIS_PORT || "6379", 10),
158
+ password: process.env.REDIS_PASSWORD,
159
+ },
160
+ defaultJobOptions: {
161
+ attempts: 3,
162
+ backoff: {
163
+ type: "exponential",
164
+ delay: 1000,
165
+ },
166
+ },
167
+ errorHandler: async (job, error) => {
168
+ console.error(\`Job \${job.id} failed:\`, error);
169
+ },
170
+ });
171
+ `}static getSQSTemplate(){return `import { defineSQSConfiguration } from "balda";
172
+
173
+ defineSQSConfiguration({
174
+ client: {
175
+ region: process.env.AWS_REGION || "us-east-1",
176
+ credentials: {
177
+ accessKeyId: process.env.AWS_ACCESS_KEY_ID || "",
178
+ secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY || "",
179
+ },
180
+ },
181
+ consumer: {
182
+ batchSize: 10,
183
+ visibilityTimeout: 30,
184
+ waitTimeSeconds: 20,
185
+ queueUrlMap: {
186
+ // Map your queue topics to SQS queue URLs
187
+ // Example: "user-notifications": process.env.USER_NOTIFICATIONS_QUEUE_URL || "",
188
+ },
189
+ },
190
+ errorHandler: (error) => {
191
+ console.error("SQS error:", error);
192
+ },
193
+ });
194
+ `}static getPGBossTemplate(){return `import { definePGBossConfiguration } from "balda";
195
+
196
+ definePGBossConfiguration({
197
+ connectionString:
198
+ process.env.DATABASE_URL ||
199
+ "postgresql://user:password@localhost:5432/database",
200
+ errorHandler: (error) => {
201
+ console.error("PG-Boss error:", error);
202
+ },
203
+ });
204
+ `}};p([u.string({description:"Queue provider type (bullmq, sqs, pgboss) - required",aliases:"t",name:"type",required:true})],D,"queueType"),p([u.string({description:"Output directory for queue configuration, default is src/queue",aliases:"o",name:"output",required:false,defaultValue:"src/queue"})],D,"outputPath");var G=class extends h{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=$.getBuiltInCommands(),t=$.getUserDefinedCommands();if(console.log(`
205
+ \u2728 Available Balda Commands:
206
+ `),t.length>0){console.log(`\x1B[1;33mUser Commands:\x1B[0m
207
+ `);let s=this.groupByCategory(t);this.displayCategorizedCommands(s);}if(e.length>0){console.log(`\x1B[1;32mBuilt-in Commands:\x1B[0m
208
+ `);let s=Math.max(...e.map(i=>i.commandName.length));for(let i of e){let n=i.commandName.padEnd(s+2),c=i.description||"No description available",a="";i.options?.deprecated&&(a=" \x1B[33m[deprecated]\x1B[0m"),console.log(` \x1B[36m${n}\x1B[0m ${c}${a}`);}console.log("");}console.log(`\x1B[90mRun 'npx balda <command> -h' for more information on a specific command.\x1B[0m
209
+ `);}static groupByCategory(e){let t=new Map;for(let s of e){let i=s.options?.category||"other";t.has(i)||t.set(i,[]),t.get(i).push(s);}return t}static displayCategorizedCommands(e){let t=Array.from(e.keys()).sort();for(let s of t){let i=e.get(s).filter(l=>l&&l.commandName);if(i.length===0)continue;let c={generator:"\x1B[35m",setup:"\x1B[34m",production:"\x1B[32m",utility:"\x1B[36m",other:"\x1B[37m"}[s]||"\x1B[37m";console.log(` ${c}${s.toUpperCase()}:\x1B[0m`);let a=Math.max(...i.map(l=>l.commandName.length));for(let l of i){let o=l.commandName.padEnd(a+2),g=l.description||"No description available",T="";l.options?.deprecated&&(T=" \x1B[33m[deprecated]\x1B[0m"),console.log(` \x1B[36m${o}\x1B[0m ${g}${T}`);}console.log("");}}};var L=class extends h{static commandName="serve";static description="Run the server in dev mode with hot reload";static help=["This command is intended to be run from the root of the project","Bun and Deno have native dev hot reload","Runtime is automatically inferred","Node.js requires tsx to be installed for both typescript and javascript files","Node.js dev dependencies (tsx) are installed automatically if not detected"];static runtime=y.type;static options={keepAlive:true};static entry;static denoImportMap;static async handle(){if(this.runtime==="bun"){execSync(`bun run --watch ${this.entry}`,{stdio:"inherit",cwd:W.getCwd()});return}if(this.runtime==="deno"){let e="deno run --watch --unstable-sloppy-imports --allow-all";this.denoImportMap&&(e=`${e} --import-map ${this.denoImportMap}`),execSync(`${e} ${this.entry}`,{stdio:"inherit",cwd:W.getCwd()});return}this.handleNodeHotReload();}static async handleNodeHotReload(){if(!X.existsSync("node_modules/.bin/tsx")){let[s,i,n]=await q();if(!await C(`${s} ${i} tsx ${n}`,s,["tsx"],{stdio:"inherit"})){this.logger.info("Installation cancelled by user. Cannot start dev server without tsx.");return}}let t=this.calledBy!=="node"?this.calledBy:"npx";execSync(`${t} tsx watch ${this.entry}`,{stdio:"inherit",cwd:process.cwd()});}};p([x({required:false,defaultValue:"src/index.ts",description:"The entry point of the project, default is src/index.ts"})],L,"entry"),p([u.string({aliases:["d"],name:"deno-import-map",required:false,description:"Path to deno import map"})],L,"denoImportMap");var U=class extends h{static commandName="setup-storage";static description="Setup storage provider with required dependencies";static help=["Install dependencies and create storage configuration for a specific provider","Flags:"," -t, --type <provider> Storage provider type (s3, azure, local)"," -o, --output <path> Output directory for storage setup (default: src/storage/)","","Examples:"," npx balda setup:storage -t s3"," npx balda setup:storage --type azure --output src/config/"];static storageType;static outputPath;static async handle(){if(!this.storageType){console.error("\x1B[31m\u274C Error: Storage type is required. Use -t or --type flag.\x1B[0m"),console.log(`\x1B[90mExample: npx balda setup:storage -t s3\x1B[0m
210
+ `);return}this.outputPath||await m.mkdir(d.join(process.cwd(),this.outputPath),{recursive:true});let e=["s3","azure","local"];if(!e.includes(this.storageType)){console.error(`\x1B[31m\u274C Error: Invalid storage type '${this.storageType}'. Valid types: ${e.join(", ")}\x1B[0m
211
+ `);return}console.log(`
212
+ \u{1F680} Setting up ${this.storageType.toUpperCase()} storage provider...
213
+ `);let t=this.getDependencies(this.storageType);if(t.length===0&&console.log(`\x1B[32m\u2705 ${this.storageType.toUpperCase()} storage doesn't require additional dependencies.\x1B[0m
214
+ `),t.length){let s=await this.checkMissingDependencies(t);if(s.length===0&&console.log(`\x1B[32m\u2705 All required dependencies are already installed.\x1B[0m
215
+ `),s.length){let[i,n]=await q(),c=`${i} ${n} ${s.join(" ")}`;if(!await C(c,i,s,{stdio:"inherit"},false)){console.log(`\x1B[33m\u26A0\uFE0F Dependency installation skipped by user.\x1B[0m
216
+ `);return}console.log(`
217
+ \x1B[32m\u2705 Dependencies installed successfully!\x1B[0m
218
+ `);}}await this.createStorageSetup(this.storageType,this.outputPath),console.log(`\x1B[32m\u2728 ${this.storageType.toUpperCase()} storage setup complete!\x1B[0m
219
+ `);}static getDependencies(e){return {s3:["@aws-sdk/client-s3","@aws-sdk/s3-request-presigner","@aws-sdk/cloudfront-signer"],azure:["@azure/storage-blob"],local:[]}[e]||[]}static async checkMissingDependencies(e){let t=d.join(process.cwd(),"package.json");if(!await m.exists(t))return e;let i=d.join(process.cwd(),"node_modules");if(!await m.exists(i))return e;let c=[];for(let a of e){let l=d.join(i,a);await m.exists(l)||c.push(a);}return c}static async createStorageSetup(e,t){let s=d.join(process.cwd(),t);await m.exists(s)||await m.mkdir(s,{recursive:true});let n=d.join(s,"storage.ts");if(await m.exists(n)){console.log(`\x1B[33m\u26A0\uFE0F Configuration file already exists: ${n}\x1B[0m`);return}let a=this.getConfigTemplate(e);await m.writeFile(n,new TextEncoder().encode(a)),console.log(`\x1B[32m\u2705 Created configuration file: ${n}\x1B[0m`);}static getConfigTemplate(e){return {s3:`import { Storage, S3StorageProvider } from "balda";
220
+
221
+ /**
222
+ * S3 Storage Configuration
223
+ *
224
+ * Environment variables required:
225
+ * - AWS_ACCESS_KEY_ID
226
+ * - AWS_SECRET_ACCESS_KEY
227
+ * - AWS_REGION
228
+ * - S3_BUCKET
229
+ *
230
+ * Optional for CloudFront:
231
+ * - CLOUDFRONT_DOMAIN
232
+ * - CLOUDFRONT_KEY_PAIR_ID
233
+ * - CLOUDFRONT_PRIVATE_KEY
234
+ */
235
+
236
+ export const storage = new Storage(
237
+ {
238
+ s3: new S3StorageProvider({
239
+ s3ClientConfig: {
240
+ bucketName: process.env.S3_BUCKET || "your-bucket-name",
241
+ region: process.env.AWS_REGION || "us-east-1",
242
+ credentials: {
243
+ accessKeyId: process.env.AWS_ACCESS_KEY_ID || "",
244
+ secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY || "",
245
+ },
246
+ },
247
+ // Uncomment to enable CloudFront signed URLs
248
+ // cloudfrontOptions: {
249
+ // domainName: process.env.CLOUDFRONT_DOMAIN || "",
250
+ // keyPairId: process.env.CLOUDFRONT_KEY_PAIR_ID || "",
251
+ // privateKey: process.env.CLOUDFRONT_PRIVATE_KEY || "",
252
+ // },
253
+ }),
254
+ },
255
+ {
256
+ defaultProvider: "s3",
257
+ },
258
+ );
259
+ `,azure:`import { Storage, AzureBlobStorageProvider } from "balda";
260
+
261
+ /**
262
+ * Azure Blob Storage Configuration
263
+ *
264
+ * Environment variables required:
265
+ * - AZURE_STORAGE_CONNECTION_STRING
266
+ * - AZURE_CONTAINER_NAME
267
+ * - AZURE_STORAGE_ACCOUNT
268
+ * - AZURE_STORAGE_KEY
269
+ */
270
+
271
+ export const storage = new Storage(
272
+ {
273
+ azure: new AzureBlobStorageProvider({
274
+ containerName: process.env.AZURE_CONTAINER_NAME || "your-container-name",
275
+ connectionString: process.env.AZURE_STORAGE_CONNECTION_STRING || "",
276
+ storageAccountName: process.env.AZURE_STORAGE_ACCOUNT || "",
277
+ storageAccountKey: process.env.AZURE_STORAGE_KEY || "",
278
+ }),
279
+ },
280
+ {
281
+ defaultProvider: "azure",
282
+ },
283
+ );
284
+ `,local:`import { Storage, LocalStorageProvider } from "balda";
285
+
286
+ /**
287
+ * Local Storage Configuration
288
+ */
289
+ export const storage = new Storage(
290
+ {
291
+ local: new LocalStorageProvider({
292
+ directory: "./uploads",
293
+ }),
294
+ },
295
+ {
296
+ defaultProvider: "local",
297
+ },
298
+ );
299
+ `}[e]||""}};p([u({description:"Storage provider type (s3, azure, local)",type:"string",aliases:["t"],name:"type",required:true})],U,"storageType"),p([u({description:"Output directory for storage setup",type:"string",aliases:["o"],name:"output",required:false,defaultValue:"src/storage/"})],U,"outputPath");var qe=[_,z,M,O,E,F,I,S,D,G,v,L,U],j=class r{commands;builtInCommands;static commandsPattern="src/commands/**/*.{ts,js}";static logger=Z;constructor(){this.commands=new Map,this.builtInCommands=new Set;}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())}getBuiltInCommands(){return Array.from(this.commands.values()).filter(e=>this.builtInCommands.has(e.commandName))}getUserDefinedCommands(){return Array.from(this.commands.values()).filter(e=>!this.builtInCommands.has(e.commandName))}isBuiltInCommand(e){return this.builtInCommands.has(e)}async loadCommands(e){r.logger.info(`Loading commands from ${e}`);let t=await glob(e,{absolute:true,cwd:W.getCwd()});if(t.some(s=>s.endsWith(".ts")))try{let{register:s}=await import('module');s("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 s of t){let i=await import(s).then(n=>n.default?n.default:n).catch(n=>(r.logger.error(`Error loading command ${s}: ${n}`),null));i&&this.commands.set(i.commandName,i);}for(let s of qe)this.commands.set(s.commandName,s),this.builtInCommands.add(s.commandName);}},$=j.getInstance();var Ae=r=>{let e=new Map;for(let t of r){let s=t.options?.category||"other";e.has(s)||e.set(s,[]),e.get(s).push(t);}return e},Ne=r=>{let e=Array.from(r.keys()).sort();for(let t of e){let s=r.get(t).filter(a=>a&&a.commandName);if(!s.length)continue;let n={generator:"\x1B[35m",setup:"\x1B[34m",production:"\x1B[32m",utility:"\x1B[36m",other:"\x1B[37m"}[t]||"\x1B[37m";console.log(` ${n}${t.toUpperCase()}:\x1B[0m`);let c=Math.max(...s.map(a=>a.commandName.length));for(let a of s){let l=a.commandName.padEnd(c+2),o=a.description||"No description available",g="";a.options?.deprecated&&(g=" \x1B[33m[deprecated]\x1B[0m"),console.log(` \x1B[36m${l}\x1B[0m ${o}${g}`);}console.log("");}},ce=async()=>{await $.loadCommands(j.commandsPattern);let[r,...e]=B.getCliArgs();if(!r||r==="-h"||r==="--help"){let n=$.getBuiltInCommands(),c=$.getUserDefinedCommands();if(console.log(`
300
+ \u2728 Available Balda Commands:
301
+ `),c.length&&(console.log(`\x1B[1;33mUser Commands:\x1B[0m
302
+ `),Ne(Ae(c))),n.length){console.log(`\x1B[1;32mBuilt-in Commands:\x1B[0m
303
+ `);let a=Math.max(...n.map(l=>l.commandName.length));for(let l of n){let o=l.commandName.padEnd(a+2),g=l.description||"No description available",T="";l.options?.deprecated&&(T=" \x1B[33m[deprecated]\x1B[0m"),console.log(` \x1B[36m${o}\x1B[0m ${g}${T}`);}console.log("");}console.log(`\x1B[90mRun 'npx balda <command> -h' for more information on a specific command.\x1B[0m
304
+ `),N.exit(0);return}let t=$.getCommand(r);if(!t){console.error(pe(r,$.getCommands().filter(n=>n&&n.commandName).map(n=>n.commandName))||`Command ${r} not found`),N.exit(1);return}let s=t;if(s.calledBy=d.basename(B.getCliCaller()),s.options?.deprecated){let n=s.options.deprecated.message||"This command is deprecated",c=s.options.deprecated.replacement;console.warn(`\x1B[33m\u26A0\uFE0F Warning: ${n}\x1B[0m`),c&&console.warn(`\x1B[33m Use '${c}' instead.\x1B[0m
305
+ `);}if(s.handleHelpFlag(s.flags),s.validateContext(s),s.options?.validate&&!await s.options.validate(s)){console.error("Command validation failed"),N.exit(1);return}await s.handle(),(t.options?.keepAlive??false)||N.exit(0);};typeof process<"u"?ce().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),ce().catch(t=>{j.logger.error(t),process.exit(1);});}catch{j.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 j.logger.error(r),process.exit(1);}):ce().catch(r=>{j.logger.error(r),N.exit(1);});export{ce as cli};//# sourceMappingURL=cli.js.map
306
+ //# sourceMappingURL=cli.js.map