@elysiumjs/core 0.4.3 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,19 @@
1
+ // @bun
2
+ var Z0=Object.defineProperty;var $0=(L,Y)=>{for(var Q in Y)Z0(L,Q,{get:Y[Q],enumerable:!0,configurable:!0,set:(X)=>Y[Q]=()=>X})};var $2=(L,Y)=>()=>(L&&(Y=L(L=0)),Y);import*as D2 from"readline";import{isEmpty as U0,omit as _0}from"radash";class k{static SPACE_WIDTH=60;write(L,Y=!0,Q=process.stdout){Q.write(L+(Y?`
3
+ `:""))}newLine(){this.write(`
4
+ `,!1)}info(L){this.write(`${this.format("\u2139",4)} ${L}`)}success(L){this.write(`${this.format("\u2714",2)} ${L}`)}warning(L){this.write(`${this.format("\u26A0",3)} ${L}`)}error(L){this.write(`${this.format("\u2716",1)} ${L}`,!0,process.stderr)}debug(L){if(process.env.DEBUG)this.write(`\uD83D\uDD0D ${L}`)}trace(L,Y){if(!L)return;let Q=L.name||"Error",X=L.message||"An error occurred",Z=L.stack||"";if(Y)this.title(Y);else this.newLine();if(this.write(this.format(`${Q}: ${X}`,1)),L.stack)this.write(this.format("Stack Trace:",9)),this.write(this.format(Z.split(`
5
+ `).map((U)=>` ${U}`).join(`
6
+ `),8));let $=_0(L,["name","message","stack"]);if(!U0($))this.write(this.format("Additional Information:",9)),Object.keys($).forEach((U)=>{let _=L[U];this.write(` ${U}: ${JSON.stringify(_)}`)});this.newLine()}title(L){this.newLine(),this.write(this.format(L,9,10)),this.newLine()}section(L){this.newLine(),this.write(`\x1B[1m${L}\x1B[0m`)}table(L,Y){if(L.length===0){this.info("No data to display");return}let Q=Object.keys(Y||L[0]),X={};for(let U of Q){let _=Y?.[U];if(_?.width){X[U]=_.width;continue}let V=(_?.header||String(U)).length,H=Math.max(...L.map((G)=>{let R=G[U];if(_?.format)return _.format(R).length;return String(R===null||R===void 0?"":R).length}));X[U]=Math.max(V,H)}let Z="",$="";for(let U of Q){let V=Y?.[U]?.header||String(U),H=X[U];Z+=`| ${V.padEnd(H)} `,$+=`| ${"-".repeat(H)} `}Z+="|",$+="|",this.write(Z),this.write($);for(let U of L){let _="";for(let V of Q){let H=Y?.[V],G=X[V],R=U[V],W;if(H?.format)W=H.format(R);else W=String(R===null||R===void 0?"":R);_+=`| ${W.padEnd(G)} `}_+="|",this.write(_)}this.newLine()}format(L,...Y){return`${Y.map((X)=>G0[X]).join("")}${L}\x1B[0m`}bold(L){return this.format(L,9)}italic(L){return this.format(L,11)}underline(L){return this.format(L,10)}clear(){process.stdout.write("\x1Bc")}moveCursor(L,Y){process.stdout.moveCursor(L,Y)}clearLine(){process.stdout.clearLine(0),process.stdout.cursorTo(0)}async prompt(L,Y){let Q=D2.createInterface({input:process.stdin,output:process.stdout}),X=Y?` (default: ${Y})`:"";return new Promise((Z)=>{Q.question(`${L}${X}: `,($)=>{Q.close(),Z($||Y||"")})})}async promptPassword(L){let Y=D2.createInterface({input:process.stdin,output:process.stdout});return process.stdin.setRawMode?.(!0),new Promise((Q)=>{let X="";process.stdout.write(`${L}: `),process.stdin.on("data",(Z)=>{let $=Z.toString();if($==="\r"||$===`
7
+ `){process.stdout.write(`
8
+ `),process.stdin.setRawMode?.(!1),process.stdin.removeAllListeners("data"),Y.close(),Q(X);return}if($==="\b"||$==="\x7F"){if(X.length>0)X=X.slice(0,-1),process.stdout.write("\b \b");return}X+=$,process.stdout.write("*")})})}async confirm(L,Y=!1){let Q=Y?"Y/n":"y/N",X=await this.prompt(`${L} [${Q}]`);if(!X)return Y;return X.toLowerCase()==="y"||X.toLowerCase()==="yes"}async select(L,Y,Q=0){if(Y.length===0)throw new Error("No options provided for selection");this.write(L),Y.forEach(($,U)=>{let _=U===Q;this.write(` ${U+1}. ${$}${_?" (default)":""}`)});let X=await this.prompt("Enter your choice (number)");if(!X)return Y[Q];let Z=parseInt(X,10)-1;if(isNaN(Z)||Z<0||Z>=Y.length)return this.warning(`Invalid selection. Using default: ${Y[Q]}`),Y[Q];return Y[Z]}formatTime(L){if(L<60)return`${L.toFixed(1)}s`;if(L<3600)return`${Math.floor(L/60)}m ${Math.floor(L%60)}s`;return`${Math.floor(L/3600)}h ${Math.floor(L%3600/60)}m`}}var O2,G0;var e=$2(()=>{((P)=>{P[P.BLACK=0]="BLACK";P[P.RED=1]="RED";P[P.GREEN=2]="GREEN";P[P.YELLOW=3]="YELLOW";P[P.BLUE=4]="BLUE";P[P.MAGENTA=5]="MAGENTA";P[P.CYAN=6]="CYAN";P[P.WHITE=7]="WHITE";P[P.GRAY=8]="GRAY";P[P.BOLD=9]="BOLD";P[P.UNDERLINE=10]="UNDERLINE";P[P.ITALIC=11]="ITALIC";P[P.INVERSE=12]="INVERSE"})(O2||={});G0={[0]:Bun.color("black","ansi")||Bun.color("black","ansi-256")||"",[1]:Bun.color("red","ansi")||Bun.color("red","ansi-256")||"",[2]:Bun.color("green","ansi")||Bun.color("green","ansi-256")||"",[3]:Bun.color("yellow","ansi")||Bun.color("yellow","ansi-256")||"",[4]:Bun.color("blue","ansi")||Bun.color("blue","ansi-256")||"",[5]:Bun.color("magenta","ansi")||Bun.color("magenta","ansi-256")||"",[6]:Bun.color("cyan","ansi")||Bun.color("cyan","ansi-256")||"",[7]:Bun.color("white","ansi")||Bun.color("white","ansi-256")||"",[8]:Bun.color("gray","ansi")||Bun.color("gray","ansi-256")||"",[9]:"\x1B[1m",[10]:"\x1B[4m",[11]:"\x1B[3m",[12]:"\x1B[7m"}});import{isObject as U2,isPrimitive as O0}from"radash";function o(L,...Y){if(!Y.length)return L;let Q=Y.shift();if(Q===void 0)return L;if(U2(L)&&U2(Q))for(let X in Q)if(U2(Q[X])){if(!L[X])Object.assign(L,{[X]:Q[X]})}else if(Array.isArray(Q[X])){if(!Array.isArray(L[X]))L[X]=[];if(Q[X].length>0&&!U2(Q[X][0]))L[X]=[...new Set([...L[X],...Q[X]])];else Q[X].forEach((Z,$)=>{if(U2(Z)&&L[X][$])L[X][$]=o(L[X][$],Z);else if(!L[X].includes(Z))L[X].push(Z)})}else if(O0(Q[X]))L[X]??=Q[X];else o(L[X],Q[X]);return o(L,...Y)}var O,n=()=>new Promise((L)=>process.nextTick(L));var g=$2(()=>{((T)=>(T.app=Symbol("elysium:Application"),T.controller=Symbol("elysium:Controller"),T.middlewares=Symbol("elysium:MiddlewaresList"),T.services=Symbol("elysium:ServicesList"),T.websocket=Symbol("elysium:WebSocket"),T.wamp=Symbol("elysium:Wamp"),T.http=Symbol("elysium:Http"),T.job=Symbol("elysium:Job"),T.arg=Symbol("elysium:CommandArguments"),T.elysiaPlugin=Symbol("elysium:ElysiaPlugin"),T.middlewareGuards=Symbol("elysium:MiddlewareGuards")))(O||={})});import{isString as L2}from"radash";var N2,P0=(L)=>{return typeof L==="function"&&L.prototype&&L.prototype.constructor===L},s,z;var d=$2(()=>{g();((Q)=>{Q[Q.SINGLETON=0]="SINGLETON";Q[Q.FACTORY=1]="FACTORY"})(N2||={});s=new Map;((E)=>{E.register=(G)=>{return function(R){let W=G?.name??R.name,P=G?.scope??0;if(z.exists(W))console.error(`A service with the name ${W} has already been registered.`),process.exit(1);let K=()=>z.make(R);if(P===0){let C=K();s.set(W,{scope:P,factory(){return C}})}else s.set(W,{scope:P,factory:K})}},E.inject=(G)=>{return function(R,W,P){let K=Reflect.getMetadata(O.services,R,W)??[],C=Reflect.getMetadata("design:paramtypes",R,W)??[],y=L2(G)?G:G?.name??C[P].name;K.push({name:y,index:P}),Reflect.defineMetadata(O.services,K,R,W)}},E.get=(G)=>{let R=L2(G)?G:G.name;if(E.exists(R))return s.get(R).factory();return null},E.make=(G)=>{let R=Reflect.getMetadata(O.services,G)??[],W=[];return R.forEach((P)=>{let K=E.get(P.name);if(K===null)console.error(`Cannot inject service ${P.name}. No service was registered with the name: ${P.name}`),process.exit(1);W[P.index]=K}),new G(...W)},E.bind=(G,R)=>{let W=E.make(G);return E.instance(R??G.name,W)};function $(G,R){let W=L2(G)?G:R??G.name;if(E.exists(W))console.error(`A service with the name ${W} has already been registered.`),process.exit(1);let P=()=>{return P0(G)?E.make(G):R()};return s.set(W,{scope:1,factory:P}),P()}E.factory=$,E.instance=(G,R)=>{let W=L2(G)?G:G.name;if(E.exists(W))console.error(`A service with the name ${W} has already been registered.`),process.exit(1);return s.set(W,{scope:0,factory(){return R}}),R},E.remove=(G)=>{let R=L2(G)?G:G.name;s.delete(R)},E.exists=(G)=>{let R=L2(G)?G:G.name;return s.has(R)},E.clear=()=>{s.clear()}})(z||={})});import"reflect-metadata";import{assign as K0,uid as j0}from"radash";var d2;var j2=$2(()=>{e();d();g();d2=class d2 extends k{#L;#Y;#Q="pending";#X;static register(L={}){return function(Y){L=K0({name:Y.name,queue:"default"},L);let Q=`job.${L.name}`;z.instance(Q,Y),Reflect.defineMetadata(O.job,{name:Q,queue:L.queue},Y)}}id;createdAt;get startedAt(){return this.#L}get completedAt(){return this.#Y}get status(){return this.#Q}constructor(L){super();this.id=L||this.generateJobId(),this.createdAt=new Date}async run(){try{this.#Q="running",this.#L=new Date,this.debug(`Job ${this.id} started at ${this.#L.toISOString()}`),await this.execute(),this.#Q="completed",this.#Y=new Date,this.debug(`Job ${this.id} completed at ${this.#Y.toISOString()}`)}catch(L){if(this.#X=L instanceof Error?L:new Error(String(L)),this.#Q!=="cancelled")this.#Q="failed";this.#Y=new Date,this.trace(this.#X)}}cancel(){this.#Q="cancelled"}generateJobId(){return`job_${Date.now()}_${j0(8)}`}}});var l2={};$0(l2,{WorkerPool:()=>R2,Worker:()=>F2});import{uid as F0}from"radash";var p2,F2,R2;var E2=$2(()=>{e();j2();d();g();p2=globalThis.Worker;F2=class F2 extends k{#L;queues=new Map;defaultQueueName="default";static spawn(L,Y=["default"],Q){let X=new this;X.debug(`Worker ${X.id} starting with queues: ${Y.join(", ")}`);for(let Z of Y)X.createQueue({name:Z,concurrency:Q?.concurrency??1,maxRetries:Q?.maxRetries??5,retryDelay:Q?.retryDelay??5000,pauseOnError:Q?.pauseOnError??!1});return L.addEventListener("message",async(Z)=>{let{type:$="job:process",jobId:U,job:_,args:V,queue:H="default"}=Z.data;switch($){case"job:cancel":let G=X.cancelJob(U,H);L.postMessage({type:"job:canceled",jobId:U,queue:H,success:G,count:G?1:0});break;case"job:cancelAll":let R=X.cancelAllJobs(H);L.postMessage({type:"jobs:canceled",queue:H,count:R});break;case"job:process":X.debug(`Worker ${X.id} received job ${_} for queue ${H}`);try{let W=z.get(_);if(!W)throw X.error(`Job class ${_} not found`),new Error(`Job class ${_} not found`);let P=new W(...V||[]);X.addJob(P,H),L.postMessage({type:"job:received",jobId:P.id,queue:H})}catch(W){X.trace({...W,...Q??{}},`Error while adding job '${_}' to queue '${H}' with worker ${X.id}`),L.postMessage({type:"job:error",jobName:_,error:W.message})}break}}),L.addEventListener("error",(Z)=>{X.trace({...Z.error,filename:Z.filename},`Worker ${X.id} error:`)}),L.addEventListener("unhandledrejection",(Z)=>{X.trace(Z,`Worker ${X.id} unhandled rejection:`)}),L.postMessage({type:"worker:ready",id:X.id,queues:Y}),X}constructor(){super();this.#L=F0(24),this.createQueue({name:this.defaultQueueName})}get id(){return this.#L}createQueue(L){if(this.queues.has(L.name))return this.debug(`Queue with name '${L.name}' already exists`),this;let Y={options:{...L,concurrency:L.concurrency||1,maxRetries:L.maxRetries||0,retryDelay:L.retryDelay||1000,pauseOnError:L.pauseOnError||!1},jobs:[],processing:0,paused:!1,draining:!1};return this.queues.set(L.name,Y),this.debug(`Created queue '${L.name}'`),this}addJob(L,Y=this.defaultQueueName){let Q=this.queues.get(Y);if(!Q)return this.error(`Queue '${Y}' does not exist`),this;if(Q.draining)return this.warning(`Queue '${Y}' is draining, job ${L.id} will not be added`),this;let X={job:L,retries:0,queueName:Y};if(Q.jobs.push(X),this.debug(`Added job ${L.id} to queue '${Y}'`),!Q.paused&&Q.processing<Q.options.concurrency)this.processNextJob(Y);return this}pause(L){if(L){let Y=this.queues.get(L);if(Y)Y.paused=!0,this.info(`Paused queue '${L}'`)}else for(let[Y]of this.queues.entries())this.pause(Y);return this}resume(L){if(L){let Y=this.queues.get(L);if(Y)Y.paused=!1,this.info(`Resumed queue '${L}'`),this.processQueueJobs(L)}else for(let[Y]of this.queues.entries())this.resume(Y);return this}drain(L){if(L){let Y=this.queues.get(L);if(Y)Y.draining=!0,this.info(`Draining queue '${L}'`)}else for(let[Y]of this.queues.entries())this.drain(Y);return this}clear(L){if(L){let Y=this.queues.get(L);if(Y){let Q=Y.jobs.length;Y.jobs=[],this.info(`Cleared ${Q} jobs from queue '${L}'`)}}else for(let[Y,Q]of this.queues.entries()){let X=Q.jobs.length;Q.jobs=[],this.info(`Cleared ${X} jobs from queue '${Y}'`)}return this}size(L=this.defaultQueueName){let Y=this.queues.get(L);if(!Y)throw new Error(`Queue '${L}' does not exist`);return Y.jobs.length}totalSize(){let L=0;for(let Y of this.queues.values())L+=Y.jobs.length;return L}async processNextJob(L){let Y=this.queues.get(L);if(!Y||Y.paused||Y.processing>=Y.options.concurrency)return;let Q=Y.jobs.shift();if(!Q)return;if(Q.job.status==="cancelled"){this.info(`Skipping cancelled job ${Q.job.id}`),Y.processing--,this.processQueueJobs(L);return}Y.processing++;try{if(this.debug(`Processing job ${Q.job.id} from queue '${L}'`),await Q.job.run(),Q.job.status==="failed"){if(Q.retries<Y.options.maxRetries)Q.retries++,this.warning(`Job ${Q.job.id} failed, retrying (${Q.retries}/${Y.options.maxRetries})`),setTimeout(()=>{if(Q.job.status!=="cancelled")Y.jobs.push(Q),this.processQueueJobs(L);else this.info(`Skipping cancelled job ${Q.job.id} during retry delay`)},Y.options.retryDelay);else if(this.error(`Job ${Q.job.id} failed after ${Q.retries} retries`),Y.options.pauseOnError)this.pause(L),this.warning(`Queue '${L}' paused due to job failure`)}else if(Q.job.status==="completed")this.success(`Job ${Q.job.id} completed successfully`);else this.info(`Job ${Q.job.id} cancelled while running`)}catch(X){if(this.error(`Unexpected error processing job ${Q.job.id}: ${X}`),Y.options.pauseOnError)this.pause(L),this.warning(`Queue '${L}' paused due to unexpected error`)}finally{Y.processing--,this.processQueueJobs(L)}}processQueueJobs(L){let Y=this.queues.get(L);if(!Y||Y.paused)return;while(Y.jobs.length>0&&Y.processing<Y.options.concurrency)this.processNextJob(L)}getStats(){let L={};for(let[Y,Q]of this.queues.entries())L[Y]={waiting:Q.jobs.length,processing:Q.processing,paused:Q.paused,draining:Q.draining};return L}cancelJob(L,Y){if(Y)return this.cancelJobInQueue(L,Y);else{let Q=!1;for(let[X]of this.queues.entries())if(this.cancelJobInQueue(L,X)){Q=!0;break}return Q}}cancelJobInQueue(L,Y){let Q=this.queues.get(Y);if(!Q)return!1;let X=Q.jobs.findIndex((Z)=>Z.job.id===L);if(X>=0)return Q.jobs[X].job.cancel(),this.info(`Canceled job ${L} in queue '${Y}'`),!0;return!1}cancelAllJobs(L){let Y=0;if(L){let Q=this.queues.get(L);if(Q)Y=Q.jobs.length,Q.jobs.forEach((X)=>{X.job.cancel()}),this.info(`Canceled ${Y} jobs in queue '${L}'`)}else for(let[Q,X]of this.queues.entries()){let Z=X.jobs.length;X.jobs.forEach(($)=>{$.job.cancel()}),Y+=Z,this.info(`Canceled ${Z} jobs in queue '${Q}'`)}return Y}};R2=class R2 extends k{workers=[];currentWorkerIndex=0;queueWorkerMap=new Map;static instance=new R2;constructor(){super()}async init(){}async addWorker(L=[]){let Y;if(ELYSIUM_BUILD)Y=new p2("./index.js",{argv:["work",...L.map((Q)=>`--queue=${Q}`)]});else{let Q=await Array.fromAsync(new Bun.Glob("./src/**/*.job.ts").scan());Y=new p2("./index.ts",{preload:Q,argv:["work",...L.map((X)=>`--queue=${X}`)]})}Y.addEventListener("error",(Q)=>{this.trace({message:"An error occurred inside a worker process",stack:Q.message,name:"WorkerError"}),this.removeWorker(Y),this.addWorker(L)}),Y.addEventListener("messageerror",(Q)=>{this.error(`Worker message error: ${Q}`)}),Y.addEventListener("message",(Q)=>{if(Q.data.type==="worker:ready")this.debug(`Worker ${Q.data.id} ready with queues: ${Q.data.queues.join(", ")}`);else if(Q.data.type==="job:received")this.debug(`Job ${Q.data.jobId} received by worker for queue ${Q.data.queue}`);else if(Q.data.type==="job:error")this.error(`Error processing job ${Q.data.jobName}: ${Q.data.error}`);else this.debug(`Worker message: ${JSON.stringify(Q.data)}`)}),this.workers.push(Y);for(let Q of L){if(!this.queueWorkerMap.has(Q))this.queueWorkerMap.set(Q,[]);this.queueWorkerMap.get(Q).push(Y)}}removeWorker(L){let Y=L??this.workers.pop();if(!Y)return;Y.terminate();for(let[Q,X]of this.queueWorkerMap.entries())this.queueWorkerMap.set(Q,X.filter((Z)=>Z!==Y));if(L)this.workers=this.workers.filter((Q)=>Q!==Y)}terminate(){while(this.workers.length>0)this.removeWorker();this.queueWorkerMap.clear()}runJob(L,...Y){if(!Reflect.hasMetadata(O.job,L))throw new Error(`Job ${L.name} is not marked with @job() decorator`);let{name:Q,queue:X="default"}=Reflect.getMetadata(O.job,L),Z=this.queueWorkerMap.get(X)||this.workers;if(Z.length===0)throw new Error(`No workers available for queue '${X}'`);let $=this.currentWorkerIndex%Z.length;Z[$].postMessage({job:Q,args:Y,queue:X}),this.currentWorkerIndex=(this.currentWorkerIndex+1)%this.workers.length}cancelJob(L,Y){for(let Q of this.workers)Q.postMessage({type:"job:cancel",jobId:L,queue:Y});return this.workers.length>0}cancelAllJobs(L){for(let Y of this.workers)Y.postMessage({type:"job:cancelAll",queue:L});return this.workers.length>0}}});global.ELYSIUM_BUILD=typeof ELYSIUM_BUILD!=="undefined";import{t as vY}from"elysia";e();import{AsyncLocalStorage as E0}from"async_hooks";import{parseArgs as I0}from"util";import{swagger as T0}from"@elysiajs/swagger";import{Value as _2}from"@sinclair/typebox/value";import{Elysia as x0}from"elysia";import{first as f0}from"radash";import{getTableName as q2,is as h2,Table as b2}from"drizzle-orm";import{drizzle as V0}from"drizzle-orm/bun-sql";import{Cache as M0}from"drizzle-orm/cache/core";import{createCache as S2}from"cache-manager";import{KeyvCacheableMemory as z0}from"cacheable";import{Keyv as C2}from"keyv";import{alphabetical as B0}from"radash";import{EventEmitter as R0}from"events";import{omit as W0}from"radash";import{EventEmitter as H0}from"events";import{isString as w2}from"radash";class q extends H0{static instance=new q;constructor(){super();this.on("error",(L)=>this.emitError(L))}emitError(L){this.emit("elysium:error",{data:L,source:null})}emitEvent(L,Y,Q=null){this.emit(L,{data:Y,source:Q})}}var f;((m)=>{m.emit=(U,_,V=null)=>{q.instance.emitEvent(U,_,V)};function Y(U,_){if(w2(U))q.instance.on(U,_);else return function(V,H,G){let R=async function(P){try{await G.value(P)}catch(K){q.instance.emitError(K)}};if(U.prepend??!1)q.instance.prependListener(U.event,R);else q.instance.on(U.event,R)}}m.on=Y;function Q(U,_){if(w2(U))q.instance.once(U,_);else return function(V,H,G){let R=async function(P){try{await G.value(P)}catch(K){q.instance.emitError(K)}};if(U.prepend??!1)q.instance.prependOnceListener(U.event,R);else q.instance.once(U.event,R)}}m.once=Q,m.off=(U)=>{q.instance.removeAllListeners(U)},m.clear=()=>{q.instance.removeAllListeners()},m.listen=(U)=>{if(U.mode==="on")return Y(U);else if(U.mode==="once")return Q(U);return function(_,V,H){console.error("Unknown mode provided to @listen. Use either 'on' or 'once'.")}}})(f||={});d();class J2 extends R0{#L;#Y;#Q="::";#X=1000;#Z=!0;#$=!1;#U;constructor(L){super();f.once("elysium:app:launched",()=>{this.#L=r.getConnection(L.connection)}),this.#U=L.connection,this.#Y=L.namespace,this.#Q=L.keyPrefixSeparator??"::",this.#X=L.clearBatchSize??1000,this.#Z=L.useUnlink??!0,this.#$=L.noNamespaceAffectsAll??!1,this.on("error",(Y)=>{f.emit("elysium:error",Y)})}get client(){return this.#L}get opts(){return{namespace:this.#Y,keyPrefixSeparator:this.#Q,clearBatchSize:this.#X,noNamespaceAffectsAll:this.#$,dialect:"redis",url:this.#U}}get namespace(){return this.#Y}set namespace(L){this.#Y=L}async get(L){L=this.createKeyPrefix(L,this.#Y);let Y=await this.client.get(L);return Y===null?void 0:Y}async set(L,Y,Q){if(L=this.createKeyPrefix(L,this.#Y),Q)await this.client.set(L,Y,"PX",Q);else await this.client.set(L,Y)}async setMany(L){let Y=[];for(let{key:Q,value:X,ttl:Z}of L){let $=this.createKeyPrefix(Q,this.#Y);if(Z)Y.push(this.client.set($,X,"PX",Z));else Y.push(this.client.set($,X))}await Promise.all(Y)}async delete(L){return L=this.createKeyPrefix(L,this.#Y),await(this.#Z?this.client.send("UNLINK",[L]):this.client.del(L))>0}async clear(){try{if(!this.#Y&&this.#$){await this.client.send("FLUSHDB",[]);return}let L="0",Y=this.#X,Q=this.#Y?`${this.#Y}${this.#Q}*`:"*",X=[];do{let Z=await this.client.send("SCAN",[L,"MATCH",Q,"COUNT",Y.toString(),"TYPE","string"]),[$,U]=Z;if(L=$.toString(),U.length===0)continue;if(!this.#Y)U=U.filter((_)=>!_.includes(this.#Q));X.push(U.map((_)=>this.client.del(_)))}while(L!=="0");await Promise.all(X)}catch(L){this.emit("error",L)}}async has(L){return L=this.createKeyPrefix(L,this.#Y),this.client.exists(L)}async hasMany(L){let Y=[];for(let Q of L){let X=this.createKeyPrefix(Q,this.#Y);Y.push(this.client.exists(X))}return Promise.all(Y)}async getMany(L){if(L.length===0)return[];return L=L.map((Q)=>this.createKeyPrefix(Q,this.#Y)),await this.client.mget(...L)}async disconnect(){this.client.close()}async deleteMany(L){let Y=!1,Q=[];for(let Z of L){let $=this.createKeyPrefix(Z,this.#Y);if(this.#Z)Q.push(this.client.send("UNLINK",[$]));else Q.push(this.client.del($))}let X=await Promise.all(Q);for(let Z of X)if(typeof Z==="number"&&Z>0)Y=!0;return Y}async*iterator(L){let Y=L?`${L}${this.#Q}*`:"*",Q="0";do{let X=await this.client.send("SCAN",[Q,"MATCH",Y,"TYPE","string"]),[Z,$]=X;if(Q=Z.toString(),!L&&!this.#$)$=$.filter((U)=>!U.includes(this.#Q));if($.length>0){let U=await this.client.mget(...$);for(let _ of $.keys()){let V=this.getKeyWithoutPrefix($[_],L),H=U[_];yield[V,H]}}}while(Q!=="0")}createKeyPrefix(L,Y){return Y?`${Y}${this.#Q}${L}`:L}getKeyWithoutPrefix(L,Y){return Y?L.replace(`${Y}${this.#Q}`,""):L}}var r;((h)=>{let L=(U)=>{return`redis.connection.${U}`};h.getConnection=(U)=>{if(!z.exists(L(U)))console.error(`No Redis connection with name ${U} found. Please make sure to register the connection before using it.`),process.exit(1);return z.get(L(U))},h.registerConnection=(U,_)=>{if(z.exists(L(U)))console.error(`A Redis connection with the name ${U} has already been registered.`),process.exit(1);return z.instance(L(U),new Bun.RedisClient(_.url,W0(_,["url"])))},h.connectionExists=(U)=>{return z.exists(L(U))},h.getDefaultConnection=()=>{return h.getConnection("default")},h.setDefaultConnection=(U)=>{let _=L("default");return z.remove(_),z.instance(_,h.getConnection(U))}})(r||={});var k2=(L)=>{let Y=S2({stores:[new C2({store:L,namespace:"cache"})]}),Q=new Map;return{...Y,tags(...X){let Z=`cache__${B0(X,(U)=>U).join("__")}`,$=Q.get(Z);if(!$)$=S2({stores:[new C2({store:L,namespace:Z})]}),Q.set(Z,$);return $}}};class p{static#L;static#Y;static weak=Object.seal({map:new WeakMap,get(L){if(!this.map.has(L))this.map.set(L,{});return this.map.get(L)},del(L){this.map.delete(L)}});static get redis(){if(!p.#L)p.#L=k2(new J2({connection:"cache"}));return p.#L}static get memory(){if(!p.#Y)p.#Y=k2(new z0({ttl:60000,lruSize:5000}));return p.#Y}}d();class A2 extends M0{cacheStrategy;globalTtl;#L;usedTablesPerKey={};constructor(L="explicit",Y=1,Q="redis"){super();this.cacheStrategy=L;this.globalTtl=Y;this.#L=p[Q].tags("database")}strategy(){return this.cacheStrategy}async get(L){return await this.#L.get(L)??void 0}async put(L,Y,Q,X,Z){await this.#L.set(L,Y,(Z?.ex??this.globalTtl)*1000);for(let $ of Q){let U=this.usedTablesPerKey[$];if(U===void 0)this.usedTablesPerKey[$]=[L];else U.push(L)}}async onMutate(L){let Y=L.tags?Array.isArray(L.tags)?L.tags:[L.tags]:[],Q=L.tables?Array.isArray(L.tables)?L.tables:[L.tables]:[],X=new Set;for(let Z of Q){let $=h2(Z,b2)?q2(Z):Z,U=this.usedTablesPerKey[$]??[];for(let _ of U)X.add(_)}if(X.size>0||Y.length>0){await this.#L.mdel(Y),await this.#L.mdel([...X]);for(let Z of Q){let $=h2(Z,b2)?q2(Z):Z;this.usedTablesPerKey[$]=[]}}}}var l;((b)=>{let L=(U)=>{return`db.connection.${U}`};b.getConnection=(U)=>{if(!z.exists(L(U)))console.error(`No connection with name ${U} found. Please make sure to register the connection before using it.`),process.exit(1);return z.get(L(U))},b.registerConnection=(U,_)=>{if(z.exists(L(U)))console.error(`A connection with the name ${U} has already been registered.`),process.exit(1);return z.instance(L(U),V0({..._,cache:_.cache===void 0?void 0:_.cache===!0?new A2:_.cache.enabled?new A2(_.cache.strategy,_.cache.ttl,_.cache.storage):void 0}))},b.connectionExists=(U)=>{return z.exists(L(U))},b.getDefaultConnection=()=>{return b.getConnection("default")},b.setDefaultConnection=(U)=>{let _=L("default");return z.remove(_),z.instance(_,b.getConnection(U))}})(l||={});var P2=new Map,K2=(L)=>{for(let[Y,Q]of Object.entries(L))P2.set(Y,Q)},v2;((Y2)=>(Y2.get=(X,Z)=>{return P2.get(X)??Z},Y2.exists=(X)=>{return P2.has(X)},Y2.clear=()=>{P2.clear()}))(v2||={});d();g();var u=(L,Y,Q)=>{return N.context.run(new Map([["tenant",Y.tenant],["http:context",Y]]),async()=>{for(let X of L)try{let Z=await X[Q](Y);if(Z!==void 0)return Z}catch(Z){throw Z}})},Q2=(L,Y)=>{let Q=L.map((X)=>z.make(X));Y.onRequest((X)=>{return u(Q,X,"onRequest")}),Y.onTransform((X)=>{return u(Q,X,"onTransform")}),Y.onBeforeHandle((X)=>{return u(Q,X,"onBeforeHandle")}),Y.onAfterHandle((X)=>{return u(Q,X,"onAfterHandle")}),Y.onAfterResponse((X)=>{return u(Q,X,"onAfterResponse")})};class y2{static register(...L){return function(Y,Q,X){if(Q===void 0&&X===void 0){let Z=Reflect.getMetadata(O.middlewares,Y)??[];Z.push(...L),Reflect.defineMetadata(O.middlewares,Z,Y)}else{let Z=Reflect.getMetadata(O.middlewares,Y,Q)??[];Z.push(...L),Reflect.defineMetadata(O.middlewares,Z,Y,Q)}}}static guards(L){class Y extends this{}return Reflect.defineMetadata(O.middlewareGuards,L,Y),Y}get guards(){return Reflect.getMetadata(O.middlewareGuards,this.constructor)??[]}onRequest(L){}onTransform(L){}onAfterHandle(L){}onBeforeHandle(L){}onAfterResponse(L){}}d();g();import{Elysia as D0}from"elysia";import{omit as J0}from"radash";import A0 from"wampy";d();g();class g2 extends WebSocket{protocols;constructor(L,Y){super(L,Y);this.protocols=Y}get protocol(){return this.protocols?.[0]??"wamp.2.json"}}var t;((w)=>{let L=(H)=>{return`wamp.connection.${H}`};w.getConnection=(H)=>{if(!z.exists(L(H)))console.error(`No WAMP connection with name ${H} found. Please make sure to register the connection before using it.`),process.exit(1);return z.get(L(H))},w.registerConnection=(H,G)=>{if(z.exists(L(H)))console.error(`A WAMP connection with name ${H} already exists. Please ensure to register a new connection before overwriting it.`),process.exit(1);let R=new A0(G.url,{ws:g2,...J0(G,["url"]),onError(){G.onError?.(),f.emit("elysium:error",new Error(`An error occurred in WAMP connection ${H}`))}}),W=G.maxRetries??5,P=G.retryInterval??5000,K=0,C=async()=>{try{await R.connect()}catch(y){if(console.error(`Failed to connect to WAMP server (attempt ${K+1}/${W}):`,y),K<W)K++,setTimeout(C,P);else console.error(`Max retry attempts (${W}) reached. Giving up.`),f.emit("elysium:error",new Error(`Failed to establish WAMP connection ${H} after ${W} attempts`))}};return C(),z.instance(L(H),R)},w.connectionExists=(H)=>{return z.exists(L(H))},w.getDefaultConnection=()=>{return w.getConnection("default")},w.setDefaultConnection=(H)=>{let G=L("default");return z.remove(G),z.instance(G,w.getConnection(H))},w.controller=(H)=>{return function(G){async function R(){console.log(`Registering Wamp controller for connection ${H.connection} using ${G.name}`),await n();let W=z.make(G),P=Reflect.getMetadata(O.wamp,G)??{},K=t.getConnection(H.connection??"default"),C=new D0;return C.onStart(async(y)=>{let B=P.registrations??[],D=P.subscriptions??[];for(let M of B)K.register(M.topic,M.handler.bind(W),M.options).then((I)=>{console.log(`Registered ${M.topic} with id ${I.registrationId}`)});for(let M of D)K.subscribe(M.topic,M.handler.bind(W),M.options).then((I)=>{console.log(`Subscribed ${M.topic} with id ${I.subscriptionId}`)})}),C}Reflect.defineMetadata(O.elysiaPlugin,R,G)}},w.register=(H,G)=>{return function(R,W,P){let K=Reflect.getMetadata(O.wamp,R.constructor)??{};K.registrations??=[],K.registrations.push({topic:H,options:G,handler:P.value}),Reflect.defineMetadata(O.wamp,K,R.constructor)}},w.subscribe=(H,G)=>{return function(R,W,P){let K=Reflect.getMetadata(O.wamp,R.constructor)??{};K.subscriptions??=[],K.subscriptions.push({topic:H,options:G,handler:P.value}),Reflect.defineMetadata(O.wamp,K,R.constructor)}}})(t||={});class N extends k{#L;#Y;_appContextStorage=new E0;static get instance(){return z.get("elysium.app")}static get context(){return N.instance._appContextStorage}static register(L={}){return function(Y){let Q,X=Object.getPrototypeOf(Y);while(X&&X!==Object.prototype){let $=Reflect.getMetadata(O.app,X);if($){Q=$;break}X=Object.getPrototypeOf(X)}if(Q)L=o(Q,L);let Z=Reflect.getMetadata(O.app,Y);if(Z)L=o(Z,L);L=o({modules:[],swagger:!1},L),Reflect.defineMetadata(O.app,L,Y)}}constructor(){super();let{env:L,debug:Y}=Reflect.getMetadata(O.app,this.constructor)??{};if(this.#Y=Y??!1,L){let $=_2.Convert(L,_2.Clone(Bun.env));if(this.#Y&&!_2.Check(L,$)){let U=_2.Errors(L,$).First();this.trace(U,"Invalid environment configuration")}K2(_2.Clean(L,$))}else K2(Bun.env);z.instance("elysium.app",this);let{database:Q,redis:X,wamp:Z}=Reflect.getMetadata(O.app,this.constructor);if(X){for(let $ in X.connections)r.registerConnection($,X.connections[$]);if(r.connectionExists(X.default))r.setDefaultConnection(X.default)}if(Q){for(let $ in Q.connections)l.registerConnection($,Q.connections[$]);if(l.connectionExists(Q.default))l.setDefaultConnection(Q.default)}if(Z){for(let $ in Z.connections)t.registerConnection($,Z.connections[$]);if(t.connectionExists(Z.default))t.setDefaultConnection(Z.default)}this.run().then(()=>f.emit("elysium:app:launched",this,this)).catch(($)=>{f.emit("elysium:error",$),this.trace($,"An error occurred while launching the application"),process.exit(1)})}get elysia(){return this.#L}get isDebug(){return this.#Y}set isDebug(L){this.#Y=L}async onError(L){return!0}async onStart(L){}async onStop(L){}async run(){let L=process.argv.slice(2),Y=L[0];if(!Y)this.commandDescribe();else{let{commands:Q}=Reflect.getMetadata(O.app,this.constructor);switch(Y){case"serve":return this.commandServe();case"work":return this.commandWork(L.slice(1));case"help":{let X=L[1];if(X){let Z=Q?.find(($)=>$.command===X);if(Z){let $=z.make(Z);return this.write(await $.help()),process.exit(0)}console.error(`Command <${X}> not found.`)}else console.error("No command provided. Usage: styx help <command>");this.commandList();break}case"list":{this.write(this.bold("Available commands:")),this.commandList();break}default:{let X=L.slice(1);return this.commandExec(Y,X)}}}return process.exit(0)}getConfig(L){return Reflect.getMetadata(O.app,this.constructor)?.[L]??null}async commandExec(L,Y){let{commands:Q}=Reflect.getMetadata(O.app,this.constructor),X=Q?.find((Z)=>Z.command===L);if(!X)return console.error(`Command ${L} not found`),this.commandList(),process.exit(1);try{let Z=z.make(X);if(await Z.init(...Y))await Z.run();else{let U=await Z.help();this.write(U)}return process.exit(0)}catch(Z){return console.error(Z.message),process.exit(1)}}async commandWork(L){this.info("Starting worker process...");let{values:Y}=I0({args:L,options:{queue:{type:"string",multiple:!0,default:["default"],short:"q"},concurrency:{type:"string",default:"1",short:"c"},["max-retries"]:{type:"string",default:"5",short:"r"},["retry-delay"]:{type:"string",default:"5000",short:"d"},["pause-on-error"]:{type:"boolean",default:!1,short:"p"}}}),{Worker:Q}=await Promise.resolve().then(() => (E2(),l2)),X=Y.queue.map(($)=>$.split(",")).reduce(($,U)=>$.concat(U),[]),Z=Q.spawn(self,X,{concurrency:parseInt(Y.concurrency,10),maxRetries:parseInt(Y["max-retries"],10),retryDelay:parseInt(Y["retry-delay"],10),pauseOnError:Y["pause-on-error"]});this.success(`Worker process ${this.format(Z.id,2)} started with queues: ${X.map(($)=>this.format($,6)).join(", ")}`)}async commandServe(){let{server:L,modules:Y,swagger:Q,plugins:X}=Reflect.getMetadata(O.app,this.constructor);if(this.#L=new x0(L).onRequest(($)=>{if(this.isDebug)console.log($.request.method,$.request.url)}),f.emit("elysium:server:before-init",this,this),this.#L.resolve({as:"global"},({request:$})=>({tenant:$.headers.get("x-tenant-id")??"public"})),Q)this.#L.use(T0(Q));if(X&&X.length>0){this.debug("Registering plugins...");for(let $ of X)this.#L.use(await $(this))}this.#L.onError({as:"global"},async($)=>{if(await this.onError($)){f.emit("elysium:error",$),this.trace({name:"HttpError",message:"Unexpected error while handling HTTP request",stack:$.error.stack,...$.error});let U={};if(typeof $.code==="number")return $.error.response;else switch($.code){case"VALIDATION":{U={scope:$.error.type,code:$.error.message};break}case"INTERNAL_SERVER_ERROR":{U={message:$.error.message};break}}return{type:$.code,data:U}}}).onStart(async($)=>{await this.onStart($),f.emit("elysium:server:start",$,this)}).onStop(async($)=>{await this.onStop($),f.emit("elysium:server:stop",$,this),this._appContextStorage.disable()});let Z=Reflect.getMetadata(O.middlewares,this.constructor)??[];Q2(Z,this.#L);for(let $ of Y){let U=Reflect.getMetadata(O.elysiaPlugin,$);if(U===void 0)return console.error(`Invalid module class ${$.name} registered in app ${this.constructor.name}. Ensure that you used the @module() decorator on the module.`),process.exit(1);let _=z.bind($);await _.beforeRegister(),this.#L.use(await U(_)),await _.afterRegister()}f.emit("elysium:server:after-init",this,this),this.#L.listen(L?.port??(parseInt(process.env.PORT,10)||3000)),process.on("SIGINT",()=>{this.#L.stop().then(()=>process.exit(0))})}commandDescribe(){this.section(`${this.bold("Usage:")} ${this.format("styx",5)} <command> [options]`),this.section(this.bold("Core Commands:")),this.newLine(),this.commandDescription("serve","","Starts the server."),this.commandDescription("help","<command>","Displays help for a command."),this.commandDescription("list","","List all available application commands."),this.section(this.bold("Application Commands:")),this.commandList()}commandList(){let{commands:L}=Reflect.getMetadata(O.app,this.constructor),Y=(L??[]).reduce((Q,X)=>{let Z=f0(X.command.split(":")),$=Q.get(Z)??[];return $.push(X),Q.set(Z,$),Q},new Map);for(let[Q,X]of Y){this.section(this.format(Q,4));for(let Z of X)this.commandDescription(Z.command,"",Z.description)}}commandDescription(L,Y,Q,X=k.SPACE_WIDTH){Y=Y.length===0?" ":` ${Y} `,this.write(` ${this.format(L,6)}${Y}${"\u2219".repeat(X-L.length-Y.length)} ${Q}`)}}e();g();import{isArray as w0,trim as N0}from"radash";var u2;(($)=>{$.STRING="string";$.NUMBER="number";$.BOOLEAN="boolean";$.ENUM="enum";$.ARRAY="array"})(u2||={});class i2 extends k{static command="command";static description="Command description";static arg(L={}){return function(Y,Q){let X=Reflect.getMetadata(O.arg,Y.constructor)??[],Z=Reflect.getMetadata("design:type",Y,Q),$=L.type;if(!$&&Z){if(Z===Array){if($="array",!L.arrayType)L={...L,arrayType:"string"}}else if(Z.constructor!==Object)switch(Z.name.toLowerCase()){case"number":$="number";break;case"boolean":$="boolean";break;case"string":$="string";break;default:$=void 0}else if(Object.values(Z).length>0){if($="enum",!L.enum)L={...L,enum:Object.values(Z)}}}X.push({name:L.name??Q,description:L.description,required:L.required??!1,default:L.default,type:$,enum:L.enum,arrayType:L.arrayType,propertyKey:Q}),Reflect.defineMetadata(O.arg,X,Y.constructor)}}async init(...L){let Y=this.processArgs(L),Q=this.validateArgs(Y);if(!Q.valid){if(Q.missing.length>0)console.error(`Missing required arguments: ${Q.missing.join(", ")}
9
+ `);return!1}if(Object.keys(Y).includes("help"))return!1;let X=this.getArguments();for(let Z of X)if(Y[Z.name]!==void 0)this[Z.propertyKey]=Y[Z.name];return!0}getArguments(){return Reflect.getMetadata(O.arg,this.constructor)||[]}async help(){let L=`${this.bold("Command:")} ${this.format(this.constructor.command,5)}
10
+ `;L+=`${this.bold("Description:")} ${this.constructor.description}
11
+
12
+ `;let Y=this.getArguments();if(Y.length>0){L+=`${this.bold("Arguments:")}
13
+ `;for(let Q of Y){let X=this.format(Q.required?"(required)":"(optional)",1,9),Z=Q.default!==void 0?this.format(`[default: ${Q.default}]`,8,11):"",$="";if(Q.type==="array")$=`<array of ${Q.arrayType||"string"}s>`;else if(Q.type)$=`<${Q.type}>`;let U=Q.enum?` [${Q.enum.join("|")}]`:"";if(L+=` ${this.format(`--${Q.name}`,6)} ${$}${U} ${X} ${Z}
14
+ `,Q.description)L+=` ${Q.description}
15
+
16
+ `}}else L+=`This command has no arguments.
17
+ `;return N0(L,`
18
+ `)}validateArgs(L){let Y=[],Q=[],X=this.getArguments();if(Object.keys(L).includes("help"))return{valid:!0,missing:[]};for(let Z of X){if(Z.required&&(L[Z.name]===void 0||L[Z.name]===null)){Y.push(Z.name);continue}if(L[Z.name]===void 0)continue;if(Z.type==="enum"&&Z.enum&&!Z.enum.includes(L[Z.name]))Q.push(`${Z.name} (must be one of: ${Z.enum.join(", ")})`);if(Z.type==="array"&&Z.arrayType==="enum"&&Z.enum){let $=L[Z.name].filter((U)=>!Z.enum.includes(U));if($.length>0)Q.push(`${Z.name} (contains invalid values: ${$.join(", ")}. Must be one of: ${Z.enum.join(", ")})`)}}if(Q.length>0)console.error(`Invalid argument values: ${Q.join(", ")}
19
+ `);return{valid:Y.length===0&&Q.length===0,missing:Y}}processArgs(L){let Y={},Q=this.getArguments();for(let X=0;X<L.length;X++){let Z=L[X];if(Z.startsWith("--")){let $=Z.slice(2);if(X+1<L.length&&!L[X+1].startsWith("--"))Y[$]=L[X+1],X++;else Y[$]=!0}}for(let X of Q){if(Y[X.name]===void 0&&X.default!==void 0){Y[X.name]=X.default;continue}if(Y[X.name]===void 0)continue;if(typeof Y[X.name]==="string")switch(X.type||this.inferType(X.default)){case"number":Y[X.name]=Number(Y[X.name]);break;case"boolean":let $=Y[X.name].toLowerCase();Y[X.name]=$==="true"||$==="1"||$==="yes";break;case"enum":if(X.enum&&X.enum.length>0&&typeof X.enum[0]==="number")Y[X.name]=Number(Y[X.name]);break;case"array":let U=Y[X.name].split(",").map((_)=>_.trim());if(X.arrayType)Y[X.name]=U.map((_)=>{switch(X.arrayType){case"number":return Number(_);case"boolean":return _.toLowerCase()==="true"||_.toLowerCase()==="1"||_.toLowerCase()==="yes";case"enum":return _;default:return _}});else Y[X.name]=U;break;case"string":default:break}}return Y}progress(L,Y="Processing"){return new c2(L,Y)}spinner(L="Processing",Y,Q){return new m2(L,Y,Q)}inferType(L){if(L===void 0)return"string";switch(typeof L){case"number":return"number";case"boolean":return"boolean";default:return w0(L)?"array":"string"}}}class c2 extends k{#L=!1;#Y=0;#Q=0;#X="";#Z=0;constructor(L=0,Y="Processing"){super();this.#Y=L,this.#X=Y,this.#L=!0,this.#Q=0,this.#Z=Date.now(),this.update(0)}update(L=1,Y){if(!this.#L)return;if(this.#Q+=L,Y)this.#X=Y;let Q=Math.min(100,Math.floor(this.#Q/this.#Y*100)),Z=(Date.now()-this.#Z)/1000,$=0,U=0,_="";if(this.#Q>0)$=Z/this.#Q*this.#Y,U=Math.max(0,$-Z),_=` | ${this.formatTime(Z)} elapsed | ${this.formatTime(U)} remaining`;let V=30,H=Math.floor(Q/100*V),G=V-H,R="["+"=".repeat(H)+(G>0?">":"")+" ".repeat(Math.max(0,G-(G>0?1:0)))+"]",W=`${this.#X}: ${R} ${Q}% (${this.#Q}/${this.#Y})${_}`;if(this.clearLine(),this.write(W,!1),this.#Q>=this.#Y)this.complete()}complete(L){if(!this.#L)return;this.#Q=this.#Y;let Q=(Date.now()-this.#Z)/1000;if(this.clearLine(),L)this.write(`${L} (completed in ${this.formatTime(Q)})`);else this.write(`${this.#X} completed in ${this.formatTime(Q)}`);this.#L=!1}pause(L){if(!this.#L)return;this.newLine(),this.write(L),this.update(0)}isActive(){return this.#L}getCurrent(){return this.#Q}getTotal(){return this.#Y}getPercentage(){return Math.min(100,Math.floor(this.#Q/this.#Y*100))}}class m2 extends k{#L=!1;#Y="";#Q=0;#X=null;#Z=0;#$=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];#U=80;constructor(L="Processing",Y,Q){super();if(this.#Y=L,Y)this.#$=Y;if(Q)this.#U=Q;if(this.#L)return;this.#L=!0,this.#Q=Date.now(),this.#Z=0,this.#X=setInterval(()=>{this.render()},this.#U),this.render()}update(L){if(!this.#L)return;this.#Y=L}complete(L,Y=!0){if(!this.#L)return;if(this.#X)clearInterval(this.#X),this.#X=null;let X=(Date.now()-this.#Q)/1000;this.clearLine();let Z=this.formatTime(X);if(L)this[Y?"success":"error"](`${L} (${Z})`);else this[Y?"success":"error"](`${this.#Y} completed in ${Z}`);this.#L=!1}fail(L){this.complete(L,!1)}pause(L){if(!this.#L)return;if(this.#X)clearInterval(this.#X),this.#X=null;this.clearLine(),this.write(L),this.#X=setInterval(()=>{this.render()},this.#U)}isActive(){return this.#L}getElapsedTime(){return(Date.now()-this.#Q)/1000}render(){if(!this.#L)return;let L=this.getElapsedTime(),Y=this.#$[this.#Z];this.#Z=(this.#Z+1)%this.#$.length,this.clearLine(),this.write(`${Y} ${this.#Y} (${this.formatTime(L)})`,!1)}}e();import{Elysia as S0,sse as C0,t as n2}from"elysia";import{assign as k0,isEmpty as W2,objectify as q0}from"radash";d();g();var h0=(L)=>{let Y=Reflect.getMetadata("http:body",L.target,L.propertyKey),Q=Reflect.getMetadata("http:params",L.target,L.propertyKey)??[],X=Reflect.getMetadata("http:query",L.target,L.propertyKey),Z=Reflect.getMetadata("http:rawContext",L.target,L.propertyKey),$=Reflect.getMetadata("http:customDecorators",L.target,L.propertyKey)??[],U=Reflect.getMetadata(O.middlewares,L.target,L.propertyKey)??[],_=Reflect.getMetadata(O.services,L.target,L.propertyKey)??[],{path:V,method:H,handler:G,target:R,response:W,operationId:P,description:K,transactional:C}=L,y=Reflect.getMetadata(O.http,R.constructor)??[];y.push({path:V,method:H,body:Y,params:Q,query:X,customDecorators:$,rawContext:Z,handler:G,middlewares:U,response:W,operationId:P,description:K,services:_,transactional:C}),Reflect.defineMetadata(O.http,y,R.constructor)},s2;((Q)=>{Q[Q.SERVER=0]="SERVER";Q[Q.REQUEST=1]="REQUEST"})(s2||={});var o2;((J)=>(J.controller=(B={path:"/"})=>{return function(D){async function M(){console.log(`Registering HTTP controller for ${B.path} using ${D.name}`),await n(),B=k0({path:"/",scope:0,tags:[]},B);let I=new S0({prefix:B.path,name:D.name}),i=(()=>{if(B.scope===0)return()=>{let A=z.make(D);return()=>A};else if(B.scope===1)return()=>()=>z.make(D);else throw new Error(`Invalid scope for controller: ${D.name}`)})();I.resolve({as:"local"},()=>({controller:i()}));let X2=Reflect.getMetadata("http:onRequest",D)??{};if(X2.handler)I.onRequest((A)=>{let a=i()();return X2.handler.call(a,A)});let e2=Reflect.getMetadata(O.middlewares,D)??[];Q2(e2,I);let L0=Reflect.getMetadata(O.http,D)??[];for(let A of L0){let a=async(F)=>{let j=[];if(A.rawContext)j[A.rawContext.index]=F;if(A.body)j[A.body.index]=F.body;if(A.query)j[A.query.index]=F.query;if(!W2(A.params))for(let x of A.params)j[x.index]=F.params[x.slug];if(!W2(A.customDecorators))for(let x of A.customDecorators)j[x.index]=await x.handler(F);if(!W2(A.services))for(let x of A.services)j[x.index]=z.get(x.name);return j},Y0=A.handler.constructor.name.includes("GeneratorFunction"),x2=A.method==="elysium:SSE",Q0=A.transactional??B.transactional??!1,M2=A.body&&A.body.schema===void 0&&A.body.validator!==void 0;A.method=x2?"GET":A.method;let X0=()=>{let F=(j)=>{if(Q0)return function(...x){return l.getDefaultConnection().transaction((H2)=>{return N.context.run(new Map([["tenant",j.tenant],["http:context",j],["db:tx",H2]]),()=>{try{return A.handler.call(j.controller(),...x)}catch(Z2){throw H2.rollback(),Z2}})})};return function(...x){return N.context.run(new Map([["tenant",j.tenant],["http:context",j]]),()=>A.handler.call(j.controller(),...x))}};if(Y0)return async function*(j){let x=F(j),H2=await a(j);try{for await(let Z2 of x(...H2))yield Z2}catch(Z2){yield Z2}};if(x2)return async function*(j){let x=F(j);j.set.headers["content-type"]="text/event-stream",j.set.headers["cache-control"]="no-cache",j.set.headers.connection="keep-alive";while(!0)yield C0(await x(...await a(j))),await Bun.sleep(10)};if(M2)return async function(j){if(await A.body.validator.validate(j))return await F(j)(...await a(j));throw j.status(400,"Invalid request body")};return async function(j){return await F(j)(...await a(j))}},f2=q0(A.params??[],(F)=>F.slug,(F)=>F.schema),G2=A.middlewares.map((F)=>z.make(F));I.route(A.method,A.path,X0(),{config:{},async transform(F){if(M2&&!await A.body.validator.authorize(F))throw F.status(401,"Unauthorized");return u(G2,F,"onTransform")},beforeHandle(F){return u(G2,F,"onBeforeHandle")},afterHandle(F){return u(G2,F,"onAfterHandle")},afterResponse(F){return u(G2,F,"onAfterResponse")},detail:{tags:B.tags,description:A.description,operationId:A.operationId},body:M2?A.body?.validator?.schema:A.body?.schema,response:A.response,params:W2(f2)?void 0:n2.Object(f2)})}return I}Reflect.defineMetadata(O.elysiaPlugin,M,D)}},J.sse=(B={})=>{let{path:D="/",...M}=B;return J.custom({method:"elysium:SSE",path:D,...M})},J.get=(B={})=>{let{path:D="/",...M}=B;return J.custom({method:"GET",path:D,...M})},J.post=(B={})=>{let{path:D="/",...M}=B;return J.custom({method:"POST",path:D,...M})},J.put=(B={})=>{let{path:D="/",...M}=B;return J.custom({method:"PUT",path:D,...M})},J.del=(B={})=>{let{path:D="/",...M}=B;return J.custom({method:"DELETE",path:D,...M})},J.patch=(B={})=>{let{path:D="/",...M}=B;return J.custom({method:"PATCH",path:D,...M})},J.head=(B={})=>{let{path:D="/",...M}=B??{};return J.custom({method:"HEAD",path:D,...M})},J.options=(B={})=>{let{path:D="/",...M}=B;return J.custom({method:"OPTIONS",path:D,...M})},J.trace=(B={})=>{let{path:D="/",...M}=B;return J.custom({method:"TRACE",path:D,...M})},J.custom=({path:B="/",...D})=>{return function(M,I,i){process.nextTick(()=>{h0({path:B,handler:i.value,target:M,propertyKey:I,...D})})}},J.onRequest=()=>{return function(B,D,M){let I=Reflect.getMetadata("http:onRequest",B.constructor)??{};I.handler=M.value,Reflect.defineMetadata("http:onRequest",I,B.constructor)}},J.context=()=>{return function(B,D,M){Reflect.defineMetadata("http:rawContext",{index:M},B,D)}},J.param=(B,D)=>{return function(M,I,i){let X2=Reflect.getMetadata("http:params",M,I)??[];X2.push({slug:B,schema:D??n2.String(),index:i}),Reflect.defineMetadata("http:params",X2,M,I)}},J.query=(B)=>{return function(D,M,I){Reflect.defineMetadata("http:query",{schema:B,index:I},D,M)}},J.body=(B)=>{return function(D,M,I){if(typeof B==="function")Reflect.defineMetadata("http:body",{validator:B,index:I},D,M);else Reflect.defineMetadata("http:body",{schema:B,index:I},D,M)}},J.decorate=(B)=>{return()=>{return function(D,M,I){let i=Reflect.getMetadata("http:customDecorators",D,M)??[];i.push({handler:B,index:I}),Reflect.defineMetadata("http:customDecorators",i,D,M)}}}))(o2||={});j2();import{getTableConfig as b0,pgSchema as v0,pgTable as r2}from"drizzle-orm/pg-core";import{t as S}from"elysia";var I2=(L,{mode:Y="select"}={})=>{let{columns:Q}=b0(L);if(Q===void 0)return S.Object({});let X={};for(let Z of Q){if(["create","update"].includes(Y)&&Z.primary)continue;if(X[Z.name]=y0(Z),!Z.notNull)X[Z.name]=S.Nullable(X[Z.name]);if(Y==="update"||Z.hasDefault||!Z.notNull)X[Z.name]=S.Optional(X[Z.name])}return S.Object(X)},y0=(L)=>{let Y=(()=>{switch(L.dataType){case"string":return S.String({format:L.columnType==="PgUUID"?"uuid":void 0});case"number":return S.Number();case"boolean":return S.Boolean();case"array":return S.Array(S.Any());case"json":return S.Object({});case"date":case"localDate":case"localDateTime":return S.String({format:L.dataType==="date"?"date":"date-time"});case"bigint":return S.BigInt();case"buffer":return S.File();default:return S.Never()}})();if(!L.notNull)Y=S.Optional(Y);else Y=S.Required(Y);return Y},g0=(L,Y,Q)=>{let X=r2(L,Y,Q);class Z{static $inferSelect=X.$inferSelect;static $inferInsert=X.$inferInsert;static $inferUpdate=X.$inferInsert;static get table(){if(!N.instance||!N.context.getStore)return X;if(this.supportTenancy){let $=B2.getCurrentTenant()??"public";return B2.wrapTenant($,this)}return X}static tableName=L;static columns=Y;static extraConfig=Q;static insertSchema=I2(X,{mode:"create"});static updateSchema=I2(X,{mode:"update"});static selectSchema=I2(X,{mode:"select"});static supportTenancy=!1}return Z},T2=new Map,z2=new Map,B2;((c)=>{let L=($)=>{return z2.get($)??c.registerTenant($)};c.getCurrentTenant=()=>{return N.context.getStore()?.get("tenant")??null},c.wrapTenant=($,U)=>{if($==="public")return r2(U.tableName,U.columns);let _=`${$}.${U.tableName}`;if(T2.has(_))return T2.get(_);let H=L($).table(U.tableName,U.columns);return T2.set(_,H),H},c.registerTenant=($)=>{if(z2.has($))return z2.get($);let U=v0($);return z2.set($,U),U},c.withTenant=($,U)=>{let _=N.context.getStore(),V=new Map(_);return V.set("tenant",$),N.context.run(V,U)}})(B2||={});import{Elysia as d0}from"elysia";import{assign as p0}from"radash";g();class t2{static register(L={}){return function(Y){async function Q(X){console.log(`Registering module ${Y.name}`),await n();let Z=p0({controllers:[]},L),$=new d0({name:Y.name,prefix:L.prefix});$.resolve({as:"local"},()=>({module:X}));let U=Reflect.getMetadata(O.middlewares,Y)??[];Q2(U,$);for(let _ of Z.controllers){let V=Reflect.getMetadata(O.elysiaPlugin,_);if(V===void 0)console.error(`Invalid controller class ${_.name} registered in module ${Y.name}. Ensure that you either used the @Http.controller(), the @Websocket.controller(), or the @Wamp.controller() decorators on the class.`),process.exit(1);else $.use(await V())}return $}Reflect.defineMetadata(O.elysiaPlugin,Q,Y)}}beforeRegister(){return Promise.resolve()}afterRegister(){return Promise.resolve()}}import{eq as V2}from"drizzle-orm";var l0=(L)=>{class Y{static Model=L;static connection="default";get db(){let Q=this.constructor.connection,X=null;if(Q==="default")X=N.context.getStore()?.get("db:tx")??null;return X??l.getConnection(Q)}async all(){return await this.db.select().from(L.table)}async paginate(Q,X=1){let Z=await this.db.$count(L.table),$=Math.max(X-1,0)*Q;return{page:X,total:Z,data:await this.db.select().from(L.table).offset($).limit(Q)}}async find(Q){let[X]=await this.db.select().from(L.table).where(V2(L.table.id,Q));return X??null}async findBy(Q,X){let[Z]=await this.db.select().from(L.table).where(V2(L.table[Q],X));return Z??null}async insert(Q){let[X]=await this.db.insert(L.table).values(Q).returning();return X}async update(Q,X){let[Z]=await this.db.update(L.table).set(X).where(V2(L.table.id,Q)).returning();return Z}async updateAll(Q){return await this.db.update(L.table).set(Q).returning()}async delete(Q){let[X]=await this.db.delete(L.table).where(V2(L.table.id,Q)).returning();return X}async deleteAll(){return await this.db.delete(L.table).returning()}}return Y};d();import{Elysia as u0}from"elysia";d();g();var a2;((v)=>(v.controller=(U)=>{return function(_){async function V(){console.log(`Registering Websocket route for ${U.path} using ${_.name}`),await n();let H=z.make(_),G=Reflect.getMetadata(O.websocket,_)??{},R=G.open?.bind(H),W=G.close?.bind(H),P=G.message?.bind(H),K=G.drain?.bind(H),C=G.error?.bind(H)??((B)=>f.emit("elysium:error",B.error)),y=new u0;return y.ws(U.path,{open:R,close:W,message:P,drain:K,error:C,body:G.body,...U.options}),y}Reflect.defineMetadata(O.elysiaPlugin,V,_)}},v.onOpen=()=>{return function(U,_,V){let H=Reflect.getMetadata(O.websocket,U.constructor)??{};H.open=V.value,Reflect.defineMetadata(O.websocket,H,U.constructor)}},v.onClose=()=>{return function(U,_,V){let H=Reflect.getMetadata(O.websocket,U.constructor)??{};H.close=V.value,Reflect.defineMetadata(O.websocket,H,U.constructor)}},v.onMessage=(U)=>{return function(_,V,H){let G=Reflect.getMetadata(O.websocket,_.constructor)??{};G.message=H.value,G.body=U,Reflect.defineMetadata(O.websocket,G,_.constructor)}},v.onDrain=()=>{return function(U,_,V){let H=Reflect.getMetadata(O.websocket,U.constructor)??{};H.drain=V.value,Reflect.defineMetadata(O.websocket,H,U.constructor)}},v.onError=()=>{return function(U,_,V){let H=Reflect.getMetadata(O.websocket,U.constructor)??{};H.error=V.value,Reflect.defineMetadata(O.websocket,H,U.constructor)}}))(a2||={});E2();export{vY as t,R2 as WorkerPool,F2 as Worker,a2 as Websocket,t as Wamp,B2 as Tenancy,N2 as ServiceScope,z as Service,l0 as Repository,r as Redis,t2 as Module,g0 as Model,y2 as Middleware,d2 as Job,k as InteractsWithConsole,s2 as HttpControllerScope,o2 as Http,f as Event,v2 as Env,l as Database,O2 as ConsoleFormat,u2 as CommandArgumentType,i2 as Command,p as Cache,N as Application};
package/dist/job.d.ts ADDED
@@ -0,0 +1,105 @@
1
+ import 'reflect-metadata';
2
+ import type { Class } from 'type-fest';
3
+ import { InteractsWithConsole } from './console';
4
+ /**
5
+ * Properties required when declaring a job using the `@job()` decorator.
6
+ * @author Axel Nana <axel.nana@workbud.com>
7
+ */
8
+ export type JobProps = {
9
+ /**
10
+ * The name of the job.
11
+ */
12
+ name?: string;
13
+ /**
14
+ * The queue on which the job should be processed.
15
+ */
16
+ queue?: string;
17
+ };
18
+ /**
19
+ * Base class for background jobs.
20
+ *
21
+ * Jobs are classes that can be executed in the background. They provide
22
+ * an abstract execute method that serves as the entry point for the job.
23
+ *
24
+ * @author Axel Nana <axel.nana@workbud.com>
25
+ */
26
+ export declare abstract class Job extends InteractsWithConsole {
27
+ #private;
28
+ /**
29
+ * Marks a class as a job.
30
+ * @author Axel Nana <axel.nana@workbud.com>
31
+ * @param options The decorator options.
32
+ */
33
+ static register(options?: JobProps): (target: Class<Job>) => void;
34
+ /**
35
+ * Unique identifier for the job.
36
+ */
37
+ readonly id: string;
38
+ /**
39
+ * The timestamp when the job was created.
40
+ */
41
+ readonly createdAt: Date;
42
+ /**
43
+ * The timestamp when the job started execution.
44
+ */
45
+ get startedAt(): Date | undefined;
46
+ /**
47
+ * The timestamp when the job completed execution.
48
+ */
49
+ get completedAt(): Date | undefined;
50
+ /**
51
+ * The current status of the job.
52
+ */
53
+ get status(): JobStatus;
54
+ /**
55
+ * Creates a new job instance.
56
+ *
57
+ * @param id Optional job ID. If not provided, a random ID will be generated.
58
+ */
59
+ constructor(id?: string);
60
+ /**
61
+ * Run the job.
62
+ * This method handles the job lifecycle and calls the execute method.
63
+ */
64
+ run(): Promise<void>;
65
+ /**
66
+ * Cancels the job.
67
+ */
68
+ cancel(): void;
69
+ /**
70
+ * The main execution method for the job.
71
+ * This must be implemented by all job classes.
72
+ */
73
+ protected abstract execute(): Promise<void>;
74
+ /**
75
+ * Generate a random job ID.
76
+ * @returns A random job ID.
77
+ */
78
+ private generateJobId;
79
+ }
80
+ /**
81
+ * Possible statuses for a job.
82
+ * @author Axel Nana <axel.nana@workbud.com>
83
+ */
84
+ export declare enum JobStatus {
85
+ /**
86
+ * The job is in pending state, meaning it has been added to the queue but has not yet been processed.
87
+ */
88
+ PENDING = "pending",
89
+ /**
90
+ * The job is in running state, meaning it is currently being processed.
91
+ */
92
+ RUNNING = "running",
93
+ /**
94
+ * The job has completed successfully.
95
+ */
96
+ COMPLETED = "completed",
97
+ /**
98
+ * The job has failed to complete successfully. If there are enough retries left, the job will be restarted.
99
+ */
100
+ FAILED = "failed",
101
+ /**
102
+ * The job has been cancelled by the user or another job.
103
+ */
104
+ CANCELLED = "cancelled"
105
+ }
@@ -0,0 +1,8 @@
1
+ declare global {
2
+ /**
3
+ * A macro indicating if the code is running from a build.
4
+ * @author Axel Nana <axel.nana@workbud.com>
5
+ */
6
+ var ELYSIUM_BUILD: boolean;
7
+ }
8
+ export {};
@@ -0,0 +1,69 @@
1
+ import type { AnyElysia } from 'elysia';
2
+ import type { Class } from 'type-fest';
3
+ import type { Context } from './http';
4
+ /**
5
+ * Execute a chain of middlewares, stopping on the first return or throw.
6
+ * @author Axel Nana <axel.nana@workbud.com>
7
+ * @param middlewares The list of middleware instances to execute.
8
+ * @param context The context to pass to each middleware.
9
+ * @param method The method to call on each middleware.
10
+ */
11
+ export declare const executeMiddlewareChain: (middlewares: Middleware[], context: any, method: Exclude<keyof Middleware, "guards">) => Promise<any>;
12
+ /**
13
+ * Apply a list of middlewares to an Elysia plugin.
14
+ * @author Axel Nana <axel.nana@workbud.com>
15
+ * @param middlewares The list of middlewares to apply.
16
+ * @param plugin The Elysia plugin instance.
17
+ */
18
+ export declare const applyMiddlewares: (middlewares: Class<Middleware>[], plugin: AnyElysia) => void;
19
+ /**
20
+ * Base class for middleware.
21
+ * @author Axel Nana <axel.nana@workbud.com>
22
+ * @template TGuards The list of guards for the middleware.
23
+ */
24
+ export declare abstract class Middleware<TGuards extends string[] = []> {
25
+ /**
26
+ * Registers a list of middlewares to be applied on a controller or endpoint.
27
+ * @author Axel Nana <axel.nana@workbud.com>
28
+ * @param middlewares The list of middlewares to apply.
29
+ */
30
+ static register(...middlewares: Class<Middleware>[]): ClassDecorator & MethodDecorator;
31
+ /**
32
+ * Creates a guarded version of the middleware.
33
+ * @author Axel Nana <axel.nana@workbud.com>
34
+ * @param guards The list of guards for the middleware.
35
+ * @returns A middleware class decorated with guards.
36
+ */
37
+ static guards(guards: string[]): Class<Middleware>;
38
+ /**
39
+ * Gets the list of guards for the middleware.
40
+ */
41
+ get guards(): TGuards;
42
+ /**
43
+ * Called first before everything else. This middleware hook works only when used on
44
+ * a controller, a module, or the application.
45
+ * @param _ctx The request context.
46
+ */
47
+ onRequest(_ctx: Context): any;
48
+ /**
49
+ * Called before validation, but after the request has been parsed.
50
+ * Use this method to modify the request inputs before validation.
51
+ * @param _ctx The request context.
52
+ */
53
+ onTransform(_ctx: Context): any;
54
+ /**
55
+ * Called after the request has been handled, but before the response is sent.
56
+ * @param _ctx The request context.
57
+ */
58
+ onAfterHandle(_ctx: Context): any;
59
+ /**
60
+ * Called before the request is handled.
61
+ * @param _ctx The request context.
62
+ */
63
+ onBeforeHandle(_ctx: Context): any;
64
+ /**
65
+ * Called after the response has been sent.
66
+ * @param _ctx The request context.
67
+ */
68
+ onAfterResponse(_ctx: Context): any;
69
+ }