@elysiumjs/core 0.4.2 → 0.5.0

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,24 @@
1
+ // @bun
2
+ global.ELYSIUM_BUILD=typeof ELYSIUM_BUILD!=="undefined";import{t as F0}from"elysia";import{AsyncLocalStorage as R2}from"async_hooks";import{swagger as W2}from"@elysiajs/swagger";import{Value as UL}from"@sinclair/typebox/value";import{Elysia as P2}from"elysia";import{first as z2}from"radash";import*as WL from"readline";import{isEmpty as rL,omit as tL}from"radash";var ZL;((R)=>{R[R.BLACK=0]="BLACK";R[R.RED=1]="RED";R[R.GREEN=2]="GREEN";R[R.YELLOW=3]="YELLOW";R[R.BLUE=4]="BLUE";R[R.MAGENTA=5]="MAGENTA";R[R.CYAN=6]="CYAN";R[R.WHITE=7]="WHITE";R[R.GRAY=8]="GRAY";R[R.BOLD=9]="BOLD";R[R.UNDERLINE=10]="UNDERLINE";R[R.ITALIC=11]="ITALIC";R[R.INVERSE=12]="INVERSE"})(ZL||={});var aL={[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"};class k{static SPACE_WIDTH=60;write(L,Y=!0,U=process.stdout){U.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 U=L.name||"Error",Q=L.message||"An error occurred",X=L.stack||"";if(Y)this.title(Y);else this.newLine();if(this.write(this.format(`${U}: ${Q}`,1)),L.stack)this.write(this.format("Stack Trace:",9)),this.write(this.format(X.split(`
5
+ `).map((_)=>` ${_}`).join(`
6
+ `),8));let Z=tL(L,["name","message","stack"]);if(!rL(Z))this.write(this.format("Additional Information:",9)),Object.keys(Z).forEach((_)=>{let $=L[_];this.write(` ${_}: ${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 U=Object.keys(Y||L[0]),Q={};for(let _ of U){let $=Y?.[_];if($?.width){Q[_]=$.width;continue}let D=($?.header||String(_)).length,H=Math.max(...L.map((G)=>{let W=G[_];if($?.format)return $.format(W).length;return String(W===null||W===void 0?"":W).length}));Q[_]=Math.max(D,H)}let X="",Z="";for(let _ of U){let D=Y?.[_]?.header||String(_),H=Q[_];X+=`| ${D.padEnd(H)} `,Z+=`| ${"-".repeat(H)} `}X+="|",Z+="|",this.write(X),this.write(Z);for(let _ of L){let $="";for(let D of U){let H=Y?.[D],G=Q[D],W=_[D],P;if(H?.format)P=H.format(W);else P=String(W===null||W===void 0?"":W);$+=`| ${P.padEnd(G)} `}$+="|",this.write($)}this.newLine()}format(L,...Y){return`${Y.map((Q)=>aL[Q]).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 U=WL.createInterface({input:process.stdin,output:process.stdout}),Q=Y?` (default: ${Y})`:"";return new Promise((X)=>{U.question(`${L}${Q}: `,(Z)=>{U.close(),X(Z||Y||"")})})}async promptPassword(L){let Y=WL.createInterface({input:process.stdin,output:process.stdout});return process.stdin.setRawMode?.(!0),new Promise((U)=>{let Q="";process.stdout.write(`${L}: `),process.stdin.on("data",(X)=>{let Z=X.toString();if(Z==="\r"||Z===`
7
+ `){process.stdout.write(`
8
+ `),process.stdin.setRawMode?.(!1),process.stdin.removeAllListeners("data"),Y.close(),U(Q);return}if(Z==="\b"||Z==="\x7F"){if(Q.length>0)Q=Q.slice(0,-1),process.stdout.write("\b \b");return}Q+=Z,process.stdout.write("*")})})}async confirm(L,Y=!1){let U=Y?"Y/n":"y/N",Q=await this.prompt(`${L} [${U}]`);if(!Q)return Y;return Q.toLowerCase()==="y"||Q.toLowerCase()==="yes"}async select(L,Y,U=0){if(Y.length===0)throw new Error("No options provided for selection");this.write(L),Y.forEach((Z,_)=>{let $=_===U;this.write(` ${_+1}. ${Z}${$?" (default)":""}`)});let Q=await this.prompt("Enter your choice (number)");if(!Q)return Y[U];let X=parseInt(Q,10)-1;if(isNaN(X)||X<0||X>=Y.length)return this.warning(`Invalid selection. Using default: ${Y[U]}`),Y[U];return Y[X]}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`}}import{getTableName as TL,is as fL,Table as xL}from"drizzle-orm";import{drizzle as _2}from"drizzle-orm/bun-sql";import{Cache as $2}from"drizzle-orm/cache/core";import{createCache as EL}from"cache-manager";import{KeyvCacheableMemory as X2}from"cacheable";import{Keyv as FL}from"keyv";import{alphabetical as Z2}from"radash";import{EventEmitter as U2}from"events";import{omit as Q2}from"radash";import{EventEmitter as eL}from"events";import{isString as IL}from"radash";class h extends eL{static instance=new h;constructor(){super();this.on("error",(L)=>this.emitError(L))}emitError(L){this.emit("elysium:error",{data:L,source:null})}emitEvent(L,Y,U=null){this.emit(L,{data:Y,source:U})}}var x;((u)=>{u.emit=(_,$,D=null)=>{h.instance.emitEvent(_,$,D)};function Y(_,$){if(IL(_))h.instance.on(_,$);else return function(D,H,G){let W=async function(R){try{await G.value(R)}catch(I){h.instance.emitError(I)}};if(_.prepend??!1)h.instance.prependListener(_.event,W);else h.instance.on(_.event,W)}}u.on=Y;function U(_,$){if(IL(_))h.instance.once(_,$);else return function(D,H,G){let W=async function(R){try{await G.value(R)}catch(I){h.instance.emitError(I)}};if(_.prepend??!1)h.instance.prependOnceListener(_.event,W);else h.instance.once(_.event,W)}}u.once=U,u.off=(_)=>{h.instance.removeAllListeners(_)},u.clear=()=>{h.instance.removeAllListeners()},u.listen=(_)=>{if(_.mode==="on")return Y(_);else if(_.mode==="once")return U(_);return function($,D,H){console.error("Unknown mode provided to @listen. Use either 'on' or 'once'.")}}})(x||={});import{isString as a}from"radash";import{isObject as YL,isPrimitive as L2}from"radash";var O;((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||={});var c=()=>new Promise((L)=>process.nextTick(L));function n(L,...Y){if(!Y.length)return L;let U=Y.shift();if(U===void 0)return L;if(YL(L)&&YL(U))for(let Q in U)if(YL(U[Q])){if(!L[Q])Object.assign(L,{[Q]:U[Q]})}else if(Array.isArray(U[Q])){if(!Array.isArray(L[Q]))L[Q]=[];if(U[Q].length>0&&!YL(U[Q][0]))L[Q]=[...new Set([...L[Q],...U[Q]])];else U[Q].forEach((X,Z)=>{if(YL(X)&&L[Q][Z])L[Q][Z]=n(L[Q][Z],X);else if(!L[Q].includes(X))L[Q].push(X)})}else if(L2(U[Q]))L[Q]??=U[Q];else n(L[Q],U[Q]);return n(L,...Y)}var KL;((U)=>{U[U.SINGLETON=0]="SINGLETON";U[U.FACTORY=1]="FACTORY"})(KL||={});var Y2=(L)=>{return typeof L==="function"&&L.prototype&&L.prototype.constructor===L},m=new Map,z;((j)=>{j.register=(G)=>{return function(W){let P=G?.name??W.name,R=G?.scope??0;if(z.exists(P))console.error(`A service with the name ${P} has already been registered.`),process.exit(1);let I=()=>z.make(W);if(R===0){let C=I();m.set(P,{scope:R,factory(){return C}})}else m.set(P,{scope:R,factory:I})}},j.inject=(G)=>{return function(W,P,R){let I=Reflect.getMetadata(O.services,W,P)??[],C=Reflect.getMetadata("design:paramtypes",W,P)??[],y=a(G)?G:G?.name??C[R].name;I.push({name:y,index:R}),Reflect.defineMetadata(O.services,I,W,P)}},j.get=(G)=>{let W=a(G)?G:G.name;if(j.exists(W))return m.get(W).factory();return null},j.make=(G)=>{let W=Reflect.getMetadata(O.services,G)??[],P=[];return W.forEach((R)=>{let I=j.get(R.name);if(I===null)console.error(`Cannot inject service ${R.name}. No service was registered with the name: ${R.name}`),process.exit(1);P[R.index]=I}),new G(...P)},j.bind=(G,W)=>{let P=j.make(G);return j.instance(W??G.name,P)};function Z(G,W){let P=a(G)?G:W??G.name;if(j.exists(P))console.error(`A service with the name ${P} has already been registered.`),process.exit(1);let R=()=>{return Y2(G)?j.make(G):W()};return m.set(P,{scope:1,factory:R}),R()}j.factory=Z,j.instance=(G,W)=>{let P=a(G)?G:G.name;if(j.exists(P))console.error(`A service with the name ${P} has already been registered.`),process.exit(1);return m.set(P,{scope:0,factory(){return W}}),W},j.remove=(G)=>{let W=a(G)?G:G.name;m.delete(W)},j.exists=(G)=>{let W=a(G)?G:G.name;return m.has(W)},j.clear=()=>{m.clear()}})(z||={});class PL extends U2{#L;#Y;#U="::";#Q=1000;#X=!0;#Z=!1;#_;constructor(L){super();x.once("elysium:app:launched",()=>{this.#L=s.getConnection(L.connection)}),this.#_=L.connection,this.#Y=L.namespace,this.#U=L.keyPrefixSeparator??"::",this.#Q=L.clearBatchSize??1000,this.#X=L.useUnlink??!0,this.#Z=L.noNamespaceAffectsAll??!1,this.on("error",(Y)=>{x.emit("elysium:error",Y)})}get client(){return this.#L}get opts(){return{namespace:this.#Y,keyPrefixSeparator:this.#U,clearBatchSize:this.#Q,noNamespaceAffectsAll:this.#Z,dialect:"redis",url:this.#_}}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,U){if(L=this.createKeyPrefix(L,this.#Y),U)await this.client.set(L,Y,"PX",U);else await this.client.set(L,Y)}async setMany(L){let Y=[];for(let{key:U,value:Q,ttl:X}of L){let Z=this.createKeyPrefix(U,this.#Y);if(X)Y.push(this.client.set(Z,Q,"PX",X));else Y.push(this.client.set(Z,Q))}await Promise.all(Y)}async delete(L){return L=this.createKeyPrefix(L,this.#Y),await(this.#X?this.client.send("UNLINK",[L]):this.client.del(L))>0}async clear(){try{if(!this.#Y&&this.#Z){await this.client.send("FLUSHDB",[]);return}let L="0",Y=this.#Q,U=this.#Y?`${this.#Y}${this.#U}*`:"*",Q=[];do{let X=await this.client.send("SCAN",[L,"MATCH",U,"COUNT",Y.toString(),"TYPE","string"]),[Z,_]=X;if(L=Z.toString(),_.length===0)continue;if(!this.#Y)_=_.filter(($)=>!$.includes(this.#U));Q.push(_.map(($)=>this.client.del($)))}while(L!=="0");await Promise.all(Q)}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 U of L){let Q=this.createKeyPrefix(U,this.#Y);Y.push(this.client.exists(Q))}return Promise.all(Y)}async getMany(L){if(L.length===0)return[];return L=L.map((U)=>this.createKeyPrefix(U,this.#Y)),await this.client.mget(...L)}async disconnect(){this.client.close()}async deleteMany(L){let Y=!1,U=[];for(let X of L){let Z=this.createKeyPrefix(X,this.#Y);if(this.#X)U.push(this.client.send("UNLINK",[Z]));else U.push(this.client.del(Z))}let Q=await Promise.all(U);for(let X of Q)if(typeof X==="number"&&X>0)Y=!0;return Y}async*iterator(L){let Y=L?`${L}${this.#U}*`:"*",U="0";do{let Q=await this.client.send("SCAN",[U,"MATCH",Y,"TYPE","string"]),[X,Z]=Q;if(U=X.toString(),!L&&!this.#Z)Z=Z.filter((_)=>!_.includes(this.#U));if(Z.length>0){let _=await this.client.mget(...Z);for(let $ of Z.keys()){let D=this.getKeyWithoutPrefix(Z[$],L),H=_[$];yield[D,H]}}}while(U!=="0")}createKeyPrefix(L,Y){return Y?`${Y}${this.#U}${L}`:L}getKeyWithoutPrefix(L,Y){return Y?L.replace(`${Y}${this.#U}`,""):L}}var s;((q)=>{let L=(_)=>{return`redis.connection.${_}`};q.getConnection=(_)=>{if(!z.exists(L(_)))console.error(`No Redis connection with name ${_} found. Please make sure to register the connection before using it.`),process.exit(1);return z.get(L(_))},q.registerConnection=(_,$)=>{if(z.exists(L(_)))console.error(`A Redis connection with the name ${_} has already been registered.`),process.exit(1);return z.instance(L(_),new Bun.RedisClient($.url,Q2($,["url"])))},q.connectionExists=(_)=>{return z.exists(L(_))},q.getDefaultConnection=()=>{return q.getConnection("default")},q.setDefaultConnection=(_)=>{let $=L("default");return z.remove($),z.instance($,q.getConnection(_))}})(s||={});var jL=(L)=>{let Y=EL({stores:[new FL({store:L,namespace:"cache"})]}),U=new Map;return{...Y,tags(...Q){let X=`cache__${Z2(Q,(_)=>_).join("__")}`,Z=U.get(X);if(!Z)Z=EL({stores:[new FL({store:L,namespace:X})]}),U.set(X,Z);return Z}}};class g{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(!g.#L)g.#L=jL(new PL({connection:"cache"}));return g.#L}static get memory(){if(!g.#Y)g.#Y=jL(new X2({ttl:60000,lruSize:5000}));return g.#Y}}class zL extends $2{cacheStrategy;globalTtl;#L;usedTablesPerKey={};constructor(L="explicit",Y=1,U="redis"){super();this.cacheStrategy=L;this.globalTtl=Y;this.#L=g[U].tags("database")}strategy(){return this.cacheStrategy}async get(L){return await this.#L.get(L)??void 0}async put(L,Y,U,Q,X){await this.#L.set(L,Y,(X?.ex??this.globalTtl)*1000);for(let Z of U){let _=this.usedTablesPerKey[Z];if(_===void 0)this.usedTablesPerKey[Z]=[L];else _.push(L)}}async onMutate(L){let Y=L.tags?Array.isArray(L.tags)?L.tags:[L.tags]:[],U=L.tables?Array.isArray(L.tables)?L.tables:[L.tables]:[],Q=new Set;for(let X of U){let Z=fL(X,xL)?TL(X):X,_=this.usedTablesPerKey[Z]??[];for(let $ of _)Q.add($)}if(Q.size>0||Y.length>0){await this.#L.mdel(Y),await this.#L.mdel([...Q]);for(let X of U){let Z=fL(X,xL)?TL(X):X;this.usedTablesPerKey[Z]=[]}}}}var d;((b)=>{let L=(_)=>{return`db.connection.${_}`};b.getConnection=(_)=>{if(!z.exists(L(_)))console.error(`No connection with name ${_} found. Please make sure to register the connection before using it.`),process.exit(1);return z.get(L(_))},b.registerConnection=(_,$)=>{if(z.exists(L(_)))console.error(`A connection with the name ${_} has already been registered.`),process.exit(1);return z.instance(L(_),_2({...$,cache:$.cache===void 0?void 0:$.cache===!0?new zL:$.cache.enabled?new zL($.cache.strategy,$.cache.ttl,$.cache.storage):void 0}))},b.connectionExists=(_)=>{return z.exists(L(_))},b.getDefaultConnection=()=>{return b.getConnection("default")},b.setDefaultConnection=(_)=>{let $=L("default");return z.remove($),z.instance($,b.getConnection(_))}})(d||={});var _L=new Map,BL=(L)=>{for(let[Y,U]of Object.entries(L))_L.set(Y,U)},wL;((e)=>(e.get=(Q,X)=>{return _L.get(Q)??X},e.exists=(Q)=>{return _L.has(Q)},e.clear=()=>{_L.clear()}))(wL||={});var l=(L,Y,U)=>{return S.context.run(new Map([["tenant",Y.tenant],["http:context",Y]]),async()=>{for(let Q of L)try{let X=await Q[U](Y);if(X!==void 0)return X}catch(X){throw X}})},LL=(L,Y)=>{let U=L.map((Q)=>z.make(Q));Y.onRequest((Q)=>{return l(U,Q,"onRequest")}),Y.onTransform((Q)=>{return l(U,Q,"onTransform")}),Y.onBeforeHandle((Q)=>{return l(U,Q,"onBeforeHandle")}),Y.onAfterHandle((Q)=>{return l(U,Q,"onAfterHandle")}),Y.onAfterResponse((Q)=>{return l(U,Q,"onAfterResponse")})};class SL{static register(...L){return function(Y,U,Q){if(U===void 0&&Q===void 0){let X=Reflect.getMetadata(O.middlewares,Y)??[];X.push(...L),Reflect.defineMetadata(O.middlewares,X,Y)}else{let X=Reflect.getMetadata(O.middlewares,Y,U)??[];X.push(...L),Reflect.defineMetadata(O.middlewares,X,Y,U)}}}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){}}import{Elysia as G2}from"elysia";import{omit as H2}from"radash";import O2 from"wampy";class NL extends WebSocket{protocols;constructor(L,Y){super(L,Y);this.protocols=Y}get protocol(){return this.protocols?.[0]??"wamp.2.json"}}var o;((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 W=new O2(G.url,{ws:NL,...H2(G,["url"]),onError(){G.onError?.(),x.emit("elysium:error",new Error(`An error occurred in WAMP connection ${H}`))}}),P=G.maxRetries??5,R=G.retryInterval??5000,I=0,C=async()=>{try{await W.connect()}catch(y){if(console.error(`Failed to connect to WAMP server (attempt ${I+1}/${P}):`,y),I<P)I++,setTimeout(C,R);else console.error(`Max retry attempts (${P}) reached. Giving up.`),x.emit("elysium:error",new Error(`Failed to establish WAMP connection ${H} after ${P} attempts`))}};return C(),z.instance(L(H),W)},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 W(){console.log(`Registering Wamp controller for connection ${H.connection} using ${G.name}`),await c();let P=z.make(G),R=Reflect.getMetadata(O.wamp,G)??{},I=o.getConnection(H.connection??"default"),C=new G2;return C.onStart(async(y)=>{let B=R.registrations??[],V=R.subscriptions??[];for(let M of B)I.register(M.topic,M.handler.bind(P),M.options).then((F)=>{console.log(`Registered ${M.topic} with id ${F.registrationId}`)});for(let M of V)I.subscribe(M.topic,M.handler.bind(P),M.options).then((F)=>{console.log(`Subscribed ${M.topic} with id ${F.subscriptionId}`)})}),C}Reflect.defineMetadata(O.elysiaPlugin,W,G)}},w.register=(H,G)=>{return function(W,P,R){let I=Reflect.getMetadata(O.wamp,W.constructor)??{};I.registrations??=[],I.registrations.push({topic:H,options:G,handler:R.value}),Reflect.defineMetadata(O.wamp,I,W.constructor)}},w.subscribe=(H,G)=>{return function(W,P,R){let I=Reflect.getMetadata(O.wamp,W.constructor)??{};I.subscriptions??=[],I.subscriptions.push({topic:H,options:G,handler:R.value}),Reflect.defineMetadata(O.wamp,I,W.constructor)}}})(o||={});class S extends k{#L;#Y;_appContextStorage=new R2;static get instance(){return z.get("elysium.app")}static get context(){return S.instance._appContextStorage}static register(L={}){return function(Y){let U,Q=Object.getPrototypeOf(Y);while(Q&&Q!==Object.prototype){let Z=Reflect.getMetadata(O.app,Q);if(Z){U=Z;break}Q=Object.getPrototypeOf(Q)}if(U)L=n(U,L);let X=Reflect.getMetadata(O.app,Y);if(X)L=n(X,L);L=n({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 Z=UL.Convert(L,UL.Clone(Bun.env));if(this.#Y&&!UL.Check(L,Z)){let _=UL.Errors(L,Z).First();this.trace(_,"Invalid environment configuration")}BL(UL.Clean(L,Z))}else BL(Bun.env);z.instance("elysium.app",this);let{database:U,redis:Q,wamp:X}=Reflect.getMetadata(O.app,this.constructor);if(Q){for(let Z in Q.connections)s.registerConnection(Z,Q.connections[Z]);if(s.connectionExists(Q.default))s.setDefaultConnection(Q.default)}if(U){for(let Z in U.connections)d.registerConnection(Z,U.connections[Z]);if(d.connectionExists(U.default))d.setDefaultConnection(U.default)}if(X){for(let Z in X.connections)o.registerConnection(Z,X.connections[Z]);if(o.connectionExists(X.default))o.setDefaultConnection(X.default)}this.run().then(()=>x.emit("elysium:app:launched",this,this)).catch((Z)=>{x.emit("elysium:error",Z),this.trace(Z,"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:U}=Reflect.getMetadata(O.app,this.constructor);switch(Y){case"serve":return this.commandServe();case"help":{let Q=L[1];if(Q){let X=U?.find((Z)=>Z.command===Q);if(X){let Z=z.make(X);return this.write(await Z.help()),process.exit(0)}console.error(`Command <${Q}> 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 Q=L.slice(1);return this.commandExec(Y,Q)}}}return process.exit(0)}getConfig(L){return Reflect.getMetadata(O.app,this.constructor)?.[L]??null}async commandExec(L,Y){let{commands:U}=Reflect.getMetadata(O.app,this.constructor),Q=U?.find((X)=>X.command===L);if(!Q)return console.error(`Command ${L} not found`),this.commandList(),process.exit(1);try{let X=z.make(Q);if(await X.init(...Y))await X.run();else{let _=await X.help();this.write(_)}return process.exit(0)}catch(X){return console.error(X.message),process.exit(1)}}async commandServe(){let{server:L,modules:Y,swagger:U,plugins:Q}=Reflect.getMetadata(O.app,this.constructor);if(this.#L=new P2(L).onRequest((Z)=>{if(this.isDebug)console.log(Z.request.method,Z.request.url)}),x.emit("elysium:server:before-init",this,this),this.#L.resolve({as:"global"},({request:Z})=>({tenant:Z.headers.get("x-tenant-id")??"public"})),U)this.#L.use(W2(U));if(Q&&Q.length>0){this.debug("Registering plugins...");for(let Z of Q)this.#L.use(await Z(this))}this.#L.onError({as:"global"},async(Z)=>{if(await this.onError(Z)){x.emit("elysium:error",Z),this.trace({name:"HttpError",message:"Unexpected error while handling HTTP request",stack:Z.error.stack,...Z.error});let _={};if(typeof Z.code==="number")return Z.error.response;else switch(Z.code){case"VALIDATION":{_={scope:Z.error.type,code:Z.error.message};break}case"INTERNAL_SERVER_ERROR":{_={message:Z.error.message};break}}return{type:Z.code,data:_}}}).onStart(async(Z)=>{await this.onStart(Z),x.emit("elysium:server:start",Z,this)}).onStop(async(Z)=>{await this.onStop(Z),x.emit("elysium:server:stop",Z,this),this._appContextStorage.disable()});let X=Reflect.getMetadata(O.middlewares,this.constructor)??[];LL(X,this.#L);for(let Z of Y){let _=Reflect.getMetadata(O.elysiaPlugin,Z);if(_===void 0)return console.error(`Invalid module class ${Z.name} registered in app ${this.constructor.name}. Ensure that you used the @module() decorator on the module.`),process.exit(1);let $=z.bind(Z);await $.beforeRegister(),this.#L.use(await _($)),await $.afterRegister()}x.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((U,Q)=>{let X=z2(Q.command.split(":")),Z=U.get(X)??[];return Z.push(Q),U.set(X,Z),U},new Map);for(let[U,Q]of Y){this.section(this.format(U,4));for(let X of Q)this.commandDescription(X.command,"",X.description)}}commandDescription(L,Y,U,Q=k.SPACE_WIDTH){Y=Y.length===0?" ":` ${Y} `,this.write(` ${this.format(L,6)}${Y}${"\u2219".repeat(Q-L.length-Y.length)} ${U}`)}}import{isArray as B2,trim as D2}from"radash";var CL;((Z)=>{Z.STRING="string";Z.NUMBER="number";Z.BOOLEAN="boolean";Z.ENUM="enum";Z.ARRAY="array"})(CL||={});class kL extends k{static command="command";static description="Command description";static arg(L={}){return function(Y,U){let Q=Reflect.getMetadata(O.arg,Y.constructor)??[],X=Reflect.getMetadata("design:type",Y,U),Z=L.type;if(!Z&&X){if(X===Array){if(Z="array",!L.arrayType)L={...L,arrayType:"string"}}else if(X.constructor!==Object)switch(X.name.toLowerCase()){case"number":Z="number";break;case"boolean":Z="boolean";break;case"string":Z="string";break;default:Z=void 0}else if(Object.values(X).length>0){if(Z="enum",!L.enum)L={...L,enum:Object.values(X)}}}Q.push({name:L.name??U,description:L.description,required:L.required??!1,default:L.default,type:Z,enum:L.enum,arrayType:L.arrayType,propertyKey:U}),Reflect.defineMetadata(O.arg,Q,Y.constructor)}}async init(...L){let Y=this.processArgs(L),U=this.validateArgs(Y);if(!U.valid){if(U.missing.length>0)console.error(`Missing required arguments: ${U.missing.join(", ")}
9
+ `);return!1}if(Object.keys(Y).includes("help"))return!1;let Q=this.getArguments();for(let X of Q)if(Y[X.name]!==void 0)this[X.propertyKey]=Y[X.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 U of Y){let Q=this.format(U.required?"(required)":"(optional)",1,9),X=U.default!==void 0?this.format(`[default: ${U.default}]`,8,11):"",Z="";if(U.type==="array")Z=`<array of ${U.arrayType||"string"}s>`;else if(U.type)Z=`<${U.type}>`;let _=U.enum?` [${U.enum.join("|")}]`:"";if(L+=` ${this.format(`--${U.name}`,6)} ${Z}${_} ${Q} ${X}
14
+ `,U.description)L+=` ${U.description}
15
+
16
+ `}}else L+=`This command has no arguments.
17
+ `;return D2(L,`
18
+ `)}validateArgs(L){let Y=[],U=[],Q=this.getArguments();if(Object.keys(L).includes("help"))return{valid:!0,missing:[]};for(let X of Q){if(X.required&&(L[X.name]===void 0||L[X.name]===null)){Y.push(X.name);continue}if(L[X.name]===void 0)continue;if(X.type==="enum"&&X.enum&&!X.enum.includes(L[X.name]))U.push(`${X.name} (must be one of: ${X.enum.join(", ")})`);if(X.type==="array"&&X.arrayType==="enum"&&X.enum){let Z=L[X.name].filter((_)=>!X.enum.includes(_));if(Z.length>0)U.push(`${X.name} (contains invalid values: ${Z.join(", ")}. Must be one of: ${X.enum.join(", ")})`)}}if(U.length>0)console.error(`Invalid argument values: ${U.join(", ")}
19
+ `);return{valid:Y.length===0&&U.length===0,missing:Y}}processArgs(L){let Y={},U=this.getArguments();for(let Q=0;Q<L.length;Q++){let X=L[Q];if(X.startsWith("--")){let Z=X.slice(2);if(Q+1<L.length&&!L[Q+1].startsWith("--"))Y[Z]=L[Q+1],Q++;else Y[Z]=!0}}for(let Q of U){if(Y[Q.name]===void 0&&Q.default!==void 0){Y[Q.name]=Q.default;continue}if(Y[Q.name]===void 0)continue;if(typeof Y[Q.name]==="string")switch(Q.type||this.inferType(Q.default)){case"number":Y[Q.name]=Number(Y[Q.name]);break;case"boolean":let Z=Y[Q.name].toLowerCase();Y[Q.name]=Z==="true"||Z==="1"||Z==="yes";break;case"enum":if(Q.enum&&Q.enum.length>0&&typeof Q.enum[0]==="number")Y[Q.name]=Number(Y[Q.name]);break;case"array":let _=Y[Q.name].split(",").map(($)=>$.trim());if(Q.arrayType)Y[Q.name]=_.map(($)=>{switch(Q.arrayType){case"number":return Number($);case"boolean":return $.toLowerCase()==="true"||$.toLowerCase()==="1"||$.toLowerCase()==="yes";case"enum":return $;default:return $}});else Y[Q.name]=_;break;case"string":default:break}}return Y}progress(L,Y="Processing"){return new hL(L,Y)}spinner(L="Processing",Y,U){return new qL(L,Y,U)}inferType(L){if(L===void 0)return"string";switch(typeof L){case"number":return"number";case"boolean":return"boolean";default:return B2(L)?"array":"string"}}}class hL extends k{#L=!1;#Y=0;#U=0;#Q="";#X=0;constructor(L=0,Y="Processing"){super();this.#Y=L,this.#Q=Y,this.#L=!0,this.#U=0,this.#X=Date.now(),this.update(0)}update(L=1,Y){if(!this.#L)return;if(this.#U+=L,Y)this.#Q=Y;let U=Math.min(100,Math.floor(this.#U/this.#Y*100)),X=(Date.now()-this.#X)/1000,Z=0,_=0,$="";if(this.#U>0)Z=X/this.#U*this.#Y,_=Math.max(0,Z-X),$=` | ${this.formatTime(X)} elapsed | ${this.formatTime(_)} remaining`;let D=30,H=Math.floor(U/100*D),G=D-H,W="["+"=".repeat(H)+(G>0?">":"")+" ".repeat(Math.max(0,G-(G>0?1:0)))+"]",P=`${this.#Q}: ${W} ${U}% (${this.#U}/${this.#Y})${$}`;if(this.clearLine(),this.write(P,!1),this.#U>=this.#Y)this.complete()}complete(L){if(!this.#L)return;this.#U=this.#Y;let U=(Date.now()-this.#X)/1000;if(this.clearLine(),L)this.write(`${L} (completed in ${this.formatTime(U)})`);else this.write(`${this.#Q} completed in ${this.formatTime(U)}`);this.#L=!1}pause(L){if(!this.#L)return;this.newLine(),this.write(L),this.update(0)}isActive(){return this.#L}getCurrent(){return this.#U}getTotal(){return this.#Y}getPercentage(){return Math.min(100,Math.floor(this.#U/this.#Y*100))}}class qL extends k{#L=!1;#Y="";#U=0;#Q=null;#X=0;#Z=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];#_=80;constructor(L="Processing",Y,U){super();if(this.#Y=L,Y)this.#Z=Y;if(U)this.#_=U;if(this.#L)return;this.#L=!0,this.#U=Date.now(),this.#X=0,this.#Q=setInterval(()=>{this.render()},this.#_),this.render()}update(L){if(!this.#L)return;this.#Y=L}complete(L,Y=!0){if(!this.#L)return;if(this.#Q)clearInterval(this.#Q),this.#Q=null;let Q=(Date.now()-this.#U)/1000;this.clearLine();let X=this.formatTime(Q);if(L)this[Y?"success":"error"](`${L} (${X})`);else this[Y?"success":"error"](`${this.#Y} completed in ${X}`);this.#L=!1}fail(L){this.complete(L,!1)}pause(L){if(!this.#L)return;if(this.#Q)clearInterval(this.#Q),this.#Q=null;this.clearLine(),this.write(L),this.#Q=setInterval(()=>{this.render()},this.#_)}isActive(){return this.#L}getElapsedTime(){return(Date.now()-this.#U)/1000}render(){if(!this.#L)return;let L=this.getElapsedTime(),Y=this.#Z[this.#X];this.#X=(this.#X+1)%this.#Z.length,this.clearLine(),this.write(`${Y} ${this.#Y} (${this.formatTime(L)})`,!1)}}import{Elysia as M2,t as bL}from"elysia";import{assign as V2,isEmpty as $L,objectify as A2}from"radash";var J2=(L)=>{let Y=Reflect.getMetadata("http:body",L.target,L.propertyKey),U=Reflect.getMetadata("http:params",L.target,L.propertyKey)??[],Q=Reflect.getMetadata("http:query",L.target,L.propertyKey),X=Reflect.getMetadata("http:rawContext",L.target,L.propertyKey),Z=Reflect.getMetadata("http:customDecorators",L.target,L.propertyKey)??[],_=Reflect.getMetadata(O.middlewares,L.target,L.propertyKey)??[],$=Reflect.getMetadata(O.services,L.target,L.propertyKey)??[],{path:D,method:H,handler:G,target:W,response:P,operationId:R,description:I,transactional:C}=L,y=Reflect.getMetadata(O.http,W.constructor)??[];y.push({path:D,method:H,body:Y,params:U,query:Q,customDecorators:Z,rawContext:X,handler:G,middlewares:_,response:P,operationId:R,description:I,services:$,transactional:C}),Reflect.defineMetadata(O.http,y,W.constructor)},vL;((U)=>{U[U.SERVER=0]="SERVER";U[U.REQUEST=1]="REQUEST"})(vL||={});var yL;((A)=>(A.controller=(B={path:"/"})=>{return function(V){async function M(){console.log(`Registering HTTP controller for ${B.path} using ${V.name}`),await c(),B=V2({path:"/",scope:0,tags:[]},B);let F=new M2({prefix:B.path,name:V.name});if(B.scope===0){let J=z.make(V);F.resolve({as:"local"},()=>({controller:()=>J}))}else if(B.scope===1)F.resolve({as:"local"},()=>({controller:()=>z.make(V)}));let p=Reflect.getMetadata("http:onRequest",V)??{};if(p.handler)F.onRequest((J)=>{let r=J.controller();return p.handler.call(r,J)});let QL=Reflect.getMetadata(O.middlewares,V)??[];LL(QL,F);let cL=Reflect.getMetadata(O.http,V)??[];for(let J of cL){let r=async(E)=>{let K=[];if(J.rawContext)K[J.rawContext.index]=E;if(J.body)K[J.body.index]=E.body;if(J.query)K[J.query.index]=E.query;if(!$L(J.params))for(let f of J.params)K[f.index]=E.params[f.slug];if(!$L(J.customDecorators))for(let f of J.customDecorators)K[f.index]=await f.handler(E);if(!$L(J.services))for(let f of J.services)K[f.index]=z.get(f.name);return K},mL=J.handler.constructor.name.includes("GeneratorFunction"),AL=J.method==="elysium:SSE",nL=J.transactional??B.transactional??!1,RL=J.body&&J.body.schema===void 0&&J.body.validator!==void 0;J.method=AL?"GET":J.method;let sL=()=>{let E=(K)=>{if(nL)return function(...f){return d.getDefaultConnection().transaction((t)=>{return S.context.run(new Map([["tenant",K.tenant],["http:context",K],["db:tx",t]]),()=>{try{return J.handler.call(K.controller(),...f)}catch(oL){throw t.rollback(),oL}})})};return function(...f){return S.context.run(new Map([["tenant",K.tenant],["http:context",K]]),()=>J.handler.call(K.controller(),...f))}};if(mL)return async function*(K){let f=E(K);try{for await(let t of f(...await r(K)))yield t}catch(t){yield t}};if(AL)return async function*(K){let f=E(K);K.set.headers["Content-Type"]="text/event-stream",K.set.headers["Cache-Control"]="no-cache",K.set.headers.Connection="keep-alive";while(!0)yield`data: ${await f(...await r(K))}
20
+
21
+ `,await Bun.sleep(1)};if(RL)return async function(K){if(await J.body.validator.validate(K))return await E(K)(...await r(K));throw K.status(400,"Invalid request body")};return async function(K){return await E(K)(...await r(K))}},JL=A2(J.params??[],(E)=>E.slug,(E)=>E.schema),XL=J.middlewares.map((E)=>z.make(E));F.route(J.method,J.path,sL(),{config:{},async transform(E){if(RL&&!await J.body.validator.authorize(E))throw E.status(401,"Unauthorized");return l(XL,E,"onTransform")},beforeHandle(E){return l(XL,E,"onBeforeHandle")},afterHandle(E){return l(XL,E,"onAfterHandle")},afterResponse(E){return l(XL,E,"onAfterResponse")},detail:{tags:B.tags,description:J.description,operationId:J.operationId},body:RL?J.body?.validator?.schema:J.body?.schema,response:J.response,params:$L(JL)?void 0:bL.Object(JL)})}return F}Reflect.defineMetadata(O.elysiaPlugin,M,V)}},A.sse=(B={})=>{let{path:V="/",...M}=B;return A.custom({method:"elysium:SSE",path:V,...M})},A.get=(B={})=>{let{path:V="/",...M}=B;return A.custom({method:"GET",path:V,...M})},A.post=(B={})=>{let{path:V="/",...M}=B;return A.custom({method:"POST",path:V,...M})},A.put=(B={})=>{let{path:V="/",...M}=B;return A.custom({method:"PUT",path:V,...M})},A.del=(B={})=>{let{path:V="/",...M}=B;return A.custom({method:"DELETE",path:V,...M})},A.patch=(B={})=>{let{path:V="/",...M}=B;return A.custom({method:"PATCH",path:V,...M})},A.head=(B={})=>{let{path:V="/",...M}=B??{};return A.custom({method:"HEAD",path:V,...M})},A.options=(B={})=>{let{path:V="/",...M}=B;return A.custom({method:"OPTIONS",path:V,...M})},A.trace=(B={})=>{let{path:V="/",...M}=B;return A.custom({method:"TRACE",path:V,...M})},A.custom=({path:B="/",...V})=>{return function(M,F,p){process.nextTick(()=>{J2({path:B,handler:p.value,target:M,propertyKey:F,...V})})}},A.onRequest=()=>{return function(B,V,M){let F=Reflect.getMetadata("http:onRequest",B.constructor)??{};F.handler=M.value,Reflect.defineMetadata("http:onRequest",F,B.constructor)}},A.context=()=>{return function(B,V,M){Reflect.defineMetadata("http:rawContext",{index:M},B,V)}},A.param=(B,V)=>{return function(M,F,p){let QL=Reflect.getMetadata("http:params",M,F)??[];QL.push({slug:B,schema:V??bL.String(),index:p}),Reflect.defineMetadata("http:params",QL,M,F)}},A.query=(B)=>{return function(V,M,F){Reflect.defineMetadata("http:query",{schema:B,index:F},V,M)}},A.body=(B)=>{return function(V,M,F){if(typeof B==="function")Reflect.defineMetadata("http:body",{validator:B,index:F},V,M);else Reflect.defineMetadata("http:body",{schema:B,index:F},V,M)}},A.decorate=(B)=>{return()=>{return function(V,M,F){let p=Reflect.getMetadata("http:customDecorators",V,M)??[];p.push({handler:B,index:F}),Reflect.defineMetadata("http:customDecorators",p,V,M)}}}))(yL||={});import"reflect-metadata";import{assign as I2,uid as K2}from"radash";class gL extends k{#L;#Y;#U="pending";#Q;static register(L={}){return function(Y){L=I2({name:Y.name,queue:"default"},L);let U=`job.${L.name}`;z.instance(U,Y),Reflect.defineMetadata(O.job,{name:U,queue:L.queue},Y)}}id;createdAt;get startedAt(){return this.#L}get completedAt(){return this.#Y}get status(){return this.#U}constructor(L){super();this.id=L||this.generateJobId(),this.createdAt=new Date}async run(){try{this.#U="running",this.#L=new Date,this.debug(`Job ${this.id} started at ${this.#L.toISOString()}`),await this.execute(),this.#U="completed",this.#Y=new Date,this.debug(`Job ${this.id} completed at ${this.#Y.toISOString()}`)}catch(L){if(this.#Q=L instanceof Error?L:new Error(String(L)),this.#U!=="cancelled")this.#U="failed";this.#Y=new Date,this.trace(this.#Q)}}cancel(){this.#U="cancelled"}generateJobId(){return`job_${Date.now()}_${K2(8)}`}}import{getTableConfig as E2,pgSchema as F2,pgTable as dL}from"drizzle-orm/pg-core";import{t as N}from"elysia";var DL=(L,{mode:Y="select"}={})=>{let{columns:U}=E2(L);if(U===void 0)return N.Object({});let Q={};for(let X of U){if(["create","update"].includes(Y)&&X.primary)continue;if(Q[X.name]=j2(X),!X.notNull)Q[X.name]=N.Nullable(Q[X.name]);if(Y==="update"||X.hasDefault||!X.notNull)Q[X.name]=N.Optional(Q[X.name])}return N.Object(Q)},j2=(L)=>{let Y=(()=>{switch(L.dataType){case"string":return N.String({format:L.columnType==="PgUUID"?"uuid":void 0});case"number":return N.Number();case"boolean":return N.Boolean();case"array":return N.Array(N.Any());case"json":return N.Object({});case"date":case"localDate":case"localDateTime":return N.String({format:L.dataType==="date"?"date":"date-time"});case"bigint":return N.BigInt();case"buffer":return N.File();default:return N.Never()}})();if(!L.notNull)Y=N.Optional(Y);else Y=N.Required(Y);return Y},T2=(L,Y,U)=>{let Q=dL(L,Y,U);class X{static $inferSelect=Q.$inferSelect;static $inferInsert=Q.$inferInsert;static $inferUpdate=Q.$inferInsert;static get table(){if(!S.instance||!S.context.getStore)return Q;if(this.supportTenancy){let Z=HL.getCurrentTenant()??"public";return HL.wrapTenant(Z,this)}return Q}static tableName=L;static columns=Y;static extraConfig=U;static insertSchema=DL(Q,{mode:"create"});static updateSchema=DL(Q,{mode:"update"});static selectSchema=DL(Q,{mode:"select"});static supportTenancy=!1}return X},ML=new Map,GL=new Map,HL;((i)=>{let L=(Z)=>{return GL.get(Z)??i.registerTenant(Z)};i.getCurrentTenant=()=>{return S.context.getStore()?.get("tenant")??null},i.wrapTenant=(Z,_)=>{if(Z==="public")return dL(_.tableName,_.columns);let $=`${Z}.${_.tableName}`;if(ML.has($))return ML.get($);let H=L(Z).table(_.tableName,_.columns);return ML.set($,H),H},i.registerTenant=(Z)=>{if(GL.has(Z))return GL.get(Z);let _=F2(Z);return GL.set(Z,_),_},i.withTenant=(Z,_)=>{let $=S.context.getStore(),D=new Map($);return D.set("tenant",Z),S.context.run(D,_)}})(HL||={});import{Elysia as f2}from"elysia";import{assign as x2}from"radash";class lL{static register(L={}){return function(Y){async function U(Q){console.log(`Registering module ${Y.name}`),await c();let X=x2({controllers:[]},L),Z=new f2({name:Y.name,prefix:L.prefix});Z.resolve({as:"local"},()=>({module:Q}));let _=Reflect.getMetadata(O.middlewares,Y)??[];LL(_,Z);for(let $ of X.controllers){let D=Reflect.getMetadata(O.elysiaPlugin,$);if(D===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 Z.use(await D())}return Z}Reflect.defineMetadata(O.elysiaPlugin,U,Y)}}beforeRegister(){return Promise.resolve()}afterRegister(){return Promise.resolve()}}import{eq as OL}from"drizzle-orm";var w2=(L)=>{class Y{static Model=L;static connection="default";get db(){let U=this.constructor.connection,Q=null;if(U==="default")Q=S.context.getStore()?.get("db:tx")??null;return Q??d.getConnection(U)}async all(){return await this.db.select().from(L.table)}async paginate(U,Q=1){let X=await this.db.$count(L.table),Z=Math.max(Q-1,0)*U;return{page:Q,total:X,data:await this.db.select().from(L.table).offset(Z).limit(U)}}async find(U){let[Q]=await this.db.select().from(L.table).where(OL(L.table.id,U));return Q??null}async findBy(U,Q){let[X]=await this.db.select().from(L.table).where(OL(L.table[U],Q));return X??null}async insert(U){let[Q]=await this.db.insert(L.table).values(U).returning();return Q}async update(U,Q){let[X]=await this.db.update(L.table).set(Q).where(OL(L.table.id,U)).returning();return X}async updateAll(U){return await this.db.update(L.table).set(U).returning()}async delete(U){let[Q]=await this.db.delete(L.table).where(OL(L.table.id,U)).returning();return Q}async deleteAll(){return await this.db.delete(L.table).returning()}}return Y};import{Elysia as S2}from"elysia";var pL;((v)=>(v.controller=(_)=>{return function($){async function D(){console.log(`Registering Websocket route for ${_.path} using ${$.name}`),await c();let H=z.make($),G=Reflect.getMetadata(O.websocket,$)??{},W=G.open?.bind(H),P=G.close?.bind(H),R=G.message?.bind(H),I=G.drain?.bind(H),C=G.error?.bind(H)??((B)=>x.emit("elysium:error",B.error)),y=new S2;return y.ws(_.path,{open:W,close:P,message:R,drain:I,error:C,body:G.body,..._.options}),y}Reflect.defineMetadata(O.elysiaPlugin,D,$)}},v.onOpen=()=>{return function(_,$,D){let H=Reflect.getMetadata(O.websocket,_.constructor)??{};H.open=D.value,Reflect.defineMetadata(O.websocket,H,_.constructor)}},v.onClose=()=>{return function(_,$,D){let H=Reflect.getMetadata(O.websocket,_.constructor)??{};H.close=D.value,Reflect.defineMetadata(O.websocket,H,_.constructor)}},v.onMessage=(_)=>{return function($,D,H){let G=Reflect.getMetadata(O.websocket,$.constructor)??{};G.message=H.value,G.body=_,Reflect.defineMetadata(O.websocket,G,$.constructor)}},v.onDrain=()=>{return function(_,$,D){let H=Reflect.getMetadata(O.websocket,_.constructor)??{};H.drain=D.value,Reflect.defineMetadata(O.websocket,H,_.constructor)}},v.onError=()=>{return function(_,$,D){let H=Reflect.getMetadata(O.websocket,_.constructor)??{};H.error=D.value,Reflect.defineMetadata(O.websocket,H,_.constructor)}}))(pL||={});import{uid as N2}from"radash";var iL=globalThis.Worker;class uL extends k{#L;queues=new Map;defaultQueueName="default";static spawn(L,Y=["default"],U){let Q=new this;Q.debug(`Worker ${Q.id} starting with queues: ${Y.join(", ")}`);for(let X of Y)Q.createQueue({name:X,concurrency:U?.concurrency??1,maxRetries:U?.maxRetries??5,retryDelay:U?.retryDelay??5000,pauseOnError:U?.pauseOnError??!1});return L.addEventListener("message",async(X)=>{let{type:Z="job:process",jobId:_,job:$,args:D,queue:H="default"}=X.data;switch(Z){case"job:cancel":let G=Q.cancelJob(_,H);L.postMessage({type:"job:canceled",jobId:_,queue:H,success:G,count:G?1:0});break;case"job:cancelAll":let W=Q.cancelAllJobs(H);L.postMessage({type:"jobs:canceled",queue:H,count:W});break;case"job:process":Q.debug(`Worker ${Q.id} received job ${$} for queue ${H}`);try{let P=z.get($);if(!P)throw Q.error(`Job class ${$} not found`),new Error(`Job class ${$} not found`);let R=new P(...D||[]);Q.addJob(R,H),L.postMessage({type:"job:received",jobId:R.id,queue:H})}catch(P){Q.trace({...P,...U??{}},`Error while adding job '${$}' to queue '${H}' with worker ${Q.id}`),L.postMessage({type:"job:error",jobName:$,error:P.message})}break}}),L.addEventListener("error",(X)=>{Q.trace({...X.error,filename:X.filename},`Worker ${Q.id} error:`)}),L.addEventListener("unhandledrejection",(X)=>{Q.trace(X,`Worker ${Q.id} unhandled rejection:`)}),L.postMessage({type:"worker:ready",id:Q.id,queues:Y}),Q}constructor(){super();this.#L=N2(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 U=this.queues.get(Y);if(!U)return this.error(`Queue '${Y}' does not exist`),this;if(U.draining)return this.warning(`Queue '${Y}' is draining, job ${L.id} will not be added`),this;let Q={job:L,retries:0,queueName:Y};if(U.jobs.push(Q),this.debug(`Added job ${L.id} to queue '${Y}'`),!U.paused&&U.processing<U.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 U=Y.jobs.length;Y.jobs=[],this.info(`Cleared ${U} jobs from queue '${L}'`)}}else for(let[Y,U]of this.queues.entries()){let Q=U.jobs.length;U.jobs=[],this.info(`Cleared ${Q} 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 U=Y.jobs.shift();if(!U)return;if(U.job.status==="cancelled"){this.info(`Skipping cancelled job ${U.job.id}`),Y.processing--,this.processQueueJobs(L);return}Y.processing++;try{if(this.debug(`Processing job ${U.job.id} from queue '${L}'`),await U.job.run(),U.job.status==="failed"){if(U.retries<Y.options.maxRetries)U.retries++,this.warning(`Job ${U.job.id} failed, retrying (${U.retries}/${Y.options.maxRetries})`),setTimeout(()=>{if(U.job.status!=="cancelled")Y.jobs.push(U),this.processQueueJobs(L);else this.info(`Skipping cancelled job ${U.job.id} during retry delay`)},Y.options.retryDelay);else if(this.error(`Job ${U.job.id} failed after ${U.retries} retries`),Y.options.pauseOnError)this.pause(L),this.warning(`Queue '${L}' paused due to job failure`)}else if(U.job.status==="completed")this.success(`Job ${U.job.id} completed successfully`);else this.info(`Job ${U.job.id} cancelled while running`)}catch(Q){if(this.error(`Unexpected error processing job ${U.job.id}: ${Q}`),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,U]of this.queues.entries())L[Y]={waiting:U.jobs.length,processing:U.processing,paused:U.paused,draining:U.draining};return L}cancelJob(L,Y){if(Y)return this.cancelJobInQueue(L,Y);else{let U=!1;for(let[Q]of this.queues.entries())if(this.cancelJobInQueue(L,Q)){U=!0;break}return U}}cancelJobInQueue(L,Y){let U=this.queues.get(Y);if(!U)return!1;let Q=U.jobs.findIndex((X)=>X.job.id===L);if(Q>=0)return U.jobs[Q].job.cancel(),this.info(`Canceled job ${L} in queue '${Y}'`),!0;return!1}cancelAllJobs(L){let Y=0;if(L){let U=this.queues.get(L);if(U)Y=U.jobs.length,U.jobs.forEach((Q)=>{Q.job.cancel()}),this.info(`Canceled ${Y} jobs in queue '${L}'`)}else for(let[U,Q]of this.queues.entries()){let X=Q.jobs.length;Q.jobs.forEach((Z)=>{Z.job.cancel()}),Y+=X,this.info(`Canceled ${X} jobs in queue '${U}'`)}return Y}}class VL extends k{workers=[];currentWorkerIndex=0;queueWorkerMap=new Map;static instance=new VL;constructor(){super()}async init(){}async addWorker(L=[]){let Y;if(ELYSIUM_BUILD)Y=new iL("./index.js",{argv:["work",...L.map((U)=>`--queue=${U}`)]});else{let U=await Array.fromAsync(new Bun.Glob("./src/**/*.job.ts").scan());Y=new iL("./index.ts",{preload:U,argv:["work",...L.map((Q)=>`--queue=${Q}`)]})}Y.addEventListener("error",(U)=>{this.trace({message:"An error occurred inside a worker process",stack:U.message,name:"WorkerError"}),this.removeWorker(Y),this.addWorker(L)}),Y.addEventListener("messageerror",(U)=>{this.error(`Worker message error: ${U}`)}),Y.addEventListener("message",(U)=>{if(U.data.type==="worker:ready")this.debug(`Worker ${U.data.id} ready with queues: ${U.data.queues.join(", ")}`);else if(U.data.type==="job:received")this.debug(`Job ${U.data.jobId} received by worker for queue ${U.data.queue}`);else if(U.data.type==="job:error")this.error(`Error processing job ${U.data.jobName}: ${U.data.error}`);else this.debug(`Worker message: ${JSON.stringify(U.data)}`)}),this.workers.push(Y);for(let U of L){if(!this.queueWorkerMap.has(U))this.queueWorkerMap.set(U,[]);this.queueWorkerMap.get(U).push(Y)}}removeWorker(L){let Y=L??this.workers.pop();if(!Y)return;Y.terminate();for(let[U,Q]of this.queueWorkerMap.entries())this.queueWorkerMap.set(U,Q.filter((X)=>X!==Y));if(L)this.workers=this.workers.filter((U)=>U!==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:U,queue:Q="default"}=Reflect.getMetadata(O.job,L),X=this.queueWorkerMap.get(Q)||this.workers;if(X.length===0)throw new Error(`No workers available for queue '${Q}'`);let Z=this.currentWorkerIndex%X.length;X[Z].postMessage({job:U,args:Y,queue:Q}),this.currentWorkerIndex=(this.currentWorkerIndex+1)%this.workers.length}cancelJob(L,Y){for(let U of this.workers)U.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}}export{F0 as t,VL as WorkerPool,uL as Worker,pL as Websocket,o as Wamp,HL as Tenancy,KL as ServiceScope,z as Service,w2 as Repository,s as Redis,lL as Module,T2 as Model,SL as Middleware,gL as Job,k as InteractsWithConsole,vL as HttpControllerScope,yL as Http,x as Event,wL as Env,d as Database,ZL as ConsoleFormat,CL as CommandArgumentType,kL as Command,g as Cache,S as Application};
22
+
23
+ //# debugId=14632E349B4BAC5C64756E2164756E21
24
+ //# sourceMappingURL=index.js.map
package/dist/job.d.ts ADDED
@@ -0,0 +1,106 @@
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
+ }
106
+ //# sourceMappingURL=job.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=macros.d.ts.map
@@ -0,0 +1,70 @@
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
+ }
70
+ //# sourceMappingURL=middleware.d.ts.map