balda 0.0.52 → 0.0.53
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 +17 -17
- package/lib/cli.js.map +1 -1
- package/lib/index.cjs +25 -25
- package/lib/index.cjs.map +1 -1
- package/lib/index.d.cts +71 -22
- package/lib/index.d.ts +71 -22
- package/lib/index.js +25 -25
- package/lib/index.js.map +1 -1
- package/package.json +1 -1
package/lib/cli.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
\x1B[32m\u{1F4A1}\x1B[0m Did you mean: ${n}?`},Ee=()=>ye.getCliArgs()[0]||null;var
|
|
4
|
-
`)};static validateUnknownFlags=e=>{if(e.options?.allowUnknownFlags!==false)return;let t=new Set(["-h","--help"]),r=new Set,s=_.getAll(e);if(s){for(let c of s.values())if(c.type==="flag"&&(r.add(`--${c.name}`),r.add(`-${c.name}`),r.add(c.name),c.aliases)){let a=Array.isArray(c.aliases)?c.aliases:[c.aliases];for(let d of a)r.add(`--${d}`),r.add(`-${d}`),r.add(d);}}let n=Object.keys(e.flags).filter(c=>!t.has(c)&&!r.has(c));if(n.length){let c={error:"\x1B[0;31m",title:"\x1B[1;31m",reset:"\x1B[0m",info:"\x1B[0;34m",flag:"\x1B[0;35m"};console.error(`${c.title}\u274C Unknown Flags:${c.reset}`),console.error(""),n.forEach(a=>{console.error(` ${c.error}\u2022${c.reset} ${c.flag}${a}${c.reset}`);}),console.error(""),console.error(`${c.info}\u{1F4A1} Tip: Use --help for available flags${c.reset}`),z.exit(1);}};static validateContext=e=>{let t=Array.from(_.get(e,ee)||[]);if(t.length){let r={error:"\x1B[0;31m",title:"\x1B[1;31m",reset:"\x1B[0m",info:"\x1B[0;34m",code:"\x1B[0;32m"};console.error(`${r.title}\u274C Validation Errors:${r.reset}`),console.error(""),t.forEach((s,n)=>{let c=`${r.info}${n+1}.${r.reset}`,a=`${r.error}${s.type.toUpperCase()}${r.reset}`,d=`${r.code}${s.name}${r.reset}`;console.error(` ${c} ${a} ${d}: ${r.error}${s.message}${r.reset}`);}),console.error(""),console.error(`${r.info}\u{1F4A1} Tip: Use --help for usage information${r.reset}`),z.exit(1);}}};var
|
|
2
|
+
import Ft from'pino';import Ae from'path';import Ce from'fs';import {execSync}from'child_process';import*as ut from'readline';import {createRequire}from'module';import {Ajv}from'ajv';import Dt from'fast-json-stringify';import rr from'crypto';import {promisify}from'util';import {gzip,gunzip}from'zlib';var Ue=Object.defineProperty;var ze=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var S=(o,e,t,r)=>{for(var s=void 0,n=o.length-1,c;n>=0;n--)(c=o[n])&&(s=(c(e,t,s))||s);return s&&Ue(e,t,s),s};var Je=class{type;constructor(){this.type=this.getRunTime();}getRunTime(){if(typeof Bun<"u")return "bun";if(typeof Deno<"u")return "deno";if(typeof process<"u")return "node";throw new Error("No environment detected")}},O=new Je;var Ke=class{getCliArgs(){switch(O.type){case "bun":return this.getBunArgs();case "node":return this.getNodeArgs();case "deno":return Deno.args;default:throw new Error("Unsupported runtime")}}getCliCaller(){switch(O.type){case "bun":return "bun";case "node":return process.argv[0];case "deno":return "deno";default:throw new Error("Unsupported runtime")}}getBunArgs(){let e=Bun.argv,t=this.findScriptIndex(e);return e.slice(t+1)}getNodeArgs(){let e=process.argv,t=this.findScriptIndex(e);return e.slice(t+1)}findScriptIndex(e){if(e.length>=3&&e[1].includes(".bin/"))return 1;for(let t=0;t<e.length;t++){let r=e[t],s=r.split("/").pop()||r;if(!r.startsWith("-")){if(s==="yarn"&&t+1<e.length&&e[t+1]==="run"||s==="npx"&&t+1<e.length)return t+1;if(s==="yarn"||s==="pnpm")return t;if(s==="npm"&&t+1<e.length&&e[t+1]==="run"||s==="bun"&&t+1<e.length&&e[t+1]==="run")return t+1;if(/\.(js|ts|mjs|cjs)$/.test(r))return t;if(/^(tsx|ts-node|node|bun)$/.test(s)){for(let n=t+1;n<e.length;n++)if(!e[n].startsWith("-")&&/\.(js|ts|mjs|cjs)$/.test(e[n]))return n;return t}}}for(let t=e.length-1;t>=0;t--)if(!e[t].startsWith("-"))return t;return 1}},ye=new Ke;var it=(o,e)=>{let t=Array(e.length+1).fill(null).map(()=>Array(o.length+1).fill(null));for(let r=0;r<=o.length;r++)t[0][r]=r;for(let r=0;r<=e.length;r++)t[r][0]=r;for(let r=1;r<=e.length;r++)for(let s=1;s<=o.length;s++){let n=o[s-1]===e[r-1]?0:1;t[r][s]=Math.min(t[r][s-1]+1,t[r-1][s]+1,t[r-1][s-1]+n);}return t[e.length][o.length]},Me=o=>o.toLowerCase().replace(/[-_.]/g,"_").replace(/([A-Z])/g,"_$1").replace(/^_+/,"").replace(/_+$/,"").toLowerCase(),$e=o=>o.split(/[-_.]/g).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),at=o=>o.split(/[-_.]/g).map(e=>e.toLowerCase()).join("-");var It=o=>{if(!o||o==="-"||o==="--")return null;let e=o.indexOf("=");if(e>0){let t=o.substring(0,e),r=o.substring(e+1);return {name:t,value:lt(r)}}return {name:o,value:true}},lt=o=>{if(o.toLowerCase()==="true")return true;if(o.toLowerCase()==="false")return false;let e=Number(o);return !Number.isNaN(e)&&Number.isFinite(e)?e:o},Y=()=>{let o=ye.getCliArgs(),e=[],t={};if(!o||!o.length)return {args:e,flags:t};for(let r=0;r<o.length;r++){let s=o[r];if(!(!s||typeof s!="string")){if(s.startsWith("-")){let n=It(s);if(n){if(n.value===true&&r+1<o.length){let c=o[r+1];c&&typeof c=="string"&&!c.startsWith("-")&&(n.value=lt(c),r++);}if(n.name in t){let c=t[n.name];Array.isArray(c)?c.push(n.value):t[n.name]=[c,n.value];}else t[n.name]=n.value;}continue}e.push(s);}}return {args:e,flags:t}},ct=(o,e)=>{if(!o||typeof o!="string"||!e||!Array.isArray(e)||e.length===0)return "";let t=o.toLowerCase().trim(),r=e.filter(c=>{let a=c.toLowerCase();if(a===t||a.includes(t)||t.includes(a))return true;let d=it(a,t),u=Math.max(t.length,a.length)*.4;return d<=u});if(r.length===0)return "";let n=r.slice(0,3).map(c=>`\x1B[36m${c}\x1B[0m`).join(", ");return `\x1B[31m\u2717\x1B[0m Command \x1B[33m${o}\x1B[0m not found
|
|
3
|
+
\x1B[32m\u{1F4A1}\x1B[0m Did you mean: ${n}?`},Ee=()=>ye.getCliArgs()[0]||null;var Bt=()=>Ft({level:"info",formatters:{level:e=>({level:e})}}),E=Bt();var We=class{getCwd(){switch(O.type){case "node":case "bun":return process.cwd();case "deno":return Deno.cwd();default:throw new Error("Unsupported runtime")}}},N=new We;var Ve=class{basename(e){switch(O.type){case "node":case "bun":case "deno":return Ae.basename(e);default:throw new Error("Unsupported runtime")}}join(...e){switch(O.type){case "node":case "bun":case "deno":return Ae.join(...e);default:throw new Error("Unsupported runtime")}}extName(e){switch(O.type){case "bun":case "node":case "deno":return Ae.extname(e);default:throw new Error("Unsupported runtime")}}resolve(...e){switch(O.type){case "bun":case "node":case "deno":return Ae.resolve(...e);default:throw new Error("Unsupported runtime")}}},w=new Ve;var _=class{static metadata=new WeakMap;static set(e,t,r){this.metadata.has(e)||this.metadata.set(e,new Map),this.metadata.get(e).set(t,r);}static get(e,t){return this.metadata.get(e)?.get(t)}static getAll(e){return this.metadata.get(e)}static getOrCreateAll(e){return this.metadata.has(e)||this.metadata.set(e,new Map),this.metadata.get(e)}static delete(e,t){this.metadata.get(e)?.delete(t);}static clear(e){this.metadata.delete(e);}};var ee="VALIDATION_ERROR";var dt=Y().args.slice(1),R=o=>(e,t)=>{let r=Ee();if(!r||r!==e.commandName)return;let s=t;_.set(e,t,{type:"arg",name:s,description:o.description});let n=dt.length?dt.shift():o.defaultValue;if(o.required&&!n){let c=_.get(e,ee);_.set(e,ee,[...c||[],{type:"arg",name:s,message:"Required argument not provided"}]);return}o.parse&&n&&(n=o.parse(n)),Object.defineProperty(e,t,{value:n,enumerable:true,configurable:true,writable:true});};var Ge=class{exit(e){switch(O.type){case "bun":case "node":process.exit(e);case "deno":Deno.exit(e);default:throw new Error(`Unsupported runtime: ${O.type}`)}}},z=new Ge;var q=class{static flagsAndArgs={flags:Y().flags,args:Y().args.slice(1)};static commandName=this.name;static calledBy=this.name;static description="";static help=[];static options={keepAlive:false,loggerPath:"src/logger.ts",allowUnknownFlags:true};static args=this.flagsAndArgs.args;static flags=this.flagsAndArgs.flags;static logger=E.child({scope:this.constructor.name});static handle(){throw new Error(`Handle method not implemented in command class ${this.name}`)}static handleHelpFlag(e){let t=["-h","--help"];if(!Object.keys(e).some(u=>t.includes(u)))return;let s=this.commandName,n=this.description||"No description available",c=this.help||[],a=this.options,d=this.generateHelpOutput({name:s,description:n,helpText:c,options:a,args:this.args,flags:this.flags},this);console.log(d),z.exit(0);}static generateHelpOutput=(e,t)=>{let{name:r,description:s,helpText:n,options:c,args:a,flags:d}=e,u={title:"\x1B[1;36m",subtitle:"\x1B[1;33m",description:"\x1B[0;37m",code:"\x1B[0;32m",flag:"\x1B[0;35m",reset:"\x1B[0m",error:"\x1B[0;31m",success:"\x1B[0;32m",info:"\x1B[0;34m"},l=[`${u.title}${r}${u.reset}`,`${u.description}${s}${u.reset}`,"",`${u.subtitle}Usage:${u.reset}`,` ${u.code}${r}${u.reset} [options] [arguments]`,"",`${u.subtitle}Options:${u.reset}`,` ${u.flag}-h, --help${u.reset} Show this help message`,"",`${u.subtitle}Command Options:${u.reset}`,` ${u.flag}keepAlive${u.reset} ${c?.keepAlive??false?u.success+"Enabled"+u.reset:u.error+"Disabled"+u.reset}`,` ${u.flag}loggerPath${u.reset} ${c?.loggerPath??"src/logger.ts"}`,` ${u.flag}allowUnknownFlags${u.reset} ${c?.allowUnknownFlags??true?u.success+"Enabled"+u.reset:u.error+"Disabled"+u.reset}`,""];if(n){let m=Array.isArray(n)?n:[n];l.push(`${u.subtitle}Help:${u.reset}`),m.forEach(g=>{l.push(` ${u.description}${g}${u.reset}`);}),l.push("");}let i=_.getAll(t),p=i?Array.from(i.values()).filter(m=>m.type==="arg"):[],h=i?Array.from(i.values()).filter(m=>m.type==="flag"):[];return p.length&&(l.push(`${u.subtitle}Available Arguments:${u.reset}`),p.forEach(m=>{let g=m.required?` ${u.error}(required)${u.reset}`:"",f=m.description?` ${u.description}${m.description}${u.reset}`:"";l.push(` ${u.code}${m.name}${u.reset}${g}${f}`);}),l.push("")),h.length&&(l.push(`${u.subtitle}Available Flags:${u.reset}`),h.forEach(m=>{m.aliases&&!Array.isArray(m.aliases)&&(m.aliases=[m.aliases]);let g=m.aliases.length?` ${u.flag}(${m.aliases.join(", ")})${u.reset}`:"",f=m.required?` ${u.error}(required)${u.reset}`:"",x=m.description?` ${u.description}${m.description}${u.reset}`:"";l.push(` ${u.flag}--${m.name}${g}${u.reset}${f}${x}`);}),l.push("")),((a?.length??0)>0||d&&Object.keys(d).length>0)&&(l.push(`${u.subtitle}Current Context:${u.reset}`),a?.length&&l.push(` ${u.info}Provided Arguments:${u.reset} ${u.code}${a.join(" ")}${u.reset}`),d&&Object.keys(d).length>0&&(l.push(` ${u.info}Provided Flags:${u.reset}`),Object.keys(d).forEach(m=>{let g=d[m],f=g!=null?` = ${u.code}${g}${u.reset}`:"";l.push(` ${u.flag}${m}${u.reset}${f}`);})),l.push("")),n&&(Array.isArray(n)?n.some(m=>m.includes("example")):n.includes("example"))&&(l.push(`${u.subtitle}Examples:${u.reset}`),(Array.isArray(n)?n.filter(g=>g.includes("example")):[n.split("example")[1].trim()]).forEach(g=>{l.push(` ${u.code}${g}${u.reset}`);}),l.push("")),l.join(`
|
|
4
|
+
`)};static validateUnknownFlags=e=>{if(e.options?.allowUnknownFlags!==false)return;let t=new Set(["-h","--help"]),r=new Set,s=_.getAll(e);if(s){for(let c of s.values())if(c.type==="flag"&&(r.add(`--${c.name}`),r.add(`-${c.name}`),r.add(c.name),c.aliases)){let a=Array.isArray(c.aliases)?c.aliases:[c.aliases];for(let d of a)r.add(`--${d}`),r.add(`-${d}`),r.add(d);}}let n=Object.keys(e.flags).filter(c=>!t.has(c)&&!r.has(c));if(n.length){let c={error:"\x1B[0;31m",title:"\x1B[1;31m",reset:"\x1B[0m",info:"\x1B[0;34m",flag:"\x1B[0;35m"};console.error(`${c.title}\u274C Unknown Flags:${c.reset}`),console.error(""),n.forEach(a=>{console.error(` ${c.error}\u2022${c.reset} ${c.flag}${a}${c.reset}`);}),console.error(""),console.error(`${c.info}\u{1F4A1} Tip: Use --help for available flags${c.reset}`),z.exit(1);}};static validateContext=e=>{let t=Array.from(_.get(e,ee)||[]);if(t.length){let r={error:"\x1B[0;31m",title:"\x1B[1;31m",reset:"\x1B[0m",info:"\x1B[0;34m",code:"\x1B[0;32m"};console.error(`${r.title}\u274C Validation Errors:${r.reset}`),console.error(""),t.forEach((s,n)=>{let c=`${r.info}${n+1}.${r.reset}`,a=`${r.error}${s.type.toUpperCase()}${r.reset}`,d=`${r.code}${s.name}${r.reset}`;console.error(` ${c} ${a} ${d}: ${r.error}${s.message}${r.reset}`);}),console.error(""),console.error(`${r.info}\u{1F4A1} Tip: Use --help for usage information${r.reset}`),z.exit(1);}}};var L=o=>(e,t)=>{let r=Ee();if(!r||r!==e.commandName)return;let s=o.name||t,n=Y().flags,c=o.aliases?Array.isArray(o.aliases)?o.aliases:[o.aliases]:[],a=[s,...c],d=o.defaultValue;for(let u of a){let l=[u,`-${u}`,`--${u}`];for(let i of l)if(i in n){let p=n[i];o.type==="list"?d=(Array.isArray(p)?p:[p]).map(m=>{let g=String(m);return o.parse?o.parse(g):g}):(d=p,o.type==="boolean"?d=!!d:o.type==="number"?d=Number(d):o.type==="string"&&(d=String(d)),o.parse&&(d=o.parse(d)));break}if(d!==o.defaultValue)break}if(_.set(e,t,{type:"flag",name:s,aliases:c||[],description:o.description}),o.required&&(o.type==="list"?!d||Array.isArray(d)&&d.length===0:!d)){let l=_.get(e,ee);_.set(e,ee,[...l||[],{type:"flag",name:s,message:"Required flag not provided"}]);return}Object.defineProperty(e,t,{value:d,enumerable:true,configurable:true,writable:true});};L.boolean=o=>L({...o,type:"boolean"});L.string=o=>L({...o,type:"string"});L.number=o=>L({...o,type:"number"});L.list=o=>L({...o,type:"list"});L.array=o=>L({...o,type:"list"});var C=L;var Xe=class{async glob(...e){let t=await import('fs/promises'),r=N.getCwd(),s=w.resolve(r,e[1]?.cwd??""),n=[];for await(let c of t.glob(...e)){if(typeof c=="string"){n.push(w.resolve(s,c));continue}c.isFile()&&n.push(w.resolve(s,c.name));}return n}async mkdir(e,t){switch(O.type){case "bun":case "node":await(await import('fs/promises')).mkdir(e,{recursive:t?.recursive??false,mode:t?.mode});break;case "deno":typeof t?.mode=="string"&&(t.mode=Number.parseInt(t.mode)),await Deno.mkdir(e,{recursive:t?.recursive??false,mode:t?.mode});break}}async exists(e){switch(O.type){case "node":return (await import('fs')).existsSync(e);case "bun":return (await import('fs')).existsSync(e);case "deno":return Deno.stat(e).then(()=>true).catch(()=>false);default:throw new Error("Unsupported runtime")}}async readFile(e,t){switch(O.type){case "node":let s=await(await import('fs/promises')).readFile(e,{encoding:t?.encoding??null});return t?.encoding==="utf8"?s:new Uint8Array(s);case "bun":let n=Bun.file(e);return t?.encoding==="utf8"?n.text():new Uint8Array(await n.arrayBuffer());case "deno":let c=await Deno.readFile(e);return t?.encoding==="utf8"?new TextDecoder().decode(c):new Uint8Array(c)}}async writeFile(e,t){switch(O.type){case "node":await(await import('fs/promises')).writeFile(e,t);break;case "bun":await Bun.write(e,t);break;case "deno":await Deno.writeFile(e,t);break}}async stat(e){switch(O.type){case "node":let r=await(await import('fs/promises')).stat(e);return {isDirectory:r.isDirectory(),isFile:r.isFile(),isSymbolicLink:r.isSymbolicLink(),size:r.size};case "bun":let n=await(await import('fs/promises')).stat(e);return {isDirectory:n.isDirectory(),isFile:n.isFile(),isSymbolicLink:n.isSymbolicLink(),size:n.size};case "deno":let c=await Deno.stat(e);return {isDirectory:c.isDirectory,isFile:c.isFile,isSymbolicLink:false,size:c.size}}}async unlink(e){switch(O.type){case "node":await(await import('fs/promises')).unlink(e);break;case "bun":await Bun.file(e).delete();break;case "deno":await Deno.remove(e);break;default:throw new Error("Unsupported runtime")}}async streamFile(e){switch(O.type){case "node":let t=await import('fs'),{Readable:r}=await import('stream'),s=t.createReadStream(e);return r.toWeb(s);case "bun":return Bun.file(e).stream();case "deno":return (await Deno.open(e)).readable;default:throw new Error("Unsupported runtime")}}async readdir(e){switch(O.type){case "bun":case "node":return (await import('fs/promises')).readdir(e);case "deno":let r=[];for await(let s of Deno.readDir(e))r.push(s.name);return r;default:throw new Error("Unsupported runtime")}}},y=new Xe;var je=typeof import.meta<"u"?createRequire(import.meta.url):ze("module").createRequire?.(import.meta?.url??__filename)??ze,W=async o=>{let e=w.join(process.cwd(),"node_modules");if(!await y.exists(e))return o;let r=[];for(let s of o){let n=w.join(e,s);await y.exists(n)||r.push(s);}return r},I=async()=>await y.exists(w.join(process.cwd(),"yarn.lock"))?["yarn","add","-D"]:await y.exists(w.join(process.cwd(),"pnpm-lock.yaml"))?["pnpm","add","-D"]:await y.exists(w.join(process.cwd(),"package-lock.json"))?["npm","install","-D"]:await y.exists(w.join(process.cwd(),"bun.lockb"))?["bun","add","-D"]:await y.exists(w.join(process.cwd(),"deno.lock"))?["deno","add","-D"]:["npm","install","-D"],j=async(o,e,t,r,s=true)=>{let n=ut.createInterface({input:process.stdin,output:process.stdout}),c=t.join(", "),a=`Do you want to install the following ${s?"dev":""} dependencies using ${e}?
|
|
5
5
|
${c}
|
|
6
|
-
(y/n): `;return new Promise(d=>{n.question(a,u=>{if(n.close(),u.toLowerCase()==="y"||u.toLowerCase()==="yes"){execSync(o,r),d(true);return}d(false);});})};var B=class extends q{static commandName="build";static description="Build the project for production, node.js only";static help=["Build the project for production, node.js only","It will create a production build of the project in the dist directory","Must have a tsconfig.json file in the root of the project","Must have esbuild installed as a dependency while running the command","Must have esbuild-plugin-copy installed as a dependency while running the command if you want to copy assets to the output directory","Example: npx balda build -t ./tsconfig.json -a ./assets"];static clearDist;static entry;static output;static tsconfig;static assets;static format;static packages;static sourcemap;static async handle(){if(typeof process===void 0&&(this.logger.error("Build command is only supported in node.js"),process.exit(1)),["esm","cjs"].includes(this.format)||(this.logger.error("Invalid format, must be 'esm' or 'cjs'"),process.exit(1)),["bundle","external"].includes(this.packages)||(this.logger.error("Invalid packages, must be 'bundle' or 'external'"),process.exit(1)),!await import('esbuild').then(a=>true).catch(()=>false)){let[a,d,u]=await I();await
|
|
7
|
-
Zod is a peer dependency required when using Zod schemas for validation.`)}}static get(){return this.load()}static isZodSchema(e){try{this.load();}catch{return false}if(typeof e!="object"||e===null)return false;if(this.zodSchemaCache.has(e))return true;let t="_def"in e&&typeof e.parse=="function"&&typeof e.safeParse=="function";return t&&this.zodSchemaCache.add(e),t}static ensureZodV4(){let e=this.zodModule?.z;if(!e)throw new be;if(!("toJSONSchema"in e))throw new be}static toJSONSchema(e){this.load(),this.ensureZodV4();let t=this.zodModule?.z;if(!t?.toJSONSchema)throw new be;if(!e||typeof e!="object"||!("_def"in e))throw new Error(`Invalid Zod schema provided. Make sure you're using Zod v4 schemas. If you're importing from 'zod/v3', change to 'zod' or '{ z } from "zod"'.`);try{return t.toJSONSchema(e)}catch(r){throw r instanceof Error&&r.message.includes("Cannot read properties of undefined")?new Ne(r):r}}};var _e=class extends F{constructor(){super("TypeBox is not installed. Install it with: npm install @sinclair/typebox");}};var G=class{static typeboxModule=null;static typeboxSchemaCache=new WeakSet;static load(){if(this.typeboxModule)return this.typeboxModule;try{return this.typeboxModule=ke("@sinclair/typebox"),this.typeboxModule}catch{throw new _e}}static get(){return this.load()}static isTypeBoxSchema(e){try{this.load();}catch{return false}if(typeof e!="object"||e===null)return false;if(this.typeboxSchemaCache.has(e))return true;let t="type"in e&&Object.getOwnPropertySymbols(e).some(r=>r.toString()==="Symbol(TypeBox.Kind)");return t&&this.typeboxSchemaCache.add(e),t}};function Se(o){if(!o||typeof o!="object")return o;let e;if(o.properties&&typeof o.properties=="object"){e={...o,additionalProperties:false};let t=o.properties,r={},s=false;for(let n in t){let c=t[n];if(c&&typeof c=="object"&&!("$ref"in c)){let a=Se(c);a!==c&&(s=true),r[n]=a;}else r[n]=c;}s&&(e.properties=r);}if(o.items&&typeof o.items=="object"&&!("$ref"in o.items)){let t=Se(o.items);t!==o.items&&(e=e??{...o},e.items=t);}for(let t of ["oneOf","anyOf","allOf"]){let r=o[t];if(Array.isArray(r)){let s=[],n=false;for(let c of r)if(c&&typeof c=="object"&&!("$ref"in c)){let a=Se(c);a!==c&&(n=true),s.push(a);}else s.push(c);n&&(e=e??{...o},e[t]=s);}}for(let t of ["$defs","definitions"]){let r=o[t];if(r&&typeof r=="object"){let s={},n=false;for(let c in r){let a=r[c];if(a&&typeof a=="object"){let d=Se(a);d!==a&&(n=true),s[c]=d;}else s[c]=a;}n&&(e=e??{...o},e[t]=s);}}return e??o}var M=class{static ajv=new Ajv({validateSchema:false,strict:false});static serializerCache=new WeakMap;static responseSerializersCache=new WeakMap;static refCounter=0;static schemaKeyCache=new WeakMap;static setGlobalInstance(e){this.ajv=e,this.ajv.opts.strict=false,this.ajv.opts.validateSchema=false;}static getSchemaKey(e,t){let r=this.schemaKeyCache.get(e);r||(r=new Map,this.schemaKeyCache.set(e,r));let s=r.get(t);return s||(s=`${t}_${++this.refCounter}`,r.set(t,s)),s}static getOrCompileValidator(e,t){let r=this.getSchemaKey(e,t),s=this.ajv.getSchema(r);if(s)return s;this.ajv.addSchema(e,r);let n=this.ajv.getSchema(r);if(!n)throw new Error(`Failed to compile schema with key: ${r}`);return n}static getOrCreateSerializer(e,t){if(!e||typeof e!="object")return null;let r=this.serializerCache.get(e);r||(r=new Map,this.serializerCache.set(e,r));let s=r.get(t);if(s)return s;try{let n=Se(e),c=Bt(n,{ajv:this.ajv.opts});return r.set(t,c),c}catch{return null}}static getOrCreateResponseSerializers(e){if(!e)return null;let t=this.responseSerializersCache.get(e);if(t)return t;let r=new Map;for(let[s,n]of Object.entries(e)){let c=Number(s),a=null;if(Q.isZodSchema(n)){let d=Q.toJSONSchema(n);a=this.getOrCreateSerializer(d,"fast_stringify_zod");}else G.isTypeBoxSchema(n)?a=this.getOrCreateSerializer(n,"fast_stringify_typebox"):typeof n=="object"&&n!==null&&(a=this.getOrCreateSerializer(n,"fast_stringify_json"));a&&r.set(c,a);}return this.responseSerializersCache.set(e,r),r}static storeJsonSchema(e,t){let r=this.getSchemaKey(e,t);this.ajv.getSchema(r)||this.ajv.addSchema(e,r);}static getJsonSchema(e,t){let r=this.schemaKeyCache.get(e);if(!r)return;let s=r.get(t);return s?this.ajv.getSchema(s)?.schema:void 0}static clearAllCaches(){this.ajv=new Ajv({validateSchema:false,strict:false}),this.serializerCache=new WeakMap,this.schemaKeyCache=new WeakMap,this.refCounter=0;}static getSchemaCount(){return Object.keys(this.ajv.schemas).length}static getCacheStats(){return {schemaCount:this.getSchemaCount(),totalRefsCreated:this.refCounter}}};var Qt=o=>{if(Q.isZodSchema(o)){try{let t=Q.toJSONSchema(o);M.storeJsonSchema(t,"serialize_zod"),M.getOrCompileValidator(t,"serialize_zod");}catch(t){E.warn({error:t,schemaType:"zod",context:"serialize_decorator"},"Failed to compile Zod schema for validation. Schema may contain unsupported types (e.g., z.instanceof). Runtime validation will still work, but Swagger documentation may be incomplete.");return}return}if(G.isTypeBoxSchema(o)){try{M.storeJsonSchema(o,"serialize_typebox"),M.getOrCompileValidator(o,"serialize_typebox");}catch(t){E.warn({error:t,schemaType:"typebox",context:"serialize_decorator"},"Failed to compile TypeBox schema for validation. Schema may be invalid or use unsupported features.");return}return}if(typeof o=="object"&&o!==null){try{M.storeJsonSchema(o,"serialize_json"),M.getOrCompileValidator(o,"serialize_json");}catch(t){E.warn({error:t,schemaType:"json",context:"serialize_decorator"},"Failed to compile JSON schema for validation. Schema may be invalid or malformed.");return}return}let e=JSON.stringify(o);try{let t={type:typeof o};M.storeJsonSchema(t,`serialize_primitive_${e}`),M.getOrCompileValidator(t,`serialize_primitive_${e}`);}catch(t){E.warn({error:t,schemaType:"primitive",cacheKey:e,context:"serialize_decorator"},"Failed to compile schema for validation. Schema format may be unsupported.");}},ht=o=>{if(Q.isZodSchema(o)){try{let t=Q.toJSONSchema(o);M.storeJsonSchema(t,"zod_schema"),M.getOrCompileValidator(t,"zod_schema");}catch(t){E.warn({error:t,schemaType:"zod",context:"request_validation"},"Failed to compile Zod schema for request validation. Schema may contain unsupported types (e.g., z.instanceof). Swagger documentation may be incomplete.");return}return}if(G.isTypeBoxSchema(o)){try{M.storeJsonSchema(o,"typebox_schema"),M.getOrCompileValidator(o,"typebox_schema");}catch(t){E.warn({error:t,schemaType:"typebox",context:"request_validation"},"Failed to compile TypeBox schema for request validation. Schema may be invalid or use unsupported features.");return}return}if(typeof o=="object"&&o!==null){try{M.storeJsonSchema(o,"json_schema"),M.getOrCompileValidator(o,"json_schema");}catch(t){E.warn({error:t,schemaType:"json",context:"request_validation"},"Failed to compile JSON schema for request validation. Schema may be invalid or malformed.");return}return}let e=JSON.stringify(o);try{let t={type:typeof o};M.storeJsonSchema(t,`primitive_${e}`),M.getOrCompileValidator(t,`primitive_${e}`);}catch(t){E.warn({error:t,schemaType:"primitive",cacheKey:e,context:"request_validation"},"Failed to compile schema for request validation. Schema format may be unsupported.");}},gt=(o,e)=>{o&&ht(o),e&&ht(e);},ft=o=>{if(!o||Object.keys(o).length===0)return;let e={};for(let[t,r]of Object.entries(o)){let s=Number(t);if(e[s]=r,Qt(r),Q.isZodSchema(r))try{let n=Q.toJSONSchema(r);M.getOrCreateSerializer(n,"fast_stringify_zod");}catch{}else G.isTypeBoxSchema(r)?M.getOrCreateSerializer(r,"fast_stringify_typebox"):typeof r=="object"&&r!==null&&M.getOrCreateSerializer(r,"fast_stringify_json");}return e};var yt=(o,e)=>async function(t,r,...s){try{if(e.body){let n=t.validate(e.body,!0);t.body=n;}if(e.query){let n=t.validateQuery(e.query,!0);t.query=n;}if(e.all){let n=t.validateAll(e.all,!0);t.body=n;}return o(t,r,...s)}catch(n){return r.badRequest(n)}};promisify(gzip);promisify(gunzip);var ve=class{staticChildren;paramChild;wildcardChild;middleware;handler;paramName;constructor(){this.staticChildren=new Map,this.paramChild=null,this.wildcardChild=null,this.middleware=null,this.handler=null,this.paramName=null;}},Ye=class o{trees;routes;middlewares;basePath;staticRouteCache;handlerResponseSchemas;constructor(e="",t=[]){this.trees=new Map,this.routes=[],this.middlewares=t,this.basePath=this.normalizeBasePath(e),this.staticRouteCache=new Map,this.handlerResponseSchemas=new Map;}getRoutes(){return this.routes.slice()}addOrUpdate(e,t,r,s,n,c,a,d=false){e=e.toUpperCase();let u=t.split("?")[0];gt(n?.body,n?.query);let l=ft(a),i=n&&(n.body||n.query||n.all),p=i?yt(s,n):s,h=i?n:void 0,m=this.trees.get(e);m||(m=new ve,this.trees.set(e,m));let g=u.replace(/^\/+|\/+$/g,""),f=g.length===0?[]:g.split("/"),x=true,P=[],T=m;for(let v of f){if(v==="*"){x=false,T.wildcardChild||(T.wildcardChild=new ve),T=T.wildcardChild;break}if(v.startsWith(":")){x=false;let $=v.slice(1);P.push($),T.paramChild||(T.paramChild={node:new ve,name:$}),T=T.paramChild.node;continue}T.staticChildren.has(v)||T.staticChildren.set(v,new ve),T=T.staticChildren.get(v);}if(T.middleware=r,T.handler=p,P.length>0&&(T.paramName=P.join(",")),l&&this.handlerResponseSchemas.set(s,l),x){let v="/"+g,$=`${e}:${v}`;this.staticRouteCache.set($,{middleware:r,handler:p,params:{},responseSchemas:l});}else {let v="/"+g.replace(/:[^/]+/g,"").replace(/\/+/g,"/"),$=`${e}:${v}`;this.staticRouteCache.delete($);}let b=this.routes.findIndex(v=>v.method===e&&v.path===t);if(b!==-1){if(!d)throw new Error(`Duplicate route detected: ${e} ${t} is already registered. Each route must be unique.`);this.routes[b].middleware=r,this.routes[b].handler=p,this.routes[b].swaggerOptions=c,this.routes[b].responses=a,this.routes[b].responseSchemas=l,this.routes[b].validationSchemas=h;return}this.routes.push({method:e,path:t,middleware:r,handler:p,swaggerOptions:c,responses:a,responseSchemas:l,validationSchemas:h});}find(e,t){e=e.toUpperCase();let r=t,s=t.indexOf("?");s!==-1&&(r=t.substring(0,s));let n=`${e}:${r}`,c=this.staticRouteCache.get(n);if(c)return c;let a=this.trees.get(e);if(!a)return null;let d=r.replace(/^\/+|\/+$/g,""),u=d.length===0?[]:d.split("/"),l={},i=a;for(let h=0;h<u.length;h++){let m=u[h];if(i.staticChildren.has(m)){i=i.staticChildren.get(m);continue}if(i.paramChild){l[i.paramChild.name]=m,i=i.paramChild.node;continue}if(i.wildcardChild){l["*"]=u.slice(h).join("/"),i=i.wildcardChild;break}return null}if(!i.handler||!i.middleware)return null;let p=this.handlerResponseSchemas.get(i.handler);return {middleware:i.middleware,handler:i.handler,params:l,responseSchemas:p}}extractOptionsAndHandler(e,t){if(typeof e=="function")return {middlewares:[],handler:e,swaggerOptions:void 0};let r=e,s=Array.isArray(r.middlewares)?r.middlewares:r.middlewares?[r.middlewares]:[];if(r.cache);return {middlewares:s,handler:t,body:r.body,query:r.query,all:r.all,responses:r.responses,swaggerOptions:r.swagger}}get(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:c,body:a,query:d,all:u,responses:l,swaggerOptions:i}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...n],h={body:a,query:d,all:u};this.addOrUpdate("GET",s,p,c,h,i,l);}post(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:c,body:a,query:d,all:u,responses:l,swaggerOptions:i}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...n],h={body:a,query:d,all:u};this.addOrUpdate("POST",s,p,c,h,i,l);}patch(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:c,body:a,query:d,all:u,responses:l,swaggerOptions:i}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...n],h={body:a,query:d,all:u};this.addOrUpdate("PATCH",s,p,c,h,i,l);}put(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:c,body:a,query:d,all:u,responses:l,swaggerOptions:i}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...n],h={body:a,query:d,all:u};this.addOrUpdate("PUT",s,p,c,h,i,l);}delete(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:c,body:a,query:d,all:u,responses:l,swaggerOptions:i}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...n],h={body:a,query:d,all:u};this.addOrUpdate("DELETE",s,p,c,h,i,l);}options(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:c,body:a,query:d,all:u,responses:l,swaggerOptions:i}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...n],h={body:a,query:d,all:u};this.addOrUpdate("OPTIONS",s,p,c,h,i,l);}head(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:c,body:a,query:d,all:u,responses:l,swaggerOptions:i}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...n],h={body:a,query:d,all:u};this.addOrUpdate("HEAD",s,p,c,h,i,l);}group(e,t,r){let s=Array.isArray(t)?t:typeof t=="function"?[]:t?[t]:[],n=Array.isArray(t)?r:typeof t=="function"?t:void 0,c=this.joinPath(e),a=new o(c,[...this.middlewares,...s]);n?.(a);for(let d of a.getRoutes())this.addOrUpdate(d.method,d.path,d.middleware,d.handler,d.validationSchemas,d.swaggerOptions,d.responses);}applyGlobalMiddlewaresToAllRoutes(e){for(let t of this.routes){let r=[...e,...t.middleware||[]];this.addOrUpdate(t.method,t.path,r,t.handler,void 0,void 0,void 0,true);}}normalizeBasePath(e){if(!e)return "";let t=e.replace(/\s+/g,"");return t=t.replace(/\/+/g,"/"),t.startsWith("/")||(t="/"+t),t.length>1&&(t=t.replace(/\/+$/g,"")),t}joinPath(e){let r=[this.basePath,e].filter(s=>typeof s=="string"&&s.length>0).join("/");return r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r.length>1&&(r=r.replace(/\/+$/g,"")),r}clearRoutes(){this.routes=[],this.staticRouteCache.clear(),this.handlerResponseSchemas.clear(),this.trees.clear();}};new Ye;var X=class{static scheduledJobs=[];static logger=E.child({scope:"CronService"});static register(e,...t){t[2]={name:e,...t[2]},this.scheduledJobs.push({name:e,args:t});}static async run(){let e=(await import('node-cron').catch(()=>{throw new F("node-cron not installed as a dependency, it is required in order to run cron jobs with the @cron decorator")})).default;if(this.logger.info("Scheduling cron jobs"),!this.scheduledJobs.length){this.logger.info("No cron jobs to schedule");return}for(let{name:t,args:r}of this.scheduledJobs)this.logger.info(`Scheduling cron job: ${t}`),e.schedule(...r).on("execution:failed",n=>this.globalErrorHandler(n));this.logger.info("Cron jobs scheduled");}static globalErrorHandler(e){this.logger.error(e.execution?.error);}static async massiveImportCronJobs(e){let t=[];for(let r of e){let s=await y.glob(r,{cwd:N.getCwd()});t.push(...s);}await Promise.all(t.map(async r=>{await import(r).catch(s=>{this.logger.error(`Error importing cron job: ${r}`),E.error(s);});}));}};var re=class extends q{static commandName="cron-start";static description="Start cron job scheduler";static help=["Start the cron job scheduler to run scheduled tasks","Loads cron jobs from specified patterns and starts scheduling","Example: npx balda cron-start","Example: npx balda cron-start src/crons/**/*.ts --patterns src/schedules/**/*.ts"];static options={keepAlive:true};static pattern;static additionalPatterns;static async handle(){this.logger.info("Starting cron scheduler...");let e=[this.pattern];this.additionalPatterns&&this.additionalPatterns.length>0&&e.push(...this.additionalPatterns),this.logger.info(`Loading cron jobs from patterns: ${e.join(", ")}`),await X.massiveImportCronJobs(e);let t=X.scheduledJobs.length;if(t===0){this.logger.warn("No cron jobs found. Make sure your cron jobs are decorated with @cron decorator");return}this.logger.info(`Found ${t} cron job(s)`),X.run().then(()=>{this.logger.info("Cron scheduler started successfully. Press Ctrl+C to stop.");}).catch(r=>{this.logger.error("Error starting cron scheduler",r);});}};S([R({required:false,defaultValue:"src/crons/**/*.{ts,js}",description:"Primary glob pattern for cron jobs (default: src/crons/**/*.{ts,js})"})],re,"pattern"),S([C.array({aliases:["p"],name:"patterns",required:false,description:"Additional glob patterns for cron jobs"})],re,"additionalPatterns");var we=class extends q{static commandName="generate-command";static description="Generate a new command in the specified path";static help=["Generate a new cli command in the specified path","Example: npx balda generate-command my-command -p src/commands"];static path="src/commands";static name;static async handle(){if(D.getCommand(this.name)){let s=D.isBuiltInCommand(this.name)?"built-in":"user-defined";this.logger.error({commandName:this.name,type:s},`Command "${this.name}" already exists as a ${s} command. Cannot override existing commands.`);return}let t=this.getCommandTemplate();this.path=w.join(this.path,`${this.name}.ts`),await y.exists(w.join(process.cwd(),this.path))||await y.mkdir(w.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await y.writeFile(this.path,new TextEncoder().encode(t)),this.logger.info(`Command ${this.name} created successfully at ${this.path}`);}static getCommandTemplate(){return `import { Command, CommandOptions } from "balda";
|
|
6
|
+
(y/n): `;return new Promise(d=>{n.question(a,u=>{if(n.close(),u.toLowerCase()==="y"||u.toLowerCase()==="yes"){execSync(o,r),d(true);return}d(false);});})};var B=class extends q{static commandName="build";static description="Build the project for production, node.js only";static help=["Build the project for production, node.js only","It will create a production build of the project in the dist directory","Must have a tsconfig.json file in the root of the project","Must have esbuild installed as a dependency while running the command","Must have esbuild-plugin-copy installed as a dependency while running the command if you want to copy assets to the output directory","Example: npx balda build -t ./tsconfig.json -a ./assets"];static clearDist;static entry;static output;static tsconfig;static assets;static format;static packages;static sourcemap;static async handle(){if(typeof process===void 0&&(this.logger.error("Build command is only supported in node.js"),process.exit(1)),["esm","cjs"].includes(this.format)||(this.logger.error("Invalid format, must be 'esm' or 'cjs'"),process.exit(1)),["bundle","external"].includes(this.packages)||(this.logger.error("Invalid packages, must be 'bundle' or 'external'"),process.exit(1)),!await import('esbuild').then(a=>true).catch(()=>false)){let[a,d,u]=await I();await j(`${a} ${d} esbuild ${u}`,a,["esbuild"],{stdio:"inherit"})||(this.logger.warn("User chose to not continue with the installation of esbuild, exiting..."),process.exit(0));}let t=await import('esbuild').catch(a=>{throw this.logger.error("esbuild is not installed, please install it with `npm install -D esbuild` to use the build command"),new Error("esbuild is not installed")}),r=Ae.join(this.output,"assets"),s=[];if(this.assets){let{copy:a}=await import('esbuild-plugin-copy').catch(d=>{throw this.logger.error("esbuild-plugin-copy is not installed, please install it with `npm install -D esbuild-plugin-copy` to use the build command"),new Error("esbuild-plugin-copy is not installed")});Ce.existsSync(r)||Ce.mkdirSync(r,{recursive:true}),s.push(a({assets:{from:this.assets,to:r}}));}this.clearDist&&Ce.existsSync(this.output)&&(this.logger.info("Clearing dist directory..."),Ce.rmSync(this.output,{recursive:true})),this.logger.info("Building project...");let n=Ae.join(this.output,"server.js"),c=await t.build({tsconfig:this.tsconfig,entryPoints:[this.entry],bundle:true,platform:"node",outfile:n,minify:true,sourcemap:this.sourcemap,plugins:s,format:this.format,packages:this.packages});c.errors.length&&(this.logger.error(JSON.stringify({message:"Failed to build the project",errors:c.errors},null,2)),process.exit(1)),c.warnings.length&&this.logger.warn(JSON.stringify({message:"Failed to build the project",warnings:c.warnings},null,2)),this.logger.info(JSON.stringify({message:`Project built successfully in ${n}`,output:n,assets:!!this.assets},null,2)),process.exit(0);}};S([C({type:"boolean",aliases:["c"],name:"clear-dist",required:false,defaultValue:false,description:"Whether to clear the dist directory before building the project"})],B,"clearDist"),S([C({type:"string",aliases:["e"],name:"entry",required:false,defaultValue:"./src/index.ts",description:"The entry point of the project, default is ./src/index.ts"})],B,"entry"),S([C({type:"string",aliases:["o"],name:"output",required:false,defaultValue:"./dist",description:"The path to the output directory, default is ./dist"})],B,"output"),S([C({type:"string",aliases:["t"],name:"tsconfig",required:false,defaultValue:"./tsconfig.json",description:"The path to the tsconfig.json file, default is ./tsconfig.json"})],B,"tsconfig"),S([C({type:"string",aliases:["a"],name:"assets",required:false,description:"The path to the assets directory that will be loaded in the production build"})],B,"assets"),S([C({type:"string",aliases:["f"],name:"format",required:false,defaultValue:"esm",description:"The format to build the project, default is esm, can be 'esm' or 'cjs'"})],B,"format"),S([C({type:"string",aliases:["p"],name:"packages",required:false,defaultValue:"external",description:"Weather to bundle node_modules or not, default is external, can be 'bundle' or 'external'"})],B,"packages"),S([C({type:"boolean",aliases:["s"],name:"sourcemap",required:false,defaultValue:true,description:"Whether to generate sourcemaps or not, default is true"})],B,"sourcemap");var F=class extends Error{constructor(e){super(e);}};var Ne=class extends F{constructor(e){super(`Failed to convert Zod schema to JSON Schema. This usually happens when using Zod v3 schemas with Zod v4. Make sure you're importing from 'zod' (v4) and not 'zod/v3'. Original error: ${e.message}`);}};var be=class extends F{constructor(){super("Zod v4 is required with the toJSONSchema() method. Install it with: npm install zod@^4.0.0");}};var Q=class{static zodModule=null;static zodSchemaCache=new WeakSet;static load(){if(this.zodModule)return this.zodModule;try{return this.zodModule=je("zod"),this.ensureZodV4(),this.zodModule}catch{throw new Error(`Zod is not installed. Install it with: npm install zod
|
|
7
|
+
Zod is a peer dependency required when using Zod schemas for validation.`)}}static get(){return this.load()}static isZodSchema(e){try{this.load();}catch{return false}if(typeof e!="object"||e===null)return false;if(this.zodSchemaCache.has(e))return true;let t="_def"in e&&typeof e.parse=="function"&&typeof e.safeParse=="function";return t&&this.zodSchemaCache.add(e),t}static ensureZodV4(){let e=this.zodModule?.z;if(!e)throw new be;if(!("toJSONSchema"in e))throw new be}static toJSONSchema(e){this.load(),this.ensureZodV4();let t=this.zodModule?.z;if(!t?.toJSONSchema)throw new be;if(!e||typeof e!="object"||!("_def"in e))throw new Error(`Invalid Zod schema provided. Make sure you're using Zod v4 schemas. If you're importing from 'zod/v3', change to 'zod' or '{ z } from "zod"'.`);try{return t.toJSONSchema(e)}catch(r){throw r instanceof Error&&r.message.includes("Cannot read properties of undefined")?new Ne(r):r}}};var _e=class extends F{constructor(){super("TypeBox is not installed. Install it with: npm install @sinclair/typebox");}};var G=class{static typeboxModule=null;static typeboxSchemaCache=new WeakSet;static load(){if(this.typeboxModule)return this.typeboxModule;try{return this.typeboxModule=je("@sinclair/typebox"),this.typeboxModule}catch{throw new _e}}static get(){return this.load()}static isTypeBoxSchema(e){try{this.load();}catch{return false}if(typeof e!="object"||e===null)return false;if(this.typeboxSchemaCache.has(e))return true;let t="type"in e&&Object.getOwnPropertySymbols(e).some(r=>r.toString()==="Symbol(TypeBox.Kind)");return t&&this.typeboxSchemaCache.add(e),t}};function Se(o){if(!o||typeof o!="object")return o;let e;if(o.properties&&typeof o.properties=="object"){e={...o,additionalProperties:false};let t=o.properties,r={},s=false;for(let n in t){let c=t[n];if(c&&typeof c=="object"&&!("$ref"in c)){let a=Se(c);a!==c&&(s=true),r[n]=a;}else r[n]=c;}s&&(e.properties=r);}if(o.items&&typeof o.items=="object"&&!("$ref"in o.items)){let t=Se(o.items);t!==o.items&&(e=e??{...o},e.items=t);}for(let t of ["oneOf","anyOf","allOf"]){let r=o[t];if(Array.isArray(r)){let s=[],n=false;for(let c of r)if(c&&typeof c=="object"&&!("$ref"in c)){let a=Se(c);a!==c&&(n=true),s.push(a);}else s.push(c);n&&(e=e??{...o},e[t]=s);}}for(let t of ["$defs","definitions"]){let r=o[t];if(r&&typeof r=="object"){let s={},n=false;for(let c in r){let a=r[c];if(a&&typeof a=="object"){let d=Se(a);d!==a&&(n=true),s[c]=d;}else s[c]=a;}n&&(e=e??{...o},e[t]=s);}}return e??o}var M=class{static ajv=new Ajv({validateSchema:false,strict:false});static serializerCache=new WeakMap;static responseSerializersCache=new WeakMap;static refCounter=0;static schemaKeyCache=new WeakMap;static setGlobalInstance(e){this.ajv=e,this.ajv.opts.strict=false,this.ajv.opts.validateSchema=false;}static getSchemaKey(e,t){let r=this.schemaKeyCache.get(e);r||(r=new Map,this.schemaKeyCache.set(e,r));let s=r.get(t);return s||(s=`${t}_${++this.refCounter}`,r.set(t,s)),s}static getOrCompileValidator(e,t){let r=this.getSchemaKey(e,t),s=this.ajv.getSchema(r);if(s)return s;this.ajv.addSchema(e,r);let n=this.ajv.getSchema(r);if(!n)throw new Error(`Failed to compile schema with key: ${r}`);return n}static getOrCreateSerializer(e,t){if(!e||typeof e!="object")return null;let r=this.serializerCache.get(e);r||(r=new Map,this.serializerCache.set(e,r));let s=r.get(t);if(s)return s;try{let n=Se(e),c=Dt(n,{ajv:this.ajv.opts});return r.set(t,c),c}catch{return null}}static getOrCreateResponseSerializers(e){if(!e)return null;let t=this.responseSerializersCache.get(e);if(t)return t;let r=new Map;for(let[s,n]of Object.entries(e)){let c=Number(s),a=null;if(Q.isZodSchema(n)){let d=Q.toJSONSchema(n);a=this.getOrCreateSerializer(d,"fast_stringify_zod");}else G.isTypeBoxSchema(n)?a=this.getOrCreateSerializer(n,"fast_stringify_typebox"):typeof n=="object"&&n!==null&&(a=this.getOrCreateSerializer(n,"fast_stringify_json"));a&&r.set(c,a);}return this.responseSerializersCache.set(e,r),r}static storeJsonSchema(e,t){let r=this.getSchemaKey(e,t);this.ajv.getSchema(r)||this.ajv.addSchema(e,r);}static getJsonSchema(e,t){let r=this.schemaKeyCache.get(e);if(!r)return;let s=r.get(t);return s?this.ajv.getSchema(s)?.schema:void 0}static clearAllCaches(){this.ajv=new Ajv({validateSchema:false,strict:false}),this.serializerCache=new WeakMap,this.schemaKeyCache=new WeakMap,this.refCounter=0;}static getSchemaCount(){return Object.keys(this.ajv.schemas).length}static getCacheStats(){return {schemaCount:this.getSchemaCount(),totalRefsCreated:this.refCounter}}};var Lt=o=>{if(Q.isZodSchema(o)){try{let t=Q.toJSONSchema(o);M.storeJsonSchema(t,"serialize_zod"),M.getOrCompileValidator(t,"serialize_zod");}catch(t){E.warn({error:t,schemaType:"zod",context:"serialize_decorator"},"Failed to compile Zod schema for validation. Schema may contain unsupported types (e.g., z.instanceof). Runtime validation will still work, but Swagger documentation may be incomplete.");return}return}if(G.isTypeBoxSchema(o)){try{M.storeJsonSchema(o,"serialize_typebox"),M.getOrCompileValidator(o,"serialize_typebox");}catch(t){E.warn({error:t,schemaType:"typebox",context:"serialize_decorator"},"Failed to compile TypeBox schema for validation. Schema may be invalid or use unsupported features.");return}return}if(typeof o=="object"&&o!==null){try{M.storeJsonSchema(o,"serialize_json"),M.getOrCompileValidator(o,"serialize_json");}catch(t){E.warn({error:t,schemaType:"json",context:"serialize_decorator"},"Failed to compile JSON schema for validation. Schema may be invalid or malformed.");return}return}let e=JSON.stringify(o);try{let t={type:typeof o};M.storeJsonSchema(t,`serialize_primitive_${e}`),M.getOrCompileValidator(t,`serialize_primitive_${e}`);}catch(t){E.warn({error:t,schemaType:"primitive",cacheKey:e,context:"serialize_decorator"},"Failed to compile schema for validation. Schema format may be unsupported.");}},ht=o=>{if(Q.isZodSchema(o)){try{let t=Q.toJSONSchema(o);M.storeJsonSchema(t,"zod_schema"),M.getOrCompileValidator(t,"zod_schema");}catch(t){E.warn({error:t,schemaType:"zod",context:"request_validation"},"Failed to compile Zod schema for request validation. Schema may contain unsupported types (e.g., z.instanceof). Swagger documentation may be incomplete.");return}return}if(G.isTypeBoxSchema(o)){try{M.storeJsonSchema(o,"typebox_schema"),M.getOrCompileValidator(o,"typebox_schema");}catch(t){E.warn({error:t,schemaType:"typebox",context:"request_validation"},"Failed to compile TypeBox schema for request validation. Schema may be invalid or use unsupported features.");return}return}if(typeof o=="object"&&o!==null){try{M.storeJsonSchema(o,"json_schema"),M.getOrCompileValidator(o,"json_schema");}catch(t){E.warn({error:t,schemaType:"json",context:"request_validation"},"Failed to compile JSON schema for request validation. Schema may be invalid or malformed.");return}return}let e=JSON.stringify(o);try{let t={type:typeof o};M.storeJsonSchema(t,`primitive_${e}`),M.getOrCompileValidator(t,`primitive_${e}`);}catch(t){E.warn({error:t,schemaType:"primitive",cacheKey:e,context:"request_validation"},"Failed to compile schema for request validation. Schema format may be unsupported.");}},gt=(o,e)=>{o&&ht(o),e&&ht(e);},ft=o=>{if(!o||Object.keys(o).length===0)return;let e={};for(let[t,r]of Object.entries(o)){let s=Number(t);if(e[s]=r,Lt(r),Q.isZodSchema(r))try{let n=Q.toJSONSchema(r);M.getOrCreateSerializer(n,"fast_stringify_zod");}catch{}else G.isTypeBoxSchema(r)?M.getOrCreateSerializer(r,"fast_stringify_typebox"):typeof r=="object"&&r!==null&&M.getOrCreateSerializer(r,"fast_stringify_json");}return e};var Ut=null;function yt(){return Ut}var bt=(o,e)=>async function(t,r,...s){try{if(e.body){let n=t.validate(e.body,!0);t.body=n;}if(e.query){let n=t.validateQuery(e.query,!0);t.query=n;}if(e.all){let n=t.validateAll(e.all,!0);t.body=n;}return o(t,r,...s)}catch(n){let c=yt();return c?c(t,r,n):r.badRequest(n)}};promisify(gzip);promisify(gunzip);var Zt=null;function qt(){return Zt}var Ot=o=>async(e,t,r)=>{for(let s of o)if(!await s.manager.canAccess(s.scope,s.handler,e)){let c=qt();return c?c(e,t):t.unauthorized({error:"Unauthorized"})}return r()};var ve=class{staticChildren;paramChild;wildcardChild;middleware;handler;paramName;constructor(){this.staticChildren=new Map,this.paramChild=null,this.wildcardChild=null,this.middleware=null,this.handler=null,this.paramName=null;}},Ye=class o{trees;routes;middlewares;basePath;staticRouteCache;handlerResponseSchemas;constructor(e="",t=[]){this.trees=new Map,this.routes=[],this.middlewares=t,this.basePath=this.normalizeBasePath(e),this.staticRouteCache=new Map,this.handlerResponseSchemas=new Map;}getRoutes(){return this.routes.slice()}addOrUpdate(e,t,r,s,n,c,a,d=false){e=e.toUpperCase();let u=t.split("?")[0];gt(n?.body,n?.query);let l=ft(a),i=n&&(n.body||n.query||n.all),p=i?bt(s,n):s,h=i?n:void 0,m=this.trees.get(e);m||(m=new ve,this.trees.set(e,m));let g=u.replace(/^\/+|\/+$/g,""),f=g.length===0?[]:g.split("/"),x=true,P=[],T=m;for(let v of f){if(v==="*"){x=false,T.wildcardChild||(T.wildcardChild=new ve),T=T.wildcardChild;break}if(v.startsWith(":")){x=false;let $=v.slice(1);P.push($),T.paramChild||(T.paramChild={node:new ve,name:$}),T=T.paramChild.node;continue}T.staticChildren.has(v)||T.staticChildren.set(v,new ve),T=T.staticChildren.get(v);}if(T.middleware=r,T.handler=p,P.length>0&&(T.paramName=P.join(",")),l&&this.handlerResponseSchemas.set(s,l),x){let v="/"+g,$=`${e}:${v}`;this.staticRouteCache.set($,{middleware:r,handler:p,params:{},responseSchemas:l});}else {let v="/"+g.replace(/:[^/]+/g,"").replace(/\/+/g,"/"),$=`${e}:${v}`;this.staticRouteCache.delete($);}let b=this.routes.findIndex(v=>v.method===e&&v.path===t);if(b!==-1){if(!d)throw new Error(`Duplicate route detected: ${e} ${t} is already registered. Each route must be unique.`);this.routes[b].middleware=r,this.routes[b].handler=p,this.routes[b].swaggerOptions=c,this.routes[b].responses=a,this.routes[b].responseSchemas=l,this.routes[b].validationSchemas=h;return}this.routes.push({method:e,path:t,middleware:r,handler:p,swaggerOptions:c,responses:a,responseSchemas:l,validationSchemas:h});}find(e,t){e=e.toUpperCase();let r=t,s=t.indexOf("?");s!==-1&&(r=t.substring(0,s));let n=`${e}:${r}`,c=this.staticRouteCache.get(n);if(c)return c;let a=this.trees.get(e);if(!a)return null;let d=r.replace(/^\/+|\/+$/g,""),u=d.length===0?[]:d.split("/"),l={},i=a;for(let h=0;h<u.length;h++){let m=u[h];if(i.staticChildren.has(m)){i=i.staticChildren.get(m);continue}if(i.paramChild){l[i.paramChild.name]=m,i=i.paramChild.node;continue}if(i.wildcardChild){l["*"]=u.slice(h).join("/"),i=i.wildcardChild;break}return null}if(!i.handler||!i.middleware)return null;let p=this.handlerResponseSchemas.get(i.handler);return {middleware:i.middleware,handler:i.handler,params:l,responseSchemas:p}}extractOptionsAndHandler(e,t){if(typeof e=="function")return {middlewares:[],handler:e,swaggerOptions:void 0};let r=e,s=Array.isArray(r.middlewares)?r.middlewares:r.middlewares?[r.middlewares]:[];if(r.policy){let c=(Array.isArray(r.policy)?r.policy:[r.policy]).map(a=>({scope:a.scope,handler:a.handler,manager:a.manager}));s.unshift(Ot(c));}if(r.cache);return {middlewares:s,handler:t,body:r.body,query:r.query,all:r.all,responses:r.responses,swaggerOptions:r.swagger}}get(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:c,body:a,query:d,all:u,responses:l,swaggerOptions:i}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...n],h={body:a,query:d,all:u};this.addOrUpdate("GET",s,p,c,h,i,l);}post(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:c,body:a,query:d,all:u,responses:l,swaggerOptions:i}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...n],h={body:a,query:d,all:u};this.addOrUpdate("POST",s,p,c,h,i,l);}patch(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:c,body:a,query:d,all:u,responses:l,swaggerOptions:i}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...n],h={body:a,query:d,all:u};this.addOrUpdate("PATCH",s,p,c,h,i,l);}put(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:c,body:a,query:d,all:u,responses:l,swaggerOptions:i}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...n],h={body:a,query:d,all:u};this.addOrUpdate("PUT",s,p,c,h,i,l);}delete(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:c,body:a,query:d,all:u,responses:l,swaggerOptions:i}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...n],h={body:a,query:d,all:u};this.addOrUpdate("DELETE",s,p,c,h,i,l);}options(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:c,body:a,query:d,all:u,responses:l,swaggerOptions:i}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...n],h={body:a,query:d,all:u};this.addOrUpdate("OPTIONS",s,p,c,h,i,l);}head(e,t,r){let s=this.joinPath(e),{middlewares:n,handler:c,body:a,query:d,all:u,responses:l,swaggerOptions:i}=this.extractOptionsAndHandler(t,r),p=[...this.middlewares,...n],h={body:a,query:d,all:u};this.addOrUpdate("HEAD",s,p,c,h,i,l);}group(e,t,r){let s=Array.isArray(t)?t:typeof t=="function"?[]:t?[t]:[],n=Array.isArray(t)?r:typeof t=="function"?t:void 0,c=this.joinPath(e),a=new o(c,[...this.middlewares,...s]);n?.(a);for(let d of a.getRoutes())this.addOrUpdate(d.method,d.path,d.middleware,d.handler,d.validationSchemas,d.swaggerOptions,d.responses);}applyGlobalMiddlewaresToAllRoutes(e){for(let t of this.routes){let r=[...e,...t.middleware||[]];this.addOrUpdate(t.method,t.path,r,t.handler,void 0,void 0,void 0,true);}}normalizeBasePath(e){if(!e)return "";let t=e.replace(/\s+/g,"");return t=t.replace(/\/+/g,"/"),t.startsWith("/")||(t="/"+t),t.length>1&&(t=t.replace(/\/+$/g,"")),t}joinPath(e){let r=[this.basePath,e].filter(s=>typeof s=="string"&&s.length>0).join("/");return r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r.length>1&&(r=r.replace(/\/+$/g,"")),r}clearRoutes(){this.routes=[],this.staticRouteCache.clear(),this.handlerResponseSchemas.clear(),this.trees.clear();}};new Ye;var X=class{static scheduledJobs=[];static logger=E.child({scope:"CronService"});static register(e,...t){t[2]={name:e,...t[2]},this.scheduledJobs.push({name:e,args:t});}static async run(){let e=(await import('node-cron').catch(()=>{throw new F("node-cron not installed as a dependency, it is required in order to run cron jobs with the @cron decorator")})).default;if(this.logger.info("Scheduling cron jobs"),!this.scheduledJobs.length){this.logger.info("No cron jobs to schedule");return}for(let{name:t,args:r}of this.scheduledJobs)this.logger.info(`Scheduling cron job: ${t}`),e.schedule(...r).on("execution:failed",n=>this.globalErrorHandler(n));this.logger.info("Cron jobs scheduled");}static globalErrorHandler(e){this.logger.error(e.execution?.error);}static async massiveImportCronJobs(e){let t=[];for(let r of e){let s=await y.glob(r,{cwd:N.getCwd()});t.push(...s);}await Promise.all(t.map(async r=>{await import(r).catch(s=>{this.logger.error(`Error importing cron job: ${r}`),E.error(s);});}));}};var re=class extends q{static commandName="cron-start";static description="Start cron job scheduler";static help=["Start the cron job scheduler to run scheduled tasks","Loads cron jobs from specified patterns and starts scheduling","Example: npx balda cron-start","Example: npx balda cron-start src/crons/**/*.ts --patterns src/schedules/**/*.ts"];static options={keepAlive:true};static pattern;static additionalPatterns;static async handle(){this.logger.info("Starting cron scheduler...");let e=[this.pattern];this.additionalPatterns&&this.additionalPatterns.length>0&&e.push(...this.additionalPatterns),this.logger.info(`Loading cron jobs from patterns: ${e.join(", ")}`),await X.massiveImportCronJobs(e);let t=X.scheduledJobs.length;if(t===0){this.logger.warn("No cron jobs found. Make sure your cron jobs are decorated with @cron decorator");return}this.logger.info(`Found ${t} cron job(s)`),X.run().then(()=>{this.logger.info("Cron scheduler started successfully. Press Ctrl+C to stop.");}).catch(r=>{this.logger.error("Error starting cron scheduler",r);});}};S([R({required:false,defaultValue:"src/crons/**/*.{ts,js}",description:"Primary glob pattern for cron jobs (default: src/crons/**/*.{ts,js})"})],re,"pattern"),S([C.array({aliases:["p"],name:"patterns",required:false,description:"Additional glob patterns for cron jobs"})],re,"additionalPatterns");var we=class extends q{static commandName="generate-command";static description="Generate a new command in the specified path";static help=["Generate a new cli command in the specified path","Example: npx balda generate-command my-command -p src/commands"];static path="src/commands";static name;static async handle(){if(H.getCommand(this.name)){let s=H.isBuiltInCommand(this.name)?"built-in":"user-defined";this.logger.error({commandName:this.name,type:s},`Command "${this.name}" already exists as a ${s} command. Cannot override existing commands.`);return}let t=this.getCommandTemplate();this.path=w.join(this.path,`${this.name}.ts`),await y.exists(w.join(process.cwd(),this.path))||await y.mkdir(w.join(process.cwd(),this.path.split("/").slice(0,-1).join("/")),{recursive:true}),await y.writeFile(this.path,new TextEncoder().encode(t)),this.logger.info(`Command ${this.name} created successfully at ${this.path}`);}static getCommandTemplate(){return `import { Command, CommandOptions } from "balda";
|
|
8
8
|
|
|
9
9
|
export default class extends Command {
|
|
10
10
|
static commandName = "${this.name}";
|
|
@@ -116,10 +116,10 @@ export default class extends BaseQueue {
|
|
|
116
116
|
this.logger.info({ payload }, 'Payload received');
|
|
117
117
|
return Promise.resolve();
|
|
118
118
|
}
|
|
119
|
-
}`}};S([R({description:"The name of the queue to generate",required:true})],Z,"queueName"),S([C({description:"The path to the queue to generate, default is src/queues",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/queues"})],Z,"path"),S([C({description:"The provider of the queue to generate, default is bullmq",type:"string",aliases:["pr"],name:"provider",required:false,defaultValue:"bullmq"})],Z,"provider");var
|
|
119
|
+
}`}};S([R({description:"The name of the queue to generate",required:true})],Z,"queueName"),S([C({description:"The path to the queue to generate, default is src/queues",type:"string",aliases:"p",name:"path",required:false,defaultValue:"src/queues"})],Z,"path"),S([C({description:"The provider of the queue to generate, default is bullmq",type:"string",aliases:["pr"],name:"provider",required:false,defaultValue:"bullmq"})],Z,"provider");var k=class extends q{static commandName="generate-sdk";static description="Generate a TypeScript SDK from your server's OpenAPI specification";static help=["Generate a TypeScript SDK from your server's OpenAPI specification","This command imports your server instance, starts it if needed, downloads the OpenAPI spec, and generates an SDK","","Arguments:"," serverPath Path to the server instance file (default: test/server/instance.ts)","","Flags:"," -o, --output <path> Output directory for generated SDK (default: sdk)"," -s, --swagger-path <path> Swagger UI path on your server (default: /docs)"," -c, --client <type> HTTP client to use: axios or fetch (default: fetch)"," --unwrap-response-data Automatically unwrap response data property"," --single-http-client Generate single HTTP client instance"," --type-prefix <prefix> Add prefix to all generated types"," --type-suffix <suffix> Add suffix to all generated types"," --enum-names-as-values Use enum names as values"," --sort-types Sort types alphabetically","","Examples:"," npx balda generate-sdk"," npx balda generate-sdk src/server/index.ts -o ./client-sdk"," npx balda generate-sdk src/server.ts --client axios"," npx balda generate-sdk --unwrap-response-data --single-http-client"," npx balda generate-sdk --type-prefix Api --sort-types"];static serverPath;static outputPath;static swaggerPath;static httpClient;static unwrapResponseData;static singleHttpClient;static typePrefix;static typeSuffix;static enumNamesAsValues;static sortTypes;static async handle(){console.log(`
|
|
120
120
|
\u{1F680} Starting SDK generation...
|
|
121
121
|
`);let e="swagger-typescript-api",t=w.join(process.cwd(),"node_modules"),r=await y.exists(t),s=w.join(t,e);if(!(r?await y.exists(s):false)){console.log(`\u{1F4E6} ${e} not found. Installing as dev dependency...
|
|
122
|
-
`);let[b,v,$]=await I();if(!await
|
|
122
|
+
`);let[b,v,$]=await I();if(!await j(`${b} ${v} ${e} ${$}`,b,[e],{stdio:"inherit"},true)){console.log(`\x1B[33m\u26A0\uFE0F SDK generation cancelled: swagger-typescript-api installation was skipped.\x1B[0m
|
|
123
123
|
`);return}console.log(`
|
|
124
124
|
\x1B[32m\u2705 ${e} installed successfully!\x1B[0m
|
|
125
125
|
`);}let c=w.resolve(process.cwd(),this.serverPath);if(!await y.exists(c)){console.error(`\x1B[31m\u274C Error: Server file not found at ${c}\x1B[0m
|
|
@@ -133,7 +133,7 @@ export default class extends BaseQueue {
|
|
|
133
133
|
`);}catch(b){console.error("\x1B[31m\u274C Error generating SDK:\x1B[0m",b);}finally{try{await y.unlink(P);}catch{}if(i){let b=l;try{console.log("\u{1F6D1} Stopping server..."),await b.close?.(),console.log(`\u2705 Server stopped.
|
|
134
134
|
`);}catch{console.log(`\x1B[33m\u26A0\uFE0F Could not stop server gracefully.\x1B[0m
|
|
135
135
|
`);}}}console.log(`\x1B[32m\u2728 SDK generation complete!\x1B[0m
|
|
136
|
-
`);}};S([R({description:"Path to the server instance file (should export a Server instance)",required:false,defaultValue:"test/server/instance.ts"})],
|
|
136
|
+
`);}};S([R({description:"Path to the server instance file (should export a Server instance)",required:false,defaultValue:"test/server/instance.ts"})],k,"serverPath"),S([C({description:"Output directory for generated SDK",type:"string",aliases:["o"],name:"output",required:false,defaultValue:"sdk"})],k,"outputPath"),S([C({description:"Swagger UI path on your server",type:"string",aliases:["s"],name:"swagger-path",required:false})],k,"swaggerPath"),S([C({description:"HTTP client to use (axios or fetch)",type:"string",aliases:["c"],name:"client",required:false,defaultValue:"fetch"})],k,"httpClient"),S([C({description:"Unwrap response data automatically",type:"boolean",name:"unwrap-response-data",required:false,defaultValue:false})],k,"unwrapResponseData"),S([C({description:"Generate single HTTP client instance",type:"boolean",name:"single-http-client",required:false,defaultValue:false})],k,"singleHttpClient"),S([C({description:"Add prefix to all generated types",type:"string",name:"type-prefix",required:false})],k,"typePrefix"),S([C({description:"Add suffix to all generated types",type:"string",name:"type-suffix",required:false})],k,"typeSuffix"),S([C({description:"Use enum names as values",type:"boolean",name:"enum-names-as-values",required:false,defaultValue:false})],k,"enumNamesAsValues"),S([C({description:"Sort types alphabetically",type:"boolean",name:"sort-types",required:false,defaultValue:false})],k,"sortTypes");var J=class extends q{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 graphql;static devDependencies=["esbuild","esbuild-plugin-copy","tsx","typescript"];static async handle(){this.logger.info("Initializing project...");let[e,t,r]=await I();if(["npm","yarn","pnpm"].includes(e)){let d=await W(this.devDependencies);if(d.length&&(this.logger.info(`Found ${d.length} missing dev dependencies`),!await j(`${e} ${t} ${d.join(" ")} -${r}`,e,d,{stdio:"inherit"}))){this.logger.info("Installation cancelled by user. Project initialization aborted.");return}d.length||this.logger.info("All dev dependencies are already installed");}if(this.mqtt&&["npm","yarn","pnpm"].includes(e)){let d=await W(["mqtt"]);d.length&&(await j(`${e} ${t} mqtt`,e,["mqtt"],{stdio:"inherit"},false)||(this.logger.info("MQTT installation cancelled by user. Skipping MQTT scaffolding."),this.mqtt=false)),d.length||this.logger.info("MQTT package is already installed");}if(this.cron&&["npm","yarn","pnpm"].includes(e)){let d=await W(["node-cron"]);d.length>0&&(await j(`${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)),d.length||this.logger.info("node-cron package is already installed");}if(this.graphql&&["npm","yarn","pnpm"].includes(e)){let d=await W(["@apollo/server","@graphql-tools/schema","graphql"]);d.length>0&&(await j(`${e} ${t} ${d.join(" ")}`,e,d,{stdio:"inherit"},false)||(this.logger.info("GraphQL installation cancelled by user. Skipping GraphQL scaffolding."),this.graphql=false)),d.length||this.logger.info("GraphQL packages are already installed");}let s=this.typescript?"ts":"js",n=this.getServerTemplate(),c=this.getIndexTemplate();y.exists(this.srcPath)||await y.mkdir(this.srcPath,{recursive:true}),this.logger.info(`Creating server.${s} file...`),await y.writeFile(`${this.srcPath}/server.${s}`,new TextEncoder().encode(n)),this.logger.info(`Creating index.${s} file...`),await y.writeFile(`${this.srcPath}/index.${s}`,new TextEncoder().encode(c));let a=this.getLoggerTemplate();if(this.logger.info(`Creating logger.${s} file...`),await y.writeFile(`${this.srcPath}/logger.${s}`,new TextEncoder().encode(a)),this.mqtt){let d=w.join(this.srcPath,"mqtt");await y.exists(d)||await y.mkdir(d,{recursive:true});let u=this.getMqttConfigTemplate();this.logger.info(`Creating mqtt/mqtt.config.${s} file...`),await y.writeFile(w.join(d,`mqtt.config.${s}`),new TextEncoder().encode(u));}if(this.cron){let d=w.join(this.srcPath,"cron");await y.exists(d)||await y.mkdir(d,{recursive:true});let u=this.getCronConfigTemplate();this.logger.info(`Creating cron/cron.config.${s} file...`),await y.writeFile(w.join(d,`cron.config.${s}`),new TextEncoder().encode(u));}if(this.graphql){let d=w.join(this.srcPath,"graphql");await y.exists(d)||await y.mkdir(d,{recursive:true});let u=this.getGraphqlConfigTemplate();this.logger.info(`Creating graphql/graphql.config.${s} file...`),await y.writeFile(w.join(d,`graphql.config.${s}`),new TextEncoder().encode(u));}this.logger.info("Project initialized successfully!");}static getServerTemplate(){return `import { Server } from "balda";
|
|
137
137
|
import { logger } from "./logger.js";
|
|
138
138
|
|
|
139
139
|
const serverInstance = new Server({
|
|
@@ -203,7 +203,7 @@ import { CommandRegistry } from "../command_registry.js";
|
|
|
203
203
|
|
|
204
204
|
export const logger = pino({ level: "info" });
|
|
205
205
|
CommandRegistry.setLogger(logger);
|
|
206
|
-
`}};S([C.string({description:"The path to the project, default is the current directory /src",aliases:"p",name:"path",required:false,defaultValue:"./src"})],J,"srcPath"),S([C.boolean({description:"Whether to use typescript, default is true",aliases:"t",name:"typescript",required:false,defaultValue:true})],J,"typescript"),S([C.boolean({description:"Initialize MQTT service connection",aliases:"m",name:"mqtt",required:false,defaultValue:false})],J,"mqtt"),S([C.boolean({description:"Initialize Cron service",aliases:"c",name:"cron",required:false,defaultValue:false})],J,"cron"),S([C.boolean({description:"Initialize GraphQL service",aliases:"g",name:"graphql",required:false,defaultValue:false})],J,"graphql");var le=class extends q{static commandName="init-mailer";static description="Initialize mailer configuration with required dependencies";static help=["Initialize a mailer configuration file with basic setup","Automatically installs required packages for nodemailer and optional template engines","Supports Handlebars, EJS, Edge.js, Mustache, or custom adapters","Example: npx balda init-mailer -t handlebars -o src/mailer"];static templateEngine;static outputPath;static mailerDependencies={base:["nodemailer","@types/nodemailer"],handlebars:["handlebars","@types/handlebars"],ejs:["ejs","@types/ejs"],edge:["edge.js"],mustache:["mustache","@types/mustache"]};static async handle(){if(this.logger.info("Initializing mailer configuration..."),!["handlebars","ejs","edge","mustache","custom","none"].includes(this.templateEngine)){this.logger.error(`Invalid template engine: ${this.templateEngine}. Must be one of: handlebars, ejs, edge, mustache, custom, none`);return}let[e,t]=await I();if(["npm","yarn","pnpm"].includes(e)){let c=[...this.mailerDependencies.base,...this.templateEngine!=="none"&&this.templateEngine!=="custom"?this.mailerDependencies[this.templateEngine]||[]:[]],a=await W(c);if(a.length>0&&(this.logger.info(`Found ${a.length} missing dependencies for mailer`),!await
|
|
206
|
+
`}};S([C.string({description:"The path to the project, default is the current directory /src",aliases:"p",name:"path",required:false,defaultValue:"./src"})],J,"srcPath"),S([C.boolean({description:"Whether to use typescript, default is true",aliases:"t",name:"typescript",required:false,defaultValue:true})],J,"typescript"),S([C.boolean({description:"Initialize MQTT service connection",aliases:"m",name:"mqtt",required:false,defaultValue:false})],J,"mqtt"),S([C.boolean({description:"Initialize Cron service",aliases:"c",name:"cron",required:false,defaultValue:false})],J,"cron"),S([C.boolean({description:"Initialize GraphQL service",aliases:"g",name:"graphql",required:false,defaultValue:false})],J,"graphql");var le=class extends q{static commandName="init-mailer";static description="Initialize mailer configuration with required dependencies";static help=["Initialize a mailer configuration file with basic setup","Automatically installs required packages for nodemailer and optional template engines","Supports Handlebars, EJS, Edge.js, Mustache, or custom adapters","Example: npx balda init-mailer -t handlebars -o src/mailer"];static templateEngine;static outputPath;static mailerDependencies={base:["nodemailer","@types/nodemailer"],handlebars:["handlebars","@types/handlebars"],ejs:["ejs","@types/ejs"],edge:["edge.js"],mustache:["mustache","@types/mustache"]};static async handle(){if(this.logger.info("Initializing mailer configuration..."),!["handlebars","ejs","edge","mustache","custom","none"].includes(this.templateEngine)){this.logger.error(`Invalid template engine: ${this.templateEngine}. Must be one of: handlebars, ejs, edge, mustache, custom, none`);return}let[e,t]=await I();if(["npm","yarn","pnpm"].includes(e)){let c=[...this.mailerDependencies.base,...this.templateEngine!=="none"&&this.templateEngine!=="custom"?this.mailerDependencies[this.templateEngine]||[]:[]],a=await W(c);if(a.length>0&&(this.logger.info(`Found ${a.length} missing dependencies for mailer`),!await j(`${e} ${t} ${a.join(" ")}`,e,a,{stdio:"inherit"},false))){this.logger.info("Installation cancelled by user. Mailer initialization aborted.");return}a.length===0&&this.logger.info("All mailer dependencies are already installed");}let r=this.getConfigTemplate(),s="mailer.config.ts",n=w.join(this.outputPath,s);await y.exists(this.outputPath)||await y.mkdir(this.outputPath,{recursive:true}),this.logger.info(`Creating ${s} file at ${this.outputPath}...`),await y.writeFile(n,new TextEncoder().encode(r)),this.logger.info(`Mailer configuration initialized successfully at ${n}`),this.logger.info("Remember to update the configuration with your actual SMTP credentials"),this.templateEngine!=="none"&&this.logger.info(`Template engine '${this.templateEngine}' configured and ready to use`);}static getConfigTemplate(){let e=this.templateEngine!=="none";return `import { createTransport } from "nodemailer";
|
|
207
207
|
import { Mailer${e?`, ${this.getAdapterImport()}`:""} } from "balda";
|
|
208
208
|
|
|
209
209
|
/**
|
|
@@ -330,7 +330,7 @@ const adapter = new CustomAdapter();
|
|
|
330
330
|
* appName: "My App",
|
|
331
331
|
* },
|
|
332
332
|
* });
|
|
333
|
-
*`}};S([C.string({description:"Template engine (handlebars, ejs, edge, mustache, custom, none) - optional",aliases:"t",name:"template",required:false,defaultValue:"none"})],le,"templateEngine"),S([C.string({description:"Output directory for mailer configuration, default is src/mailer",aliases:"o",name:"output",required:false,defaultValue:"src/mailer"})],le,"outputPath");var ce=class extends q{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 I();if(["npm","yarn","pnpm"].includes(e)){let c=this.queueDependencies[this.queueType],a=await W(c);if(a.length>0&&(this.logger.info(`Found ${a.length} missing dependencies for ${this.queueType}`),!await
|
|
333
|
+
*`}};S([C.string({description:"Template engine (handlebars, ejs, edge, mustache, custom, none) - optional",aliases:"t",name:"template",required:false,defaultValue:"none"})],le,"templateEngine"),S([C.string({description:"Output directory for mailer configuration, default is src/mailer",aliases:"o",name:"output",required:false,defaultValue:"src/mailer"})],le,"outputPath");var ce=class extends q{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 I();if(["npm","yarn","pnpm"].includes(e)){let c=this.queueDependencies[this.queueType],a=await W(c);if(a.length>0&&(this.logger.info(`Found ${a.length} missing dependencies for ${this.queueType}`),!await j(`${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 r=this.getConfigTemplate(),s=`${this.queueType}.config.ts`,n=w.join(this.outputPath,s);await y.exists(this.outputPath)||await y.mkdir(this.outputPath,{recursive:true}),this.logger.info(`Creating ${s} file at ${this.outputPath}...`),await y.writeFile(n,new TextEncoder().encode(r)),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";
|
|
334
334
|
|
|
335
335
|
// Configure BullMQ connection and default options
|
|
336
336
|
defineBullMQConfiguration({
|
|
@@ -499,24 +499,24 @@ definePGBossConfiguration({
|
|
|
499
499
|
* console.log("Processing:", payload);
|
|
500
500
|
* });
|
|
501
501
|
*/
|
|
502
|
-
`}};S([C.string({description:"Queue provider type (bullmq, sqs, pgboss) - required",aliases:"t",name:"type",required:true})],ce,"queueType"),S([C.string({description:"Output directory for queue configuration, default is src/queue",aliases:"o",name:"output",required:false,defaultValue:"src/queue"})],ce,"outputPath");var xe=class extends q{static commandName="key-generate";static description="Generate application encryption key pairs";static help=["Generate secure RSA public/private key pairs for application encryption","Keys are automatically saved to .env file","Example: npx balda key-generate","Example: npx balda key-generate --type async"];static type;static async handle(){let e=this.type??"sync";if(!["sync","async"].includes(e)){this.logger.error(`Invalid key type: ${e}. Must be sync or async`);return}let{publicKey:t,privateKey:r}=
|
|
502
|
+
`}};S([C.string({description:"Queue provider type (bullmq, sqs, pgboss) - required",aliases:"t",name:"type",required:true})],ce,"queueType"),S([C.string({description:"Output directory for queue configuration, default is src/queue",aliases:"o",name:"output",required:false,defaultValue:"src/queue"})],ce,"outputPath");var xe=class extends q{static commandName="key-generate";static description="Generate application encryption key pairs";static help=["Generate secure RSA public/private key pairs for application encryption","Keys are automatically saved to .env file","Example: npx balda key-generate","Example: npx balda key-generate --type async"];static type;static async handle(){let e=this.type??"sync";if(!["sync","async"].includes(e)){this.logger.error(`Invalid key type: ${e}. Must be sync or async`);return}let{publicKey:t,privateKey:r}=rr.generateKeyPairSync("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}}),s=e==="sync"?"APP_PUBLIC_KEY":"APP_PUBLIC_KEY_ASYNC",n=e==="sync"?"APP_PRIVATE_KEY":"APP_PRIVATE_KEY_ASYNC";console.log(`
|
|
503
503
|
\u2728 Generated ${e==="sync"?"Sync":"Async"} Key Pair:
|
|
504
504
|
`),console.log(`\x1B[33mPublic Key (${s}):\x1B[0m`),console.log(`\x1B[32m${t}\x1B[0m`),console.log(`\x1B[33mPrivate Key (${n}):\x1B[0m`),console.log(`\x1B[32m${r}\x1B[0m`),await this.saveKeyToEnvFile(s,t),await this.saveKeyToEnvFile(n,r),console.log(`\x1B[90m\u{1F4A1} Keys saved to .env file as ${s} and ${n}\x1B[0m
|
|
505
505
|
`);}static async saveKeyToEnvFile(e,t){let r=Ae.join(N.getCwd(),".env"),s=`${e}="${t}"`;if(Ce.existsSync(r)){let n=Ce.readFileSync(r,"utf-8"),c=new RegExp(`^${e}=.*$`,"m");if(c.test(n)){let a=n.replace(c,s);Ce.writeFileSync(r,a),this.logger.info(`Updated ${e} in .env file`);return}Ce.appendFileSync(r,`
|
|
506
506
|
${s}
|
|
507
507
|
`),this.logger.info(`Added ${e} to .env file`);return}Ce.writeFileSync(r,`${s}
|
|
508
|
-
`),this.logger.info(`Created .env file with ${e}`);}};S([C.string({aliases:["t"],name:"type",required:false,defaultValue:"sync",description:"Key type: sync or async (default: sync)"})],xe,"type");var Pe=class extends q{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=
|
|
508
|
+
`),this.logger.info(`Created .env file with ${e}`);}};S([C.string({aliases:["t"],name:"type",required:false,defaultValue:"sync",description:"Key type: sync or async (default: sync)"})],xe,"type");var Pe=class extends q{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=H.getBuiltInCommands(),t=H.getUserDefinedCommands();if(console.log(`
|
|
509
509
|
\u2728 Available Balda Commands:
|
|
510
510
|
`),t.length>0){console.log(`\x1B[1;33mUser Commands:\x1B[0m
|
|
511
511
|
`);let r=this.groupByCategory(t);this.displayCategorizedCommands(r);}if(e.length>0){console.log(`\x1B[1;32mBuilt-in Commands:\x1B[0m
|
|
512
512
|
`);let r=e.sort((n,c)=>n.commandName.localeCompare(c.commandName)),s=Math.max(...r.map(n=>n.commandName.length));for(let n of r){let c=n.commandName.padEnd(s+2),a=n.description||"No description available",d="";n.options?.deprecated&&(d=" \x1B[33m[deprecated]\x1B[0m"),console.log(` \x1B[36m${c}\x1B[0m ${a}${d}`);}console.log("");}console.log(`\x1B[90mRun 'npx balda <command> -h' for more information on a specific command.\x1B[0m
|
|
513
|
-
`);}static groupByCategory(e){let t=new Map;for(let r of e){let s=r.options?.category||"other";t.has(s)||t.set(s,[]),t.get(s).push(r);}return t}static displayCategorizedCommands(e){let t=Array.from(e.keys()).sort();for(let r of t){let s=e.get(r).filter(d=>d&&d.commandName).sort((d,u)=>d.commandName.localeCompare(u.commandName));if(s.length===0)continue;let c={generator:"\x1B[35m",setup:"\x1B[34m",production:"\x1B[32m",utility:"\x1B[36m",other:"\x1B[37m"}[r]||"\x1B[37m";console.log(` ${c}${r.toUpperCase()}:\x1B[0m`);let a=Math.max(...s.map(d=>d.commandName.length));for(let d of s){let u=d.commandName.padEnd(a+2),l=d.description||"No description available",i="";d.options?.deprecated&&(i=" \x1B[33m[deprecated]\x1B[0m"),console.log(` \x1B[36m${u}\x1B[0m ${l}${i}`);}console.log("");}}};var L=class extends F{constructor(...e){super(`Library not installed: ${e.join(", ")}, try run npm install ${e.join(" ")}`);}};var rt=class{randomUUID(){return crypto.randomUUID()}},qe=new rt;var V=class{static options={connection:{}}};var Be=class{queues=new Map;workers=new Map;async publish(e,t,r){let s=await this.getQueue(e),n=qe.randomUUID();return await s.add(e,t,{jobId:n,...V.options?.defaultJobOptions,...r}),{id:n}}async subscribe(e,t){if(this.workers.has(e))throw new Error(`[BullMQ] Already subscribed to topic "${e}"`);let{errorHandler:r,...s}=V.options??{},n=await this.getBullMQClient(),c=new n.Worker(e,async a=>{try{await t(a.data);}catch(d){await r?.(a,d)??Promise.reject(d);}},{...s});this.workers.set(e,c);}async unsubscribe(e){let t=this.workers.get(e);t&&(await t.close(),this.workers.delete(e));}async getQueue(e){if(!this.queues.has(e)){let t=await import('bullmq').catch(()=>{throw new L("bullmq","ioredis")}),r=new t.Queue(e,{...V.options||{connection:{}}});this.queues.set(e,r);}return this.queues.get(e)}async getBullMQClient(){return this.bullmqClient||(this.bullmqClient=await import('bullmq').catch(()=>{throw new L("bullmq","ioredis")})),this.bullmqClient}async publishWithConfig(e,t,r,s){let n=await this.getQueueWithConfig(e,s),c=qe.randomUUID(),a={jobId:c,...V.options?.defaultJobOptions,...s?.defaultJobOptions,...r};return await n.add(e,t,a),{id:c}}async subscribeWithConfig(e,t,r){let s=this.getWorkerKey(e,r);if(this.workers.has(s))throw new Error(`[BullMQ] Already subscribed to topic "${e}"`);let n=V.options??{},{errorHandler:c}=n,a=await this.getBullMQClient(),d={...n,...r};delete d.errorHandler,delete d.defaultJobOptions;let u=new a.Worker(e,async l=>{try{await t(l.data);}catch(i){await c?.(l,i)??Promise.reject(i);}},d);this.workers.set(s,u);}async getQueueWithConfig(e,t){let r=this.getQueueKey(e,t);if(!this.queues.has(r)){let s=await import('bullmq').catch(()=>{throw new L("bullmq","ioredis")}),n={...V.options||{connection:{}},...t},c=new s.Queue(e,n);this.queues.set(r,c);}return this.queues.get(r)}getQueueKey(e,t){return t?.connection?`${e}:${JSON.stringify(t.connection)}`:e}getWorkerKey(e,t){return this.getQueueKey(e,t)}};var Qe=class{subscribers=new Map;messageQueue=[];maxQueueSize;processingPromise=null;constructor(e=1e4){this.maxQueueSize=e;}clear(){this.subscribers.clear(),this.messageQueue=[],this.processingPromise=null;}async publish(e,t,r){if(this.messageQueue.length>=this.maxQueueSize)throw new Error(`Queue full: ${this.maxQueueSize} messages pending`);let s=qe.randomUUID();return this.messageQueue.push({topic:e,payload:t}),this.processingPromise||(this.processingPromise=this.processQueue().catch(n=>{console.error("[MemoryPubSub] Fatal queue processing error:",n);}).finally(()=>{this.processingPromise=null;})),{id:s}}async subscribe(e,t){this.subscribers.has(e)||this.subscribers.set(e,new Set);let r=t;this.subscribers.get(e).add(r);}async unsubscribe(e){this.subscribers.delete(e);}async processQueue(){for(;this.messageQueue.length>0;){let e=this.messageQueue.shift();if(!e)break;let t=this.subscribers.get(e.topic);t&&t.size>0&&await Promise.allSettled(Array.from(t).map(r=>r(e.payload).catch(s=>{console.error(`[MemoryPubSub] Handler error for topic "${e.topic}":`,s);})));}}};var K=class{static options={}};var De=class{createdQueues=new Set;workers=new Map;async publish(e,t,r){let s=await this.getBoss();await this.ensureQueue(e);let n=r||{},c=await s.send(e,t,n);return {id:String(c??"")}}async subscribe(e,t){let r=await this.getBoss();await this.ensureQueue(e);let s=K.options;s.errorHandler&&r.on("error",s.errorHandler);let n=await r.work(e,async c=>{let a=Array.isArray(c)?c:[c];for(let d of a)await t(d.data);});this.workers.set(e,n);}async unsubscribe(e){let t=await this.getBoss(),r=this.workers.get(e);r&&(await t.offWork(r),this.workers.delete(e));}async getBoss(){if(this.boss)return this.boss;let e=await import('pg-boss').catch(()=>{throw new L("pg-boss","pg")}),r=e.PgBoss.default??e.PgBoss,{connectionString:s,boss:n}=K.options,c=s??n,a=new r(c);return K.options?.errorHandler&&a.on("error",K.options.errorHandler),await a.start(),this.boss=a,this.boss}async ensureQueue(e){if(this.createdQueues.has(e))return;let t=await this.getBoss();typeof t.createQueue=="function"&&await t.createQueue(e),this.createdQueues.add(e);}async publishWithConfig(e,t,r,s){let n=await this.getBossWithConfig(s);await this.ensureQueueWithBoss(e,n);let c=r||{},a=await n.send(e,t,c);return {id:String(a??"")}}async subscribeWithConfig(e,t,r){let s=await this.getBossWithConfig(r);await this.ensureQueueWithBoss(e,s);let n=K.options;n.errorHandler&&s.on("error",n.errorHandler);let c=`${e}:${r?.connectionString??"default"}`,a=await s.work(e,async d=>{let u=Array.isArray(d)?d:[d];for(let l of u)await t(l.data);});this.workers.set(c,a);}bossInstances=new Map;async getBossWithConfig(e){if(!e?.connectionString)return this.getBoss();let t=e.connectionString;if(this.bossInstances.has(t))return this.bossInstances.get(t);let r=await import('pg-boss').catch(()=>{throw new L("pg-boss","pg")}),n=r.PgBoss.default??r.PgBoss,c=new n(e.connectionString);return K.options?.errorHandler&&c.on("error",K.options.errorHandler),await c.start(),this.bossInstances.set(t,c),c}async ensureQueueWithBoss(e,t){this.createdQueues.has(e)||(typeof t.createQueue=="function"&&await t.createQueue(e),this.createdQueues.add(e));}};var de=class{static options={}};var Le=class{consumers=new Map;client;async publish(e,t,r){let s=await this.getClient(),{SendMessageCommand:n}=await this.getSqsLib(),c=await this.resolveQueueUrl(e);if(!c)throw new Error(`[SQS] Queue url not configured for topic "${e}"`);let a=new n({MessageBody:JSON.stringify(t),MessageAttributes:{topic:{DataType:"String",StringValue:e}},QueueUrl:c,...r??{}});return {id:(await s.send(a)).MessageId??""}}async subscribe(e,t){if(this.consumers.has(e))throw new Error(`[SQS] Already subscribed to topic "${e}"`);let r=de.options,s=await this.getSqsConsumerLib(),n={...r.consumer||{},sqs:await this.getClient(),queueUrl:await this.resolveQueueUrl(e),handleMessage:async d=>{let u=JSON.parse(d.Body||"{}");await t(u);}},c=s.Consumer.create(n),a=r.errorHandler;a&&(c.on("error",a),c.on("processing_error",a)),c.start(),this.consumers.set(e,c);}async unsubscribe(e){let t=this.consumers.get(e);t&&(t.stop(),this.consumers.delete(e));}async getClient(){if(this.client)return this.client;let{SQSClient:e}=await this.getSqsLib(),t=de.options.client;return this.client=new e(t??{}),this.client}async getSqsLib(){return this.sqsLib||(this.sqsLib=await import('@aws-sdk/client-sqs').catch(()=>{throw new L("@aws-sdk/client-sqs","sqs-consumer")})),this.sqsLib}async getSqsConsumerLib(){return this.sqsConsumerLib||(this.sqsConsumerLib=await import('sqs-consumer').catch(()=>{throw new L("sqs-consumer")})),this.sqsConsumerLib}async resolveQueueUrl(e){let r=de.options.consumer?.queueUrlMap;if(!r?.[e])throw new Error(`[SQS] Queue url not configured for topic "${e}"`);return r[e]}async publishWithConfig(e,t,r,s){let{...n}=r??{},c=await this.getClientWithConfig(s?.client),{SendMessageCommand:a}=await this.getSqsLib(),d=s?.queueUrl??await this.resolveQueueUrl(e),u=new a({...n,MessageBody:JSON.stringify(t),MessageAttributes:{topic:{DataType:"String",StringValue:e}},QueueUrl:d});return {id:(await c.send(u)).MessageId??""}}async subscribeWithConfig(e,t,r){if(this.consumers.has(e))throw new Error(`[SQS] Already subscribed to topic "${e}"`);let s=de.options,n=await this.getSqsConsumerLib(),c=r?.queueUrl??await this.resolveQueueUrl(e),a={...s.consumer||{},sqs:await this.getClientWithConfig(r?.client),queueUrl:c,handleMessage:async l=>{let i=JSON.parse(l.Body||"{}");await t(i);}},d=n.Consumer.create(a),u=s.errorHandler;u&&(d.on("error",u),d.on("processing_error",u)),d.start(),this.consumers.set(e,d);}async getClientWithConfig(e){if(e){let{SQSClient:t}=await this.getSqsLib();return new t(e)}return this.getClient()}};var He=class{static map=new Map;static{this.map.set("bullmq",new Be),this.map.set("sqs",new Le),this.map.set("pgboss",new De),this.map.set("memory",new Qe);}static getProvider(e){if(!this.map.has(e))throw new Error(`[QueueSubscriber] Provider ${e} not found`);return this.map.get(e)}static setProvider(e,t){this.map.set(e,t);}static clearMemoryProvider(){let e=this.map.get("memory");e&&"clear"in e&&e.clear();}};var ue=class{static typedQueueSubscribers=new Map;static customQueueSubscribers=new Map;static logger=E.child({scope:"QueueService"});static instanceFactory=e=>new e;static registerTypedQueue(e,t,r,s,n){let c=`${s}:${t}:${e}`;this.typedQueueSubscribers.has(c)&&this.logger.warn(`Queue handler for ${c} already registered, overwriting previous handler`),this.typedQueueSubscribers.set(c,{name:e,topic:t,handler:r,provider:s,queueOptions:n});}static registerCustomQueue(e,t,r,s){let n=`${s.constructor.name}:${t}:${e}`;this.customQueueSubscribers.has(n)&&this.logger.warn(`Custom queue handler for ${n} already registered, overwriting previous handler`),this.customQueueSubscribers.set(n,{name:e,topic:t,handler:r,pubsub:s});}static async run(){this.logger.info("Subscribing queue handlers");let e=this.typedQueueSubscribers.size>0,t=this.customQueueSubscribers.size>0;if(!e&&!t){this.logger.info("No queue handlers to subscribe");return}for(let r of this.typedQueueSubscribers.values()){let{topic:s,handler:n,provider:c,queueOptions:a}=r;this.logger.info(`Subscribing to queue: ${s}`);let d=He.getProvider(c);a&&"subscribeWithConfig"in d&&typeof d.subscribeWithConfig=="function"?await d.subscribeWithConfig(s,n,a):await d.subscribe(s,n);}for(let{topic:r,handler:s,pubsub:n}of this.customQueueSubscribers.values())this.logger.info(`Subscribing to custom queue: ${r}`),await n.subscribe(r,s);this.logger.info("Queue handlers subscribed");}static async massiveImportQueues(e,t={}){let r=[];for(let s of e){let n=await y.glob(s,{cwd:N.getCwd()});this.logger.info(`Pattern "${s}" matched ${n.length} file(s)`),r.push(...n);}if(r.length===0){this.logger.warn("No files matched the provided patterns");return}this.logger.info(`Importing ${r.length} queue handler file(s)`),await Promise.all(r.map(async s=>{this.logger.debug(`Importing: ${s}`),await import(s).catch(n=>{if(this.logger.error(`Error importing queue handler: ${s}`),this.logger.error(n),t.throwOnError)throw n});})),this.logger.info(`Successfully imported ${r.length} file(s)`);}};var pe=class extends q{static commandName="queue-start";static description="Start queue workers to process jobs";static help=["Start queue workers to process jobs from registered queues","Loads queue handlers from specified patterns and starts processing","Example: npx balda queue-start","Example: npx balda queue-start src/queues/**/*.ts --patterns src/jobs/**/*.ts"];static options={keepAlive:true};static pattern;static additionalPatterns;static async handle(){this.logger.info("Starting queue workers...");let e=[this.pattern];this.additionalPatterns&&this.additionalPatterns.length>0&&e.push(...this.additionalPatterns),this.logger.info(`Loading queue handlers from patterns: ${e.join(", ")}`),await ue.massiveImportQueues(e,{throwOnError:false});let t=ue.typedQueueSubscribers.size,r=ue.customQueueSubscribers.size,s=t+r;if(s===0){this.logger.warn("No queue handlers found. Make sure your queue handlers are decorated with @queue decorator");return}this.logger.info(`Found ${s} queue handler(s) (${t} typed, ${r} custom)`),ue.run().then(()=>{this.logger.info("Queue workers started successfully. Press Ctrl+C to stop.");}).catch(n=>{this.logger.error("Error starting queue workers",n);});}};S([R({required:false,defaultValue:"src/queues/**/*.{ts,js}",description:"Primary glob pattern for queue handlers (default: src/queues/**/*.{ts,js})"})],pe,"pattern"),S([C.list({aliases:["p"],name:"patterns",required:false,description:"Additional glob patterns for queue handlers"})],pe,"additionalPatterns");var me=class extends q{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=O.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:N.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:N.getCwd()});return}this.handleNodeHotReload();}static async handleNodeHotReload(){if(!Ce.existsSync("node_modules/.bin/tsx")){let[r,s,n]=await I();if(!await k(`${r} ${s} tsx ${n}`,r,["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()});}};S([R({required:false,defaultValue:"src/index.ts",description:"The entry point of the project, default is src/index.ts"})],me,"entry"),S([C.string({aliases:["d"],name:"deno-import-map",required:false,description:"Path to deno import map"})],me,"denoImportMap");var he=class extends q{static commandName="init-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
|
|
513
|
+
`);}static groupByCategory(e){let t=new Map;for(let r of e){let s=r.options?.category||"other";t.has(s)||t.set(s,[]),t.get(s).push(r);}return t}static displayCategorizedCommands(e){let t=Array.from(e.keys()).sort();for(let r of t){let s=e.get(r).filter(d=>d&&d.commandName).sort((d,u)=>d.commandName.localeCompare(u.commandName));if(s.length===0)continue;let c={generator:"\x1B[35m",setup:"\x1B[34m",production:"\x1B[32m",utility:"\x1B[36m",other:"\x1B[37m"}[r]||"\x1B[37m";console.log(` ${c}${r.toUpperCase()}:\x1B[0m`);let a=Math.max(...s.map(d=>d.commandName.length));for(let d of s){let u=d.commandName.padEnd(a+2),l=d.description||"No description available",i="";d.options?.deprecated&&(i=" \x1B[33m[deprecated]\x1B[0m"),console.log(` \x1B[36m${u}\x1B[0m ${l}${i}`);}console.log("");}}};var D=class extends F{constructor(...e){super(`Library not installed: ${e.join(", ")}, try run npm install ${e.join(" ")}`);}};var rt=class{randomUUID(){return crypto.randomUUID()}},qe=new rt;var V=class{static options={connection:{}}};var Be=class{queues=new Map;workers=new Map;async publish(e,t,r){let s=await this.getQueue(e),n=qe.randomUUID();return await s.add(e,t,{jobId:n,...V.options?.defaultJobOptions,...r}),{id:n}}async subscribe(e,t){if(this.workers.has(e))throw new Error(`[BullMQ] Already subscribed to topic "${e}"`);let{errorHandler:r,...s}=V.options??{},n=await this.getBullMQClient(),c=new n.Worker(e,async a=>{try{await t(a.data);}catch(d){await r?.(a,d)??Promise.reject(d);}},{...s});this.workers.set(e,c);}async unsubscribe(e){let t=this.workers.get(e);t&&(await t.close(),this.workers.delete(e));}async getQueue(e){if(!this.queues.has(e)){let t=await import('bullmq').catch(()=>{throw new D("bullmq","ioredis")}),r=new t.Queue(e,{...V.options||{connection:{}}});this.queues.set(e,r);}return this.queues.get(e)}async getBullMQClient(){return this.bullmqClient||(this.bullmqClient=await import('bullmq').catch(()=>{throw new D("bullmq","ioredis")})),this.bullmqClient}async publishWithConfig(e,t,r,s){let n=await this.getQueueWithConfig(e,s),c=qe.randomUUID(),a={jobId:c,...V.options?.defaultJobOptions,...s?.defaultJobOptions,...r};return await n.add(e,t,a),{id:c}}async subscribeWithConfig(e,t,r){let s=this.getWorkerKey(e,r);if(this.workers.has(s))throw new Error(`[BullMQ] Already subscribed to topic "${e}"`);let n=V.options??{},{errorHandler:c}=n,a=await this.getBullMQClient(),d={...n,...r};delete d.errorHandler,delete d.defaultJobOptions;let u=new a.Worker(e,async l=>{try{await t(l.data);}catch(i){await c?.(l,i)??Promise.reject(i);}},d);this.workers.set(s,u);}async getQueueWithConfig(e,t){let r=this.getQueueKey(e,t);if(!this.queues.has(r)){let s=await import('bullmq').catch(()=>{throw new D("bullmq","ioredis")}),n={...V.options||{connection:{}},...t},c=new s.Queue(e,n);this.queues.set(r,c);}return this.queues.get(r)}getQueueKey(e,t){return t?.connection?`${e}:${JSON.stringify(t.connection)}`:e}getWorkerKey(e,t){return this.getQueueKey(e,t)}};var Qe=class{subscribers=new Map;messageQueue=[];maxQueueSize;processingPromise=null;constructor(e=1e4){this.maxQueueSize=e;}clear(){this.subscribers.clear(),this.messageQueue=[],this.processingPromise=null;}async publish(e,t,r){if(this.messageQueue.length>=this.maxQueueSize)throw new Error(`Queue full: ${this.maxQueueSize} messages pending`);let s=qe.randomUUID();return this.messageQueue.push({topic:e,payload:t}),this.processingPromise||(this.processingPromise=this.processQueue().catch(n=>{console.error("[MemoryPubSub] Fatal queue processing error:",n);}).finally(()=>{this.processingPromise=null;})),{id:s}}async subscribe(e,t){this.subscribers.has(e)||this.subscribers.set(e,new Set);let r=t;this.subscribers.get(e).add(r);}async unsubscribe(e){this.subscribers.delete(e);}async processQueue(){for(;this.messageQueue.length>0;){let e=this.messageQueue.shift();if(!e)break;let t=this.subscribers.get(e.topic);t&&t.size>0&&await Promise.allSettled(Array.from(t).map(r=>r(e.payload).catch(s=>{console.error(`[MemoryPubSub] Handler error for topic "${e.topic}":`,s);})));}}};var K=class{static options={}};var He=class{createdQueues=new Set;workers=new Map;async publish(e,t,r){let s=await this.getBoss();await this.ensureQueue(e);let n=r||{},c=await s.send(e,t,n);return {id:String(c??"")}}async subscribe(e,t){let r=await this.getBoss();await this.ensureQueue(e);let s=K.options;s.errorHandler&&r.on("error",s.errorHandler);let n=await r.work(e,async c=>{let a=Array.isArray(c)?c:[c];for(let d of a)await t(d.data);});this.workers.set(e,n);}async unsubscribe(e){let t=await this.getBoss(),r=this.workers.get(e);r&&(await t.offWork(r),this.workers.delete(e));}async getBoss(){if(this.boss)return this.boss;let e=await import('pg-boss').catch(()=>{throw new D("pg-boss","pg")}),r=e.PgBoss.default??e.PgBoss,{connectionString:s,boss:n}=K.options,c=s??n,a=new r(c);return K.options?.errorHandler&&a.on("error",K.options.errorHandler),await a.start(),this.boss=a,this.boss}async ensureQueue(e){if(this.createdQueues.has(e))return;let t=await this.getBoss();typeof t.createQueue=="function"&&await t.createQueue(e),this.createdQueues.add(e);}async publishWithConfig(e,t,r,s){let n=await this.getBossWithConfig(s);await this.ensureQueueWithBoss(e,n);let c=r||{},a=await n.send(e,t,c);return {id:String(a??"")}}async subscribeWithConfig(e,t,r){let s=await this.getBossWithConfig(r);await this.ensureQueueWithBoss(e,s);let n=K.options;n.errorHandler&&s.on("error",n.errorHandler);let c=`${e}:${r?.connectionString??"default"}`,a=await s.work(e,async d=>{let u=Array.isArray(d)?d:[d];for(let l of u)await t(l.data);});this.workers.set(c,a);}bossInstances=new Map;async getBossWithConfig(e){if(!e?.connectionString)return this.getBoss();let t=e.connectionString;if(this.bossInstances.has(t))return this.bossInstances.get(t);let r=await import('pg-boss').catch(()=>{throw new D("pg-boss","pg")}),n=r.PgBoss.default??r.PgBoss,c=new n(e.connectionString);return K.options?.errorHandler&&c.on("error",K.options.errorHandler),await c.start(),this.bossInstances.set(t,c),c}async ensureQueueWithBoss(e,t){this.createdQueues.has(e)||(typeof t.createQueue=="function"&&await t.createQueue(e),this.createdQueues.add(e));}};var de=class{static options={}};var De=class{consumers=new Map;client;async publish(e,t,r){let s=await this.getClient(),{SendMessageCommand:n}=await this.getSqsLib(),c=await this.resolveQueueUrl(e);if(!c)throw new Error(`[SQS] Queue url not configured for topic "${e}"`);let a=new n({MessageBody:JSON.stringify(t),MessageAttributes:{topic:{DataType:"String",StringValue:e}},QueueUrl:c,...r??{}});return {id:(await s.send(a)).MessageId??""}}async subscribe(e,t){if(this.consumers.has(e))throw new Error(`[SQS] Already subscribed to topic "${e}"`);let r=de.options,s=await this.getSqsConsumerLib(),n={...r.consumer||{},sqs:await this.getClient(),queueUrl:await this.resolveQueueUrl(e),handleMessage:async d=>{let u=JSON.parse(d.Body||"{}");await t(u);}},c=s.Consumer.create(n),a=r.errorHandler;a&&(c.on("error",a),c.on("processing_error",a)),c.start(),this.consumers.set(e,c);}async unsubscribe(e){let t=this.consumers.get(e);t&&(t.stop(),this.consumers.delete(e));}async getClient(){if(this.client)return this.client;let{SQSClient:e}=await this.getSqsLib(),t=de.options.client;return this.client=new e(t??{}),this.client}async getSqsLib(){return this.sqsLib||(this.sqsLib=await import('@aws-sdk/client-sqs').catch(()=>{throw new D("@aws-sdk/client-sqs","sqs-consumer")})),this.sqsLib}async getSqsConsumerLib(){return this.sqsConsumerLib||(this.sqsConsumerLib=await import('sqs-consumer').catch(()=>{throw new D("sqs-consumer")})),this.sqsConsumerLib}async resolveQueueUrl(e){let r=de.options.consumer?.queueUrlMap;if(!r?.[e])throw new Error(`[SQS] Queue url not configured for topic "${e}"`);return r[e]}async publishWithConfig(e,t,r,s){let{...n}=r??{},c=await this.getClientWithConfig(s?.client),{SendMessageCommand:a}=await this.getSqsLib(),d=s?.queueUrl??await this.resolveQueueUrl(e),u=new a({...n,MessageBody:JSON.stringify(t),MessageAttributes:{topic:{DataType:"String",StringValue:e}},QueueUrl:d});return {id:(await c.send(u)).MessageId??""}}async subscribeWithConfig(e,t,r){if(this.consumers.has(e))throw new Error(`[SQS] Already subscribed to topic "${e}"`);let s=de.options,n=await this.getSqsConsumerLib(),c=r?.queueUrl??await this.resolveQueueUrl(e),a={...s.consumer||{},sqs:await this.getClientWithConfig(r?.client),queueUrl:c,handleMessage:async l=>{let i=JSON.parse(l.Body||"{}");await t(i);}},d=n.Consumer.create(a),u=s.errorHandler;u&&(d.on("error",u),d.on("processing_error",u)),d.start(),this.consumers.set(e,d);}async getClientWithConfig(e){if(e){let{SQSClient:t}=await this.getSqsLib();return new t(e)}return this.getClient()}};var Le=class{static map=new Map;static{this.map.set("bullmq",new Be),this.map.set("sqs",new De),this.map.set("pgboss",new He),this.map.set("memory",new Qe);}static getProvider(e){if(!this.map.has(e))throw new Error(`[QueueSubscriber] Provider ${e} not found`);return this.map.get(e)}static setProvider(e,t){this.map.set(e,t);}static clearMemoryProvider(){let e=this.map.get("memory");e&&"clear"in e&&e.clear();}};var ue=class{static typedQueueSubscribers=new Map;static customQueueSubscribers=new Map;static logger=E.child({scope:"QueueService"});static instanceFactory=e=>new e;static registerTypedQueue(e,t,r,s,n){let c=`${s}:${t}:${e}`;this.typedQueueSubscribers.has(c)&&this.logger.warn(`Queue handler for ${c} already registered, overwriting previous handler`),this.typedQueueSubscribers.set(c,{name:e,topic:t,handler:r,provider:s,queueOptions:n});}static registerCustomQueue(e,t,r,s){let n=`${s.constructor.name}:${t}:${e}`;this.customQueueSubscribers.has(n)&&this.logger.warn(`Custom queue handler for ${n} already registered, overwriting previous handler`),this.customQueueSubscribers.set(n,{name:e,topic:t,handler:r,pubsub:s});}static async run(){this.logger.info("Subscribing queue handlers");let e=this.typedQueueSubscribers.size>0,t=this.customQueueSubscribers.size>0;if(!e&&!t){this.logger.info("No queue handlers to subscribe");return}for(let r of this.typedQueueSubscribers.values()){let{topic:s,handler:n,provider:c,queueOptions:a}=r;this.logger.info(`Subscribing to queue: ${s}`);let d=Le.getProvider(c);a&&"subscribeWithConfig"in d&&typeof d.subscribeWithConfig=="function"?await d.subscribeWithConfig(s,n,a):await d.subscribe(s,n);}for(let{topic:r,handler:s,pubsub:n}of this.customQueueSubscribers.values())this.logger.info(`Subscribing to custom queue: ${r}`),await n.subscribe(r,s);this.logger.info("Queue handlers subscribed");}static async massiveImportQueues(e,t={}){let r=[];for(let s of e){let n=await y.glob(s,{cwd:N.getCwd()});this.logger.info(`Pattern "${s}" matched ${n.length} file(s)`),r.push(...n);}if(r.length===0){this.logger.warn("No files matched the provided patterns");return}this.logger.info(`Importing ${r.length} queue handler file(s)`),await Promise.all(r.map(async s=>{this.logger.debug(`Importing: ${s}`),await import(s).catch(n=>{if(this.logger.error(`Error importing queue handler: ${s}`),this.logger.error(n),t.throwOnError)throw n});})),this.logger.info(`Successfully imported ${r.length} file(s)`);}};var pe=class extends q{static commandName="queue-start";static description="Start queue workers to process jobs";static help=["Start queue workers to process jobs from registered queues","Loads queue handlers from specified patterns and starts processing","Example: npx balda queue-start","Example: npx balda queue-start src/queues/**/*.ts --patterns src/jobs/**/*.ts"];static options={keepAlive:true};static pattern;static additionalPatterns;static async handle(){this.logger.info("Starting queue workers...");let e=[this.pattern];this.additionalPatterns&&this.additionalPatterns.length>0&&e.push(...this.additionalPatterns),this.logger.info(`Loading queue handlers from patterns: ${e.join(", ")}`),await ue.massiveImportQueues(e,{throwOnError:false});let t=ue.typedQueueSubscribers.size,r=ue.customQueueSubscribers.size,s=t+r;if(s===0){this.logger.warn("No queue handlers found. Make sure your queue handlers are decorated with @queue decorator");return}this.logger.info(`Found ${s} queue handler(s) (${t} typed, ${r} custom)`),ue.run().then(()=>{this.logger.info("Queue workers started successfully. Press Ctrl+C to stop.");}).catch(n=>{this.logger.error("Error starting queue workers",n);});}};S([R({required:false,defaultValue:"src/queues/**/*.{ts,js}",description:"Primary glob pattern for queue handlers (default: src/queues/**/*.{ts,js})"})],pe,"pattern"),S([C.list({aliases:["p"],name:"patterns",required:false,description:"Additional glob patterns for queue handlers"})],pe,"additionalPatterns");var me=class extends q{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=O.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:N.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:N.getCwd()});return}this.handleNodeHotReload();}static async handleNodeHotReload(){if(!Ce.existsSync("node_modules/.bin/tsx")){let[r,s,n]=await I();if(!await j(`${r} ${s} tsx ${n}`,r,["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()});}};S([R({required:false,defaultValue:"src/index.ts",description:"The entry point of the project, default is src/index.ts"})],me,"entry"),S([C.string({aliases:["d"],name:"deno-import-map",required:false,description:"Path to deno import map"})],me,"denoImportMap");var he=class extends q{static commandName="init-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
|
|
514
514
|
`);return}this.outputPath||await y.mkdir(w.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
|
|
515
515
|
`);return}console.log(`
|
|
516
516
|
\u{1F680} Setting up ${this.storageType.toUpperCase()} storage provider...
|
|
517
517
|
`);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
|
|
518
518
|
`),t.length){let r=await this.checkMissingDependencies(t);if(r.length===0&&console.log(`\x1B[32m\u2705 All required dependencies are already installed.\x1B[0m
|
|
519
|
-
`),r.length){let[s,n]=await I(),c=`${s} ${n} ${r.join(" ")}`;if(!await
|
|
519
|
+
`),r.length){let[s,n]=await I(),c=`${s} ${n} ${r.join(" ")}`;if(!await j(c,s,r,{stdio:"inherit"},false)){console.log(`\x1B[33m\u26A0\uFE0F Dependency installation skipped by user.\x1B[0m
|
|
520
520
|
`);return}console.log(`
|
|
521
521
|
\x1B[32m\u2705 Dependencies installed successfully!\x1B[0m
|
|
522
522
|
`);}}await this.createStorageSetup(this.storageType,this.outputPath),console.log(`\x1B[32m\u2728 ${this.storageType.toUpperCase()} storage setup complete!\x1B[0m
|
|
@@ -600,11 +600,11 @@ export const storage = new Storage(
|
|
|
600
600
|
defaultProvider: "local",
|
|
601
601
|
},
|
|
602
602
|
);
|
|
603
|
-
`}[e]||""}};S([C({description:"Storage provider type (s3, azure, local)",type:"string",aliases:["t"],name:"type",required:true})],he,"storageType"),S([C({description:"Output directory for storage setup",type:"string",aliases:["o"],name:"output",required:false,defaultValue:"src/storage/"})],he,"outputPath");var
|
|
603
|
+
`}[e]||""}};S([C({description:"Storage provider type (s3, azure, local)",type:"string",aliases:["t"],name:"type",required:true})],he,"storageType"),S([C({description:"Output directory for storage setup",type:"string",aliases:["o"],name:"output",required:false,defaultValue:"src/storage/"})],he,"outputPath");var or=[ae,we,ne,ie,Z,se,oe,k,J,le,ce,Pe,B,me,he,xe,pe,re],U=class o{commands;builtInCommands;static commandsPattern="src/commands/**/*.{ts,js}";static loggerPath="src/logger.ts";static logger=E.child({scope:"CommandRegistry"});static setLogger(e){o.logger=e.child({scope:"CommandRegistry"}),q.logger=e.child({scope:"Command"});}static async loadLogger(e){let t=e||o.loggerPath;try{let r=await import(w.join(N.getCwd(),t));r.logger&&o.setLogger(r.logger);}catch{o.logger.debug(`Could not load logger from ${t}, using default logger`);}}constructor(){this.commands=new Map,this.builtInCommands=new Set;}static getInstance(){return new o}static setCommandsPattern(e){this.commandsPattern=e;}getLogger(){return o.logger}setLogger(e){o.logger=e.child({scope:"CommandRegistry"}),q.logger=e.child({scope:"Command"});}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){o.logger.info(`Loading commands from ${e}`);let t=await y.glob(e,{cwd:N.getCwd()});if(t.some(r=>r.endsWith(".ts")))try{let{register:r}=await import('module');r("ts-node/esm",import.meta.url);}catch{o.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 r of t){let s=await import(r).then(n=>n.default?n.default:n).catch(n=>(o.logger.error(`Error loading command ${r}: ${n}`),null));s&&this.commands.set(s.commandName,s);}for(let r of or)this.commands.set(r.commandName,r),this.builtInCommands.add(r.commandName);}},H=U.getInstance();var ir=o=>{let e=new Map;for(let t of o){let r=t.options?.category||"other";e.has(r)||e.set(r,[]),e.get(r).push(t);}return e},ar=o=>{let e=Array.from(o.keys()).sort();for(let t of e){let r=o.get(t).filter(a=>a&&a.commandName);if(!r.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(...r.map(a=>a.commandName.length));for(let a of r){let d=a.commandName.padEnd(c+2),u=a.description||"No description available",l="";a.options?.deprecated&&(l=" \x1B[33m[deprecated]\x1B[0m"),console.log(` \x1B[36m${d}\x1B[0m ${u}${l}`);}console.log("");}},nt=async()=>{await U.loadLogger(),await H.loadCommands(U.commandsPattern);let[o,...e]=ye.getCliArgs();if(!o||o==="-h"||o==="--help"){let n=H.getBuiltInCommands(),c=H.getUserDefinedCommands();if(console.log(`
|
|
604
604
|
\u2728 Available Balda Commands:
|
|
605
605
|
`),c.length&&(console.log(`\x1B[1;33mUser Commands:\x1B[0m
|
|
606
|
-
`),
|
|
606
|
+
`),ar(ir(c))),n.length){console.log(`\x1B[1;32mBuilt-in Commands:\x1B[0m
|
|
607
607
|
`);let a=Math.max(...n.map(d=>d.commandName.length));for(let d of n){let u=d.commandName.padEnd(a+2),l=d.description||"No description available",i="";d.options?.deprecated&&(i=" \x1B[33m[deprecated]\x1B[0m"),console.log(` \x1B[36m${u}\x1B[0m ${l}${i}`);}console.log("");}console.log(`\x1B[90mRun 'npx balda <command> -h' for more information on a specific command.\x1B[0m
|
|
608
|
-
`),z.exit(0);return}let t=
|
|
608
|
+
`),z.exit(0);return}let t=H.getCommand(o);if(!t){console.error(ct(o,H.getCommands().filter(n=>n&&n.commandName).map(n=>n.commandName))||`Command ${o} not found`),z.exit(1);return}let r=t;if(r.calledBy=w.basename(ye.getCliCaller()),r.options?.deprecated){let n=r.options.deprecated.message||"This command is deprecated",c=r.options.deprecated.replacement;console.warn(`\x1B[33m\u26A0\uFE0F Warning: ${n}\x1B[0m`),c&&console.warn(`\x1B[33m Use '${c}' instead.\x1B[0m
|
|
609
609
|
`);}if(await U.loadLogger(r.options?.loggerPath),r.handleHelpFlag(r.flags),r.validateUnknownFlags(r),r.validateContext(r),r.options?.validate&&!await r.options.validate(r)){console.error("Command validation failed"),z.exit(1);return}await r.handle(),(t.options?.keepAlive??false)||z.exit(0);};typeof process<"u"?nt().catch(async o=>{if(o?.message?.includes("SyntaxError")||o?.code==="ERR_UNKNOWN_FILE_EXTENSION")try{let{register:e}=await import('module');e("ts-node/esm",import.meta.url),nt().catch(t=>{U.logger.error(t),process.exit(1);});}catch{U.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 U.logger.error(o),process.exit(1);}):nt().catch(o=>{U.logger.error(o),z.exit(1);});export{nt as cli};//# sourceMappingURL=cli.js.map
|
|
610
610
|
//# sourceMappingURL=cli.js.map
|