balda-js 0.0.77 → 0.0.78
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 +21 -21
- package/lib/cli.js.map +1 -1
- package/lib/index.cjs +19 -19
- package/lib/index.cjs.map +1 -1
- package/lib/index.js +19 -19
- package/lib/index.js.map +1 -1
- package/package.json +1 -1
package/lib/cli.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {glob}from'glob';import ye from'pino';import Z from'fs';import K from'path';import {execSync}from'child_process';import*as de from'readline';var ge=Object.defineProperty;var
|
|
3
|
-
\x1B[32m\u{1F4A1}\x1B[0m Did you mean: ${n}?`},G=()=>M.getCliArgs()[0]||null;var be=()=>ye({level:"info",formatters:{level:e=>({level:e})}}),Y=be();var X=class{getCwd(){switch(y.type){case "node":case "bun":return process.cwd();case "deno":return Deno.cwd();default:throw new Error("Unsupported runtime")}}},V=new X;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 k="VALIDATION_ERROR";var me=P().args.slice(1),x=r=>(e,t)=>{let s=G();if(!s||s!==e.commandName)return;let
|
|
4
|
-
`)};static validateContext=e=>{let t=Array.from(w.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((
|
|
2
|
+
import {glob}from'glob';import ye from'pino';import Z from'fs';import K from'path';import {execSync}from'child_process';import*as de from'readline';var ge=Object.defineProperty;var p=(r,e,t,s)=>{for(var i=void 0,n=r.length-1,o;n>=0;n--)(o=r[n])&&(i=(o(e,t,i))||i);return i&&ge(e,t,i),i};var J=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 J;var Q=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}},M=new Q;var ie=(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]},ae=r=>r.toLowerCase().replace(/[-_.]/g,"_").replace(/([A-Z])/g,"_$1").replace(/^_+/,"").replace(/_+$/,"").toLowerCase(),W=r=>r.split(/[-_.]/g).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),oe=r=>r.split(/[-_.]/g).map(e=>e.toLowerCase()).join("-");var he=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:ce(s)}}return {name:r,value:true}},ce=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},P=()=>{let r=M.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=he(i);if(n){if(n.value===true&&s+1<r.length){let o=r[s+1];o&&typeof o=="string"&&!o.startsWith("-")&&(n.value=ce(o),s++);}if(n.name in t){let o=t[n.name];Array.isArray(o)?o.push(n.value):t[n.name]=[o,n.value];}else t[n.name]=n.value;}continue}e.push(i);}}return {args:e,flags:t}},le=(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 l=o.toLowerCase();if(l===t||l.includes(t)||t.includes(l))return true;let c=ie(l,t),a=Math.max(t.length,l.length)*.4;return c<=a});if(s.length===0)return "";let n=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: ${n}?`},G=()=>M.getCliArgs()[0]||null;var be=()=>ye({level:"info",formatters:{level:e=>({level:e})}}),Y=be();var X=class{getCwd(){switch(y.type){case "node":case "bun":return process.cwd();case "deno":return Deno.cwd();default:throw new Error("Unsupported runtime")}}},V=new X;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 k="VALIDATION_ERROR";var me=P().args.slice(1),x=r=>(e,t)=>{let s=G();if(!s||s!==e.commandName)return;let i=t;w.set(e,t,{type:"arg",name:i,description:r.description});let n=me.length?me.shift():r.defaultValue;if(r.required&&!n){let o=w.get(e,k);w.set(e,k,[...o||[],{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=G();if(!s||s!==e.commandName)return;let i=r.name||t,n=P().flags,o=r.aliases||[],l=[i,...o],c=r.defaultValue;for(let a of l){let u=[a,`-${a}`,`--${a}`];for(let $ of u)if($ in n){let R=n[$];r.type==="list"?c=(Array.isArray(R)?R:[R]).map(g=>{let b=String(g);return r.parse?r.parse(b):b}):(c=R,r.type==="boolean"?c=!!c:r.type==="number"&&(c=Number(c)),r.parse&&(c=r.parse(c)));break}if(c!==r.defaultValue)break}if(w.set(e,t,{type:"flag",name:i,aliases:o||[],description:r.description}),r.required&&(r.type==="list"?!c||Array.isArray(c)&&c.length===0:!c)){let u=w.get(e,k);w.set(e,k,[...u||[],{type:"flag",name:i,message:"Required flag not provided"}]);return}Object.defineProperty(e,t,{value:c,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 f=A;var ee=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 ee;var h=class{static commandName=this.name;static calledBy=this.name;static description="";static help=[];static options={keepAlive:false};static args=P().args.slice(1);static flags=P().flags;static logger=Y;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(a=>t.includes(a)))return;let i=this.commandName,n=this.description||"No description available",o=this.help||[],l=this.options,c=this.generateHelpOutput({name:i,description:n,helpText:o,options:l,args:this.args,flags:this.flags},this);console.log(c),N.exit(0);}static generateHelpOutput=(e,t)=>{let{name:s,description:i,helpText:n,options:o,args:l,flags:c}=e,a={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=[`${a.title}${s}${a.reset}`,`${a.description}${i}${a.reset}`,"",`${a.subtitle}Usage:${a.reset}`,` ${a.code}${s}${a.reset} [options] [arguments]`,"",`${a.subtitle}Options:${a.reset}`,` ${a.flag}-h, --help${a.reset} Show this help message`,"",`${a.subtitle}Command Options:${a.reset}`,` ${a.flag}keepAlive${a.reset} ${o?.keepAlive??false?a.success+"Enabled"+a.reset:a.error+"Disabled"+a.reset}`,""];if(n){let g=Array.isArray(n)?n:[n];u.push(`${a.subtitle}Help:${a.reset}`),g.forEach(b=>{u.push(` ${a.description}${b}${a.reset}`);}),u.push("");}let $=w.getAll(t),R=Array.from($.values()).filter(g=>g.type==="arg"),H=Array.from($.values()).filter(g=>g.type==="flag");return R.length&&(u.push(`${a.subtitle}Available Arguments:${a.reset}`),R.forEach(g=>{let b=g.required?` ${a.error}(required)${a.reset}`:"",B=g.description?` ${a.description}${g.description}${a.reset}`:"";u.push(` ${a.code}${g.name}${a.reset}${b}${B}`);}),u.push("")),H.length&&(u.push(`${a.subtitle}Available Flags:${a.reset}`),H.forEach(g=>{g.aliases&&!Array.isArray(g.aliases)&&(g.aliases=[g.aliases]);let b=g.aliases.length?` ${a.flag}(${g.aliases.join(", ")})${a.reset}`:"",B=g.required?` ${a.error}(required)${a.reset}`:"",ue=g.description?` ${a.description}${g.description}${a.reset}`:"";u.push(` ${a.flag}--${g.name}${b}${a.reset}${B}${ue}`);}),u.push("")),((l?.length??0)>0||c&&Object.keys(c).length>0)&&(u.push(`${a.subtitle}Current Context:${a.reset}`),l?.length&&u.push(` ${a.info}Provided Arguments:${a.reset} ${a.code}${l.join(" ")}${a.reset}`),c&&Object.keys(c).length>0&&(u.push(` ${a.info}Provided Flags:${a.reset}`),Object.keys(c).forEach(g=>{let b=c[g],B=b!=null?` = ${a.code}${b}${a.reset}`:"";u.push(` ${a.flag}${g}${a.reset}${B}`);})),u.push("")),n&&(Array.isArray(n)?n.some(g=>g.includes("example")):n.includes("example"))&&(u.push(`${a.subtitle}Examples:${a.reset}`),(Array.isArray(n)?n.filter(b=>b.includes("example")):[n.split("example")[1].trim()]).forEach(b=>{u.push(` ${a.code}${b}${a.reset}`);}),u.push("")),u.join(`
|
|
4
|
+
`)};static validateContext=e=>{let t=Array.from(w.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,n)=>{let o=`${s.info}${n+1}.${s.reset}`,l=`${s.error}${i.type.toUpperCase()}${s.reset}`,c=`${s.code}${i.name}${s.reset}`;console.error(` ${o} ${l} ${c}: ${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 te=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 o=await Deno.readFile(e);return t?.encoding==="utf8"?new TextDecoder().decode(o):new Uint8Array(o)}}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 o=await Deno.stat(e);return {isDirectory:o.isDirectory,isFile:o.isFile,isSymbolicLink:false,size:o.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 te;var se=class{basename(e){switch(y.type){case "node":case "bun":case "deno":return K.basename(e);default:throw new Error("Unsupported runtime")}}join(...e){switch(y.type){case "node":case "bun":case "deno":return K.join(...e);default:throw new Error("Unsupported runtime")}}extName(e){switch(y.type){case "bun":case "node":case "deno":return K.extname(e);default:throw new Error("Unsupported runtime")}}resolve(...e){switch(y.type){case "bun":case "node":case "deno":return K.resolve(...e);default:throw new Error("Unsupported runtime")}}},d=new se;var j=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"],E=async(r,e,t,s,i=true)=>{let n=de.createInterface({input:process.stdin,output:process.stdout}),o=t.join(", "),l=`Do you want to install the following ${i?"dev":""} dependencies using ${e}?
|
|
5
5
|
${o}
|
|
6
|
-
(y/n): `;return new Promise(c=>{n.question(l,
|
|
6
|
+
(y/n): `;return new Promise(c=>{n.question(l,a=>{if(n.close(),a.toLowerCase()==="y"||a.toLowerCase()==="yes"){execSync(r,s),c(true);return}c(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(l=>true).catch(()=>false)){let[l,c,a]=await j();await E(`${l} ${c} esbuild ${a}`,l,["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(l=>{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=K.join(this.output,"assets"),i=[];if(this.assets){let{copy:l}=await import('esbuild-plugin-copy').catch(c=>{throw this.logger.error("esbuild-plugin-copy is not installed, please install it with `npm install -D esbuild-plugin-copy` to use the build command"),new Error("esbuild-plugin-copy is not installed")});Z.existsSync(s)||Z.mkdirSync(s,{recursive:true}),i.push(l({assets:{from:this.assets,to:s}}));}this.clearDist&&Z.existsSync(this.output)&&(this.logger.info("Clearing dist directory..."),Z.rmSync(this.output,{recursive:true})),this.logger.info("Building project...");let n=K.join(this.output,"server.js"),o=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});o.errors.length&&(this.logger.error(JSON.stringify({message:"Failed to build the project",errors:o.errors},null,2)),process.exit(1)),o.warnings.length&&this.logger.warn(JSON.stringify({message:"Failed to build the project",warnings:o.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([f({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([f({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([f({type:"string",aliases:["o"],name:"output",required:false,defaultValue:"./dist",description:"The path to the output directory, default is ./dist"})],v,"output"),p([f({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([f({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([f({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([f({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([f({type:"boolean",aliases:["s"],name:"sourcemap",required:false,defaultValue:true,description:"Whether to generate sourcemaps or not, default is true"})],v,"sourcemap");var U=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(C.getCommand(this.name)){let i=C.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-js";
|
|
7
7
|
|
|
8
8
|
export default class extends Command {
|
|
9
9
|
static commandName = "${this.name}";
|
|
@@ -17,7 +17,7 @@ export default class extends Command {
|
|
|
17
17
|
static async handle(): Promise<void> {
|
|
18
18
|
// Implement your command logic here
|
|
19
19
|
}
|
|
20
|
-
}`}};
|
|
20
|
+
}`}};p([x({description:"The name of the command to generate",required:true})],U,"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=W(this.controllerName);return `import { controller, get, post, put, del, Request, Response } from "balda-js";
|
|
21
21
|
|
|
22
22
|
@controller("/${oe(this.controllerName)}")
|
|
23
23
|
export default class ${e}Controller {
|
|
@@ -45,7 +45,7 @@ export default class ${e}Controller {
|
|
|
45
45
|
async destroy(req: Request, res: Response) {
|
|
46
46
|
return { message: \`Delete ${this.controllerName.toLowerCase()} with id \${req.params.id}\` };
|
|
47
47
|
}
|
|
48
|
-
}`}};
|
|
48
|
+
}`}};p([x({description:"The name of the controller to generate",required:true})],F,"controllerName"),p([f({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 O=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-js";
|
|
49
49
|
|
|
50
50
|
export default class extends BaseCron {
|
|
51
51
|
@cron("* * * * *")
|
|
@@ -53,7 +53,7 @@ export default class extends BaseCron {
|
|
|
53
53
|
this.logger.info("Running cron job");
|
|
54
54
|
// Implement your cron job logic here
|
|
55
55
|
}
|
|
56
|
-
}`}};
|
|
56
|
+
}`}};p([x({description:"The name of the cron job file to generate",required:true})],O,"fileName"),p([f({description:"The path to the cron job to generate, default is src/cron",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/cron"})],O,"path");var q=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=W(this.middlewareName);return `import type { Request, Response, NextFunction, ServerRouteMiddleware } from "balda-js";
|
|
57
57
|
|
|
58
58
|
/**
|
|
59
59
|
* ${e} middleware
|
|
@@ -64,7 +64,7 @@ export const ${e}: ServerRouteMiddleware = async () => {
|
|
|
64
64
|
// Add your middleware logic here
|
|
65
65
|
return next();
|
|
66
66
|
};
|
|
67
|
-
};`}};
|
|
67
|
+
};`}};p([x({description:"The name of the middleware to generate",required:true})],q,"middlewareName"),p([f({description:"The path to the middleware to generate, default is src/middlewares",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/middlewares"})],q,"path");var I=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-js";
|
|
68
68
|
|
|
69
69
|
export default class extends BasePlugin {
|
|
70
70
|
async handle(): Promise<ServerRouteMiddleware> {
|
|
@@ -73,7 +73,7 @@ export default class extends BasePlugin {
|
|
|
73
73
|
await next();
|
|
74
74
|
};
|
|
75
75
|
}
|
|
76
|
-
}`}};
|
|
76
|
+
}`}};p([x({description:"The name of the plugin to generate",required:true})],I,"pluginName"),p([f({description:"The path to the plugin to generate, default is src/plugins",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/plugins"})],I,"pluginPath");var S=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,`${ae(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-js";
|
|
77
77
|
|
|
78
78
|
export type Payload = {
|
|
79
79
|
// Add your payload here
|
|
@@ -92,7 +92,7 @@ export default class extends BaseQueue {
|
|
|
92
92
|
this.logger.info({ payload }, 'Payload received');
|
|
93
93
|
return Promise.resolve();
|
|
94
94
|
}
|
|
95
|
-
}`}};
|
|
95
|
+
}`}};p([x({description:"The name of the queue to generate",required:true})],S,"queueName"),p([f({description:"The path to the queue to generate, default is src/queues",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/queues"})],S,"path"),p([f({description:"The provider of the queue to generate, default is bullmq",type:"string",aliases:["pr"],name:"provider",required:false,defaultValue:"bullmq"})],S,"provider");var _=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-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 j();if(["npm","yarn","pnpm"].includes(e)&&!await E(`${e} ${t} ${this.devDependencies.join(" ")} -${s}`,e,this.devDependencies,{stdio:"inherit"})){this.logger.info("Installation cancelled by user. Project initialization aborted.");return}let i=this.typescript?"ts":"js",n=this.getServerTemplate(),o=this.getIndexTemplate();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(o)),this.logger.info("Project initialized successfully!");}static getServerTemplate(){return `import { Server } from "balda-js";
|
|
96
96
|
|
|
97
97
|
const serverInstance = new Server({
|
|
98
98
|
port: 80,
|
|
@@ -110,22 +110,22 @@ export { serverInstance as server };
|
|
|
110
110
|
server.listen(({ url }) => {
|
|
111
111
|
console.log(\`Server is running on \${url}\`);
|
|
112
112
|
});
|
|
113
|
-
`}};
|
|
113
|
+
`}};p([f.string({description:"The path to the project, default is the current directory /src",aliases:"p",name:"path",required:false,defaultValue:"./src"})],_,"srcPath"),p([f.boolean({description:"Whether to use typescript, default is true",aliases:"t",name:"typescript",required:false,defaultValue:true})],_,"typescript");var z=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=C.getBuiltInCommands(),t=C.getUserDefinedCommands();if(console.log(`
|
|
114
114
|
\u2728 Available Balda Commands:
|
|
115
115
|
`),t.length>0){console.log(`\x1B[1;33mUser Commands:\x1B[0m
|
|
116
116
|
`);let s=this.groupByCategory(t);this.displayCategorizedCommands(s);}if(e.length>0){console.log(`\x1B[1;32mBuilt-in Commands:\x1B[0m
|
|
117
|
-
`);let s=Math.max(...e.map(
|
|
118
|
-
`);}static groupByCategory(e){let t=new Map;for(let s of e){let
|
|
119
|
-
`);return}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
|
|
117
|
+
`);let s=Math.max(...e.map(i=>i.commandName.length));for(let i of e){let n=i.commandName.padEnd(s+2),o=i.description||"No description available",l="";i.options?.deprecated&&(l=" \x1B[33m[deprecated]\x1B[0m"),console.log(` \x1B[36m${n}\x1B[0m ${o}${l}`);}console.log("");}console.log(`\x1B[90mRun 'npx balda <command> -h' for more information on a specific command.\x1B[0m
|
|
118
|
+
`);}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(c=>c&&c.commandName);if(i.length===0)continue;let o={generator:"\x1B[35m",setup:"\x1B[34m",production:"\x1B[32m",utility:"\x1B[36m",other:"\x1B[37m"}[s]||"\x1B[37m";console.log(` ${o}${s.toUpperCase()}:\x1B[0m`);let l=Math.max(...i.map(c=>c.commandName.length));for(let c of i){let a=c.commandName.padEnd(l+2),u=c.description||"No description available",$="";c.options?.deprecated&&($=" \x1B[33m[deprecated]\x1B[0m"),console.log(` \x1B[36m${a}\x1B[0m ${u}${$}`);}console.log("");}}};var D=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:V.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:V.getCwd()});return}this.handleNodeHotReload();}static async handleNodeHotReload(){if(!Z.existsSync("node_modules/.bin/tsx")){let[s,i,n]=await j();if(!await E(`${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"})],D,"entry"),p([f.string({aliases:["d"],name:"deno-import-map",required:false,description:"Path to deno import map"})],D,"denoImportMap");var L=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
|
|
119
|
+
`);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
|
|
120
120
|
`);return}console.log(`
|
|
121
121
|
\u{1F680} Setting up ${this.storageType.toUpperCase()} storage provider...
|
|
122
|
-
`);let t=this.getDependencies(this.storageType);if(t.length
|
|
123
|
-
`),t.length
|
|
124
|
-
`),s.length
|
|
122
|
+
`);let t=this.getDependencies(this.storageType);if(t.length&&console.log(`\x1B[32m\u2705 ${this.storageType.toUpperCase()} storage doesn't require additional dependencies.\x1B[0m
|
|
123
|
+
`),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
|
|
124
|
+
`),s.length){let[i,n,o]=await j(),l=`${i} ${n} ${o} ${s.join(" ")}`;if(!await E(l,i,s,{stdio:"inherit"},true)){console.log(`\x1B[33m\u26A0\uFE0F Dependency installation skipped by user.\x1B[0m
|
|
125
125
|
`);return}console.log(`
|
|
126
126
|
\x1B[32m\u2705 Dependencies installed successfully!\x1B[0m
|
|
127
127
|
`);}}await this.createStorageSetup(this.storageType,this.outputPath),console.log(`\x1B[32m\u2728 ${this.storageType.toUpperCase()} storage setup complete!\x1B[0m
|
|
128
|
-
`);}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=
|
|
128
|
+
`);}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 o=await m.readdir(i);return e.filter(c=>!o.includes(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,`${e}.config.ts`);if(await m.exists(n)){console.log(`\x1B[33m\u26A0\uFE0F Configuration file already exists: ${n}\x1B[0m`);return}let l=this.getConfigTemplate(e);await m.writeFile(n,new TextEncoder().encode(l)),console.log(`\x1B[32m\u2705 Created configuration file: ${n}\x1B[0m`);}static getConfigTemplate(e){return {s3:`import { S3StorageProvider } from "balda";
|
|
129
129
|
|
|
130
130
|
/**
|
|
131
131
|
* S3 Storage Configuration
|
|
@@ -192,11 +192,11 @@ export const azureProvider = new AzureBlobStorageProvider({
|
|
|
192
192
|
export const localProvider = new LocalStorageProvider({
|
|
193
193
|
directory: process.env.LOCAL_STORAGE_DIR || "./storage",
|
|
194
194
|
});
|
|
195
|
-
`}[e]||""}};
|
|
195
|
+
`}[e]||""}};p([f({description:"Storage provider type (s3, azure, local)",type:"string",aliases:["t"],name:"type",required:true})],L,"storageType"),p([f({description:"Output directory for storage setup",type:"string",aliases:["o"],name:"output",required:false,defaultValue:"src/storage/"})],L,"outputPath");var Ce=[I,U,O,S,F,q,_,z,v,D,L],T=class r{commands;builtInCommands;static commandsPattern="src/commands/**/*.{ts,js}";static logger=Y;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:V.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 Ce)this.commands.set(s.commandName,s),this.builtInCommands.add(s.commandName);}},C=T.getInstance();var $e=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},Ae=r=>{let e=Array.from(r.keys()).sort();for(let t of e){let s=r.get(t).filter(l=>l&&l.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 o=Math.max(...s.map(l=>l.commandName.length));for(let l of s){let c=l.commandName.padEnd(o+2),a=l.description||"No description available",u="";l.options?.deprecated&&(u=" \x1B[33m[deprecated]\x1B[0m"),console.log(` \x1B[36m${c}\x1B[0m ${a}${u}`);}console.log("");}},ne=async()=>{await C.loadCommands(T.commandsPattern);let[r,...e]=M.getCliArgs();if(!r||r==="-h"||r==="--help"){let n=C.getBuiltInCommands(),o=C.getUserDefinedCommands();if(console.log(`
|
|
196
196
|
\u2728 Available Balda Commands:
|
|
197
197
|
`),o.length&&(console.log(`\x1B[1;33mUser Commands:\x1B[0m
|
|
198
198
|
`),Ae($e(o))),n.length){console.log(`\x1B[1;32mBuilt-in Commands:\x1B[0m
|
|
199
|
-
`);let l=Math.max(...n.map(c=>c.commandName.length));for(let c of n){let
|
|
200
|
-
`),N.exit(0);return}let t=C.getCommand(r);if(!t){console.error(le(r,C.getCommands().filter(n=>n&&n.commandName).map(n=>n.commandName))||`Command ${r} not found`),N.exit(1);return}let s=t;if(s.calledBy=
|
|
199
|
+
`);let l=Math.max(...n.map(c=>c.commandName.length));for(let c of n){let a=c.commandName.padEnd(l+2),u=c.description||"No description available",$="";c.options?.deprecated&&($=" \x1B[33m[deprecated]\x1B[0m"),console.log(` \x1B[36m${a}\x1B[0m ${u}${$}`);}console.log("");}console.log(`\x1B[90mRun 'npx balda <command> -h' for more information on a specific command.\x1B[0m
|
|
200
|
+
`),N.exit(0);return}let t=C.getCommand(r);if(!t){console.error(le(r,C.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(M.getCliCaller()),s.options?.deprecated){let n=s.options.deprecated.message||"This command is deprecated",o=s.options.deprecated.replacement;console.warn(`\x1B[33m\u26A0\uFE0F Warning: ${n}\x1B[0m`),o&&console.warn(`\x1B[33m Use '${o}' instead.\x1B[0m
|
|
201
201
|
`);}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"?ne().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),ne().catch(t=>{T.logger.error(t),process.exit(1);});}catch{T.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 T.logger.error(r),process.exit(1);}):ne().catch(r=>{T.logger.error(r),N.exit(1);});export{ne as cli};//# sourceMappingURL=cli.js.map
|
|
202
202
|
//# sourceMappingURL=cli.js.map
|