@virid/express 0.1.1 → 0.1.3
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.cjs +21 -21
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +21 -21
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,40 +1,40 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @virid/express v0.
|
|
2
|
+
* @virid/express v0.1.3
|
|
3
3
|
* Add express functionality to virid
|
|
4
4
|
*/
|
|
5
|
-
var
|
|
5
|
+
var Ue=Object.defineProperty;var wt=(r,e,t)=>e in r?Ue(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var n=(r,e)=>Ue(r,"name",{value:e,configurable:!0});var y=(r,e,t)=>wt(r,typeof e!="symbol"?e+"":e,t);import{MessageWriter as Jt}from"@virid/core";import{MessageRegistry as Yt,MessageWriter as Kt}from"@virid/core";import{BaseMessage as St,MessageWriter as te}from"@virid/core";import{MessageWriter as vt}from"@virid/core";var ve=class ve{constructor(e,t,s,i,o){y(this,"id");y(this,"req");y(this,"res");y(this,"timestamp");y(this,"route");y(this,"rc",0);y(this,"isClosed",!1);this.id=e,this.req=t,this.res=s,this.timestamp=i,this.route=o}inc(){this.rc++}dec(){this.rc--,this.rc===0&&this.tryFinalize()}tryFinalize(){if(this.res.writableEnded||this.isClosed)return;this.isClosed=!0;let e=`[Virid Express] Request Orphaned: The connection was closed because all systems finished execution without sending a response.
|
|
6
6
|
Route: ${this.route}
|
|
7
|
-
Uptime: ${Date.now()-this.timestamp}ms`;
|
|
7
|
+
Uptime: ${Date.now()-this.timestamp}ms`;vt.error(new Error(e)),this.res.headersSent?this.res.end():this.res.status(500).json({error:"Internal Logic Error",message:"Request processed but no response was returned by any system."})}};n(ve,"HttpContext");var ee=ve,Se=class Se{constructor(e,t=null,s={}){y(this,"status");y(this,"data");y(this,"headers");this.status=e,this.data=t,this.headers=s}};n(Se,"HttpResponse");var M=Se,be=class be extends M{constructor(e,t={}){super(200,e,t)}};n(be,"OkResponse");var he=be,Ae=class Ae extends M{constructor(e,t={}){super(201,e,t)}};n(Ae,"CreatedResponse");var pe=Ae,ke=class ke extends M{constructor(){super(204,null)}};n(ke,"NoContentResponse");var fe=ke,Ce=class Ce extends M{constructor(e="Bad Request"){super(400,{error:e})}};n(Ce,"BadRequestResponse");var ge=Ce,Re=class Re extends M{constructor(e="Unauthorized"){super(401,{error:e})}};n(Re,"UnauthorizedResponse");var me=Re,$e=class $e extends M{constructor(e="Forbidden"){super(403,{error:e})}};n($e,"ForbiddenResponse");var ye=$e,Te=class Te extends M{constructor(e="Not Found"){super(404,{error:e})}};n(Te,"NotFoundResponse");var xe=Te,He=class He extends M{constructor(e="Conflict"){super(409,{error:e})}};n(He,"ConflictResponse");var Le=He,Oe=class Oe extends M{constructor(e){super(422,{errors:e})}};n(Oe,"UnprocessableEntityResponse");var Ge=Oe,Ve=class Ve extends M{constructor(e="Internal Server Error"){super(500,{error:e})}};n(Ve,"InternalServerErrorResponse");var Me=Ve,Pe=class Pe extends M{constructor(e,t,s={}){super(e,t,s)}};n(Pe,"CustomResponseResponse");var Ee=Pe,Ie=class Ie extends M{constructor(t,s={dotfiles:"allow"}){super(206,s);y(this,"filePath");y(this,"options");this.filePath=t,this.options=s}};n(Ie,"StreamFileResponse");var G=Ie,De=class De extends M{constructor(t,s={}){super(s.status,{},s.headers);y(this,"stream");y(this,"options");this.stream=t,this.options=s}};n(De,"StreamResponse");var z=De,nr=n((r,e={})=>new he(r,e),"Ok"),ir=n((r,e={})=>new pe(r,e),"Created"),ar=n(()=>new fe,"NoContent"),or=n((r="Bad Request")=>new ge(r),"BadRequest"),cr=n((r="Unauthorized")=>new me(r),"Unauthorized"),lr=n((r="Forbidden")=>new ye(r),"Forbidden"),dr=n((r="Not Found")=>new xe(r),"NotFound"),we=n((r="Internal Server Error")=>new Me(r),"InternalServerError"),ur=n((r,e,t={})=>new Ee(r,e,t),"CustomResponse"),hr=n((r,e)=>new G(r,e),"StreamFile"),pr=n((r,e)=>new z(r,e),"Stream"),Be=class Be extends Error{constructor(t,s){super(s);y(this,"status");y(this,"message");this.status=t,this.message=s}};n(Be,"HttpError");var C=Be;var v=new Map;function T(r,e){if(!r){e.dec();return}(Array.isArray(r)?r:[r]).forEach(s=>{s instanceof M?bt(s,e):s instanceof C?(e.res.status(s.status).json(s.message),v.delete(e.id)):s instanceof St?te.write(s):te.warn(`[Virid Express] Invalid Return Type: ${typeof s}. Expected HttpResponse or Message.`)}),e.dec()}n(T,"handleResult");function bt(r,e){let{res:t}=e;if(r.headers&&Object.entries(r.headers).forEach(([s,i])=>t.setHeader(s,i)),r.status&&t.status(r.status),r instanceof G){e.inc(),t.sendFile(r.filePath,r.options,s=>{t.headersSent||te.error(s,`[Virid Express] SteamFile Error: Path: ${r.filePath}`),e.res.end(),v.delete(e.id),e.isClosed=!0,e.dec()});return}if(r instanceof z){let{stream:s}=r;e.inc(),s.pipe(t);let i=n(()=>{v.has(e.id)&&(e.res.end(),v.delete(e.id),e.isClosed=!0,e.dec())},"cleanup");s.on("end",i),s.on("error",o=>{t.headersSent||te.error(o,"[Virid Express] Stream Error"),i()}),s.on("close",i);return}t.status(r.status).json(r.data),v.delete(e.id)}n(bt,"handleHttpResponse");var Xe=Object.defineProperty,At=n((r,e,t)=>e in r?Xe(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,"pe"),c=n((r,e)=>Xe(r,"name",{value:e,configurable:!0}),"o"),l=n((r,e,t)=>At(r,typeof e!="symbol"?e+"":e,t),"i"),H,Je=(H=class{static send(...e){p.write(this,...e)}},n(H,"L"),H);c(Je,"BaseMessage");var ie=Je,O,Ze=(O=class extends ie{constructor(){super(),l(this,"__kind","SingleMessage")}},n(O,"W"),O);c(Ze,"SingleMessage");var ae=Ze,V,et=(V=class extends ie{constructor(){super(),l(this,"__kind","EventMessage")}},n(V,"F"),V);c(et,"EventMessage");var R=et,P,tt=(P=class extends R{constructor(e,t){super(),l(this,"error"),l(this,"context"),this.error=e,this.context=t}},n(P,"Q"),P);c(tt,"ErrorMessage");var je=tt,I,rt=(I=class extends R{constructor(e){super(),l(this,"context"),this.context=e}},n(I,"z"),I);c(rt,"WarnMessage");var Qe=rt,D,st=(D=class extends R{constructor(e){super(),l(this,"context"),this.context=e}},n(D,"U"),D);c(st,"InfoMessage");var _e=st,B,nt=(B=class extends R{constructor(e,t,s){super(),l(this,"ComponentClass"),l(this,"recipe"),l(this,"label"),this.ComponentClass=e,this.recipe=t,this.label=s}},n(B,"J"),B);c(nt,"AtomicModifyMessage");var ze=nt,Ne=new Map,qe=new Map,N,kt=(N=class extends ae{constructor(){super()}static send(...e){let t=new this(...e),s=t.debounceTime,i=Ne.get(this);if(i){t.debounceCallback(i);let a=qe.get(this);a&&clearTimeout(a)}Ne.set(this,t);let o=setTimeout(()=>{Ne.delete(this),qe.delete(this)},s);qe.set(this,o),p.write(t)}debounceCallback(e){}},n(N,"Y"),N);c(kt,"DebounceMessage");var re=null;function it(r){re=r}n(it,"ce");c(it,"activateInstance");var Ct=new Proxy({},{get(r,e){return e==="dispatch"?t=>{if(!re){console.error(`[Virid] Message dispatched before system init: ${t.constructor.name}`);return}return re.dispatch(t)}:Reflect.get(re||{},e)}}),q,at=(q=class{static write(e,...t){let s=typeof e=="function"?new e(...t):e;Ct.dispatch(s)}static error(e,t=""){this.write(new je(e,t))}static warn(e){this.write(new Qe(e))}static info(e){this.write(new _e(e))}},n(q,"q"),q);c(at,"MessageWriter");var p=at,j,ot=(j=class{constructor(e){l(this,"dirtySignalTypes",new Set),l(this,"eventQueue",[]),l(this,"isRunning",!1),l(this,"globalTick",0),l(this,"internalDepth",0),l(this,"eventHub"),l(this,"tickPayload",{}),l(this,"beforeExecuteHooks",[]),l(this,"afterExecuteHooks",[]),l(this,"beforeTickHooks",[]),l(this,"afterTickHooks",[]),this.eventHub=e}addBeforeExecute(e,t,s){s?this.beforeExecuteHooks.unshift({type:e,handler:t}):this.beforeExecuteHooks.push({type:e,handler:t})}addAfterExecute(e,t,s){s?this.afterExecuteHooks.unshift({type:e,handler:t}):this.afterExecuteHooks.push({type:e,handler:t})}addBeforeTick(e,t){t?this.beforeTickHooks.unshift(e):this.beforeTickHooks.push(e)}addAfterTick(e,t){t?this.afterTickHooks.unshift(e):this.afterTickHooks.push(e)}markDirty(e){e instanceof R?this.eventQueue.push(e):e instanceof ae&&this.dirtySignalTypes.add(e.constructor)}tick(e){if(!(this.isRunning||this.dirtySignalTypes.size===0&&this.eventQueue.length===0)){if(this.internalDepth>100){this.internalDepth=0,this.dirtySignalTypes.clear(),this.eventQueue=[],this.eventHub.reset(),p.error(new Error("[Virid Dispatcher] Deadlock: Recursive loop detected \u{1F4A5}."));return}this.isRunning=!0,this.internalDepth++,queueMicrotask(()=>{let t,s;try{this.internalDepth==0&&(this.tickPayload={},this.executeTickHooks(this.beforeTickHooks));let i=this.prepareSnapshot();t=i.signalSnapshot,s=i.eventSnapshot;let o=this.collectTasks(s,t,e);this.executeTasks(o)}catch(i){p.error(i,"[Virid Dispatcher] Unhandled Error")}finally{t&&s&&this.clear(s,t),this.isRunning=!1,this.dirtySignalTypes.size>0||this.eventQueue.length>0?this.tick(e):(this.executeTickHooks(this.afterTickHooks),this.globalTick++,this.internalDepth=0)}})}}collectTasks(e,t,s){let i=[];for(let a of e)(s.get(a.constructor)||[]).forEach(d=>{i.push(new Ye(d.fn,d.priority,a,{context:d.fn.systemContext,tick:this.globalTick,payload:{}}))});let o=new Set;for(let a of t)(s.get(a)||[]).forEach(d=>{o.has(d.fn)||(i.push(new Ye(d.fn,d.priority,this.eventHub.peekSignal(a),{context:d.fn.systemContext,tick:this.globalTick,payload:{}})),o.add(d.fn))});return i}executeTasks(e){e.sort((t,s)=>s.priority-t.priority);for(let t of e)try{let s=t.execute(this.beforeExecuteHooks,this.afterExecuteHooks);s instanceof Promise&&s.catch(i=>p.error(i,`[Virid Dispatcher]: Async System Error.
|
|
8
8
|
SystemLocation: ${t.hookContext.context.targetClass.name}.${t.hookContext.context.methodName}
|
|
9
9
|
MessageName: ${t.message.constructor.name}
|
|
10
|
-
MessageData: ${JSON.stringify(t.message)}`))}catch(s){
|
|
10
|
+
MessageData: ${JSON.stringify(t.message)}`))}catch(s){p.error(s,`[Virid Dispatcher]: Sync System Error.
|
|
11
11
|
SystemLocation: ${t.hookContext.context.targetClass.name}.${t.hookContext.context.methodName}
|
|
12
12
|
MessageName: ${t.message.constructor.name}
|
|
13
|
-
MessageData: ${JSON.stringify(t.message)}`)}}prepareSnapshot(){this.eventHub.flip();let e=new Set(this.dirtySignalTypes),t=[...this.eventQueue];return this.dirtySignalTypes.clear(),this.eventQueue=[],{signalSnapshot:e,eventSnapshot:t}}clear(e,t){let s=new Set(t);e.forEach(i=>s.add(i.constructor)),this.eventHub.clearSignals(s),this.eventHub.clearEvents()}executeTickHooks(e){let t={tick:this.globalTick,timestamp:Date.now(),payload:this.tickPayload};e.forEach(s=>s(t))}},n(
|
|
13
|
+
MessageData: ${JSON.stringify(t.message)}`)}}prepareSnapshot(){this.eventHub.flip();let e=new Set(this.dirtySignalTypes),t=[...this.eventQueue];return this.dirtySignalTypes.clear(),this.eventQueue=[],{signalSnapshot:e,eventSnapshot:t}}clear(e,t){let s=new Set(t);e.forEach(i=>s.add(i.constructor)),this.eventHub.clearSignals(s),this.eventHub.clearEvents()}executeTickHooks(e){let t={tick:this.globalTick,timestamp:Date.now(),payload:this.tickPayload};e.forEach(s=>s(t))}},n(j,"K"),j);c(ot,"Dispatcher");var Rt=ot,Q,ct=(Q=class{constructor(e,t,s,i){l(this,"fn"),l(this,"priority"),l(this,"message"),l(this,"hookContext"),this.fn=e,this.priority=t,this.message=s,this.hookContext=i}triggerHooks(e){let t=Array.isArray(this.message)?this.message[0]:this.message;if(t){for(let s of e)if(t instanceof s.type)try{let i=s.handler(this.message,this.hookContext);i instanceof Promise&&i.catch(o=>{p.error(o,`[Virid Hook] Async Hook Error:
|
|
14
14
|
It is prohibited to use asynchronous hooks within Hook:
|
|
15
|
-
${s.type.name}`)})}catch(i){
|
|
15
|
+
${s.type.name}`)})}catch(i){p.error(i,`[Virid Hook] Hook Execute Failed:
|
|
16
16
|
Triggered by: ${t.constructor.name}
|
|
17
|
-
Registered type: ${s.type.name}`)}}}execute(e,t){this.triggerHooks(e);let s=c(()=>this.triggerHooks(t),"runAfter");try{let i=this.fn(this.message);return i instanceof Promise?i.finally(()=>s()):(s(),i)}catch(i){throw s(),i}}},n(
|
|
18
|
-
${e.constructor.name} must extend SingleMessage or EventMessage`))}flip(){this.signalActive=this.signalStaging,this.signalStaging=new Map,this.eventActive=this.eventStaging,this.eventStaging=[]}peekSignal(e){return this.signalActive.get(e)||[]}getEventStream(){return this.eventActive}peekEventAt(e){return this.eventActive[e]}clearSignals(e){e.forEach(t=>this.signalActive.delete(t))}clearEvents(){this.eventActive=[]}reset(){this.signalActive.clear(),this.signalStaging.clear(),this.eventActive=[],this.eventStaging=[]}},n(
|
|
17
|
+
Registered type: ${s.type.name}`)}}}execute(e,t){this.triggerHooks(e);let s=c(()=>this.triggerHooks(t),"runAfter");try{let i=this.fn(this.message);return i instanceof Promise?i.finally(()=>s()):(s(),i)}catch(i){throw s(),i}}},n(Q,"X"),Q);c(ct,"ExecutionTask");var Ye=ct,_,lt=(_=class{constructor(){l(this,"signalActive",new Map),l(this,"signalStaging",new Map),l(this,"eventActive",[]),l(this,"eventStaging",[])}push(e){if(e instanceof ae){let t=e.constructor;this.signalStaging.has(t)||this.signalStaging.set(t,[]),this.signalStaging.get(t).push(e)}else e instanceof R?this.eventStaging.push(e):p.error(new Error(`[Virid Message] Invalid Message:
|
|
18
|
+
${e.constructor.name} must extend SingleMessage or EventMessage`))}flip(){this.signalActive=this.signalStaging,this.signalStaging=new Map,this.eventActive=this.eventStaging,this.eventStaging=[]}peekSignal(e){return this.signalActive.get(e)||[]}getEventStream(){return this.eventActive}peekEventAt(e){return this.eventActive[e]}clearSignals(e){e.forEach(t=>this.signalActive.delete(t))}clearEvents(){this.eventActive=[]}reset(){this.signalActive.clear(),this.signalStaging.clear(),this.eventActive=[],this.eventStaging=[]}},n(_,"Z"),_);c(lt,"EventHub");var $t=lt,F,dt=(F=class{constructor(){l(this,"systemTaskMap",new Map)}register(e,t,s=0){let i=this.systemTaskMap.get(e)||[];if(i.findIndex(o=>o.fn===t)===-1)i.push({fn:t,priority:s}),i.sort((o,a)=>a.priority-o.priority),this.systemTaskMap.set(e,i);else{let o=t.name||"Anonymous";return p.error(new Error(`[Virid Error] System Already Registered:
|
|
19
19
|
Class ${e.name}
|
|
20
|
-
Function ${o}`)),()=>{}}return()=>{let o=this.systemTaskMap.get(e);if(o){let a=o.findIndex(d=>d.fn===t);a!==-1&&(o.splice(a,1),o.length===0&&this.systemTaskMap.delete(e))}}}},n(
|
|
21
|
-
${
|
|
22
|
-
${
|
|
23
|
-
${
|
|
24
|
-
${
|
|
25
|
-
Component ${r.ComponentClass.name} not found in Registry.`);return}try{r.recipe(e),
|
|
20
|
+
Function ${o}`)),()=>{}}return()=>{let o=this.systemTaskMap.get(e);if(o){let a=o.findIndex(d=>d.fn===t);a!==-1&&(o.splice(a,1),o.length===0&&this.systemTaskMap.delete(e))}}}},n(F,"ee"),F);c(dt,"MessageRegistry");var Tt=dt,W,ut=(W=class{constructor(){l(this,"eventHub",new $t),l(this,"dispatcher",new Rt(this.eventHub)),l(this,"registry",new Tt),l(this,"middlewares",[]),it(this)}useMiddleware(e,t){this.middlewares.push(e)}onBeforeExecute(e,t,s){this.dispatcher.addBeforeExecute(e,t,s)}onAfterExecute(e,t,s){this.dispatcher.addAfterExecute(e,t,s)}onBeforeTick(e,t){this.dispatcher.addBeforeTick(e,t)}onAfterTick(e,t){this.dispatcher.addAfterTick(e,t)}dispatch(e){if(!(e instanceof ie)){p.error(new Error(`[Virid Dispatch] Type Error: Message must be an instance of BaseMessage,message:${e}`));return}this.pipeline(e,()=>{if(!this.registry.systemTaskMap.has(e.constructor)){p.error(new Error(`[Virid Dispatch] No handler for message: ${e.constructor.name}`));return}this.eventHub.push(e),this.dispatcher.markDirty(e),this.dispatcher.tick(this.registry.systemTaskMap)})}pipeline(e,t){let s=0,i=c(()=>{s<this.middlewares.length?this.middlewares[s++](e,i):t()},"next");i()}register(e,t,s=0){return this.registry.register(e,t,s)}},n(W,"te"),W);c(ut,"MessageInternal");var Ht=ut,U,ht=(U=class{constructor(){l(this,"bindings",new Map),l(this,"singletonInstances",new Map)}bind(e){let t={type:"transient",ctor:e};return this.bindings.set(e,t),{toSelf:c(()=>({inSingletonScope:c(()=>(t.type="singleton",{onActivation:c(s=>{},"onActivation")}),"inSingletonScope")}),"toSelf")}}get(e,t){let s=this.bindings.get(e);if(!s)throw new Error(`[Virid Container] Unbound Constructor: No binding found for ${e.name}`);let i=s.ctor;if(s.type==="singleton"){if(!this.singletonInstances.has(e)){let a=new i,d=t(a);this.singletonInstances.set(e,d)}return this.singletonInstances.get(e)}let o=new i;return t(o)}},n(U,"re"),U);c(ht,"ViridContainer");var Ot=ht,h={reset:"\x1B[0m",red:"\x1B[31m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m",bold:"\x1B[1m",green:"\x1B[32m"};function Y(r,e,t){let s={params:r,targetClass:Object,methodName:t,originalMethod:e};return e.ccsContext=s,e}n(Y,"N");c(Y,"withContext");var Vt=c(r=>{let e=`${h.green}${h.bold} \u2714 [Virid Info] ${h.reset}`,t=`${h.magenta}${r.context}${h.reset}`;console.log(`${e}${h.gray}Global Info Caught:${h.reset}
|
|
21
|
+
${h.green}Details:${h.reset}`,r.context||"unknown Info")},"globalInfoHandler"),Pt=c(r=>{let e=`${h.red}${h.bold} \u2716 [Virid Error] ${h.reset}`,t=`${h.magenta}${r.context}${h.reset}`;console.error(`${e}${h.gray}Global Error Caught:${h.reset}
|
|
22
|
+
${h.red}Context:${h.reset} ${t}
|
|
23
|
+
${h.red}Details:${h.reset}`,r.error||r||"unknown Error")},"globalErrorHandler"),It=c(r=>{let e=`${h.yellow}${h.bold} \u26A0 [Virid Warn] ${h.reset}`,t=`${h.cyan}${r.context}${h.reset}`;console.warn(`${e}${h.gray}Global Warn Caught:${h.reset}
|
|
24
|
+
${h.yellow}Context:${h.reset} ${t}`)},"globalWarnHandler"),Dt=c(r=>{let e=K.get(r.ComponentClass);if(!e){console.error(`[Virid Modify] Component Not Found:
|
|
25
|
+
Component ${r.ComponentClass.name} not found in Registry.`);return}try{r.recipe(e),p.warn(`[Virid Modify] Successfully:
|
|
26
26
|
Modify on ${r.ComponentClass.name}
|
|
27
|
-
label: ${r.label}`)}catch(t){
|
|
28
|
-
${r.label}`)}},"atomicModifyHandler");function
|
|
29
|
-
Unable to recognize system parameters, please confirm if import "reflection-metadata" was introduced at the beginning!`);
|
|
27
|
+
label: ${r.label}`)}catch(t){p.error(t,`[Virid Error] Modify Failed:
|
|
28
|
+
${r.label}`)}},"atomicModifyHandler");function pt(r){r.register(ze,Y(ze,Dt,"GlobalAtomicModifier"),1e3),r.register(Qe,Y(Qe,It,"GlobalWarnHandler"),-999),r.register(je,Y(je,Pt,"GlobalErrorHandler"),-999),r.register(_e,Y(_e,Vt,"GlobalInfoHandler"),-999),K=r}n(pt,"le");c(pt,"initializeGlobalSystems");var K=null,Er=new Proxy({},{get(r,e){return(...t)=>{if(!K){console.warn(`[Virid Vue] App method "${String(e)}" called before initialization.`);return}let s=K[e];if(typeof s=="function")return s.apply(K,t)}}}),Ke=new Set,L,ft=(L=class{constructor(){l(this,"container",new Ot),l(this,"messageInternal",new Ht),l(this,"activationHooks",[])}addActivationHook(e){this.activationHooks.push(e)}get(e){return e.length>0&&p.error(new Error(`[Virid Container] Violation: Component "${e.name}" should not have constructor arguments. Dependency Injection is only allowed in Systems.`)),this.container.get(e,t=>this.handleActivation(t))}handleActivation(e){return e&&this.activationHooks.reduce((t,s)=>{try{let i=s(t);return i===void 0&&p.warn(`[Virid Container] Hook Does Bot Return A Value: Hook "${s.name}" should return a instance to continue.`),i!==void 0?i:t}catch(i){return p.error(i,"[Virid Container] Activation Hook Failed"),t}},e)}bindController(e){return this.container.bind(e).toSelf(),{inSingletonScope:c(()=>({onActivation:c(()=>{},"onActivation")}),"inSingletonScope")}}bindComponent(e){return this.container.bind(e).toSelf().inSingletonScope(),{onActivation:c(()=>{},"onActivation")}}useMiddleware(e,t=!1){this.messageInternal.useMiddleware(e,t)}onBeforeExecute(e,t,s=!1){this.messageInternal.onBeforeExecute(e,t,s)}onAfterExecute(e,t,s=!1){this.messageInternal.onAfterExecute(e,t,s)}onBeforeTick(e,t=!1){this.messageInternal.onBeforeTick(e,t)}onAfterTick(e,t=!1){this.messageInternal.onAfterTick(e,t)}register(e,t,s=0){return this.messageInternal.register(e,t,s)}use(e,t){if(Ke.has(e.name))return p.warn(`[Virid Plugin] Duplicate Installation: Plugin ${e.name} has already been installed.`),this;try{e.install(this,t),Ke.add(e.name)}catch(s){p.error(s,`[Virid Plugin]: Install Failed: ${e.name}`)}return this}},n(L,"ne"),L);c(ft,"ViridApp");var Bt=ft,X=new Bt;X.addActivationHook(ne);pt(X);var b={SYSTEM:"virid:core:system",MESSAGE:"virid:core:message",CONTROLLER:"virid:core:controller",COMPONENT:"virid:core:component",SAFE:"virid:core:safe",OBSERVER:"virid:core:observer"},se=c(r=>{r&&(Array.isArray(r)?r:[r]).forEach(e=>{e instanceof ie?p.write(e):p.warn("[Virid HandleResult] Invalid Return Type: Must return Message or Message[].")})},"handleResult");function Nt(r={priority:0,messageClass:null}){return(e,t,s)=>{let i=s.value,o=Reflect.getMetadata("design:paramtypes",e,t),a=Reflect.getMetadata(b.MESSAGE,e,t)||null;if(!o){let g=new Error(`[Virid System] System Parameter Loss:
|
|
29
|
+
Unable to recognize system parameters, please confirm if import "reflection-metadata" was introduced at the beginning!`);p.error(g);return}if(o.some(g=>g===void 0)){let g=new Error(`[Virid System] Parameter Metadata Loss in "${t}":
|
|
30
30
|
One or more parameters have 'undefined' types.
|
|
31
31
|
This usually happens when you forget to add a type annotation to a decorated parameter.
|
|
32
|
-
Check parameter at index: ${o.indexOf(void 0)}`);
|
|
33
|
-
Please declare the message type using the Message decorator`));return}let d=c(
|
|
32
|
+
Check parameter at index: ${o.indexOf(void 0)}`);p.error(g);return}if(r.messageClass&&a){p.error(new Error(`[Virid System] Multiple Messages Are Not Allowed: Cannot use @ message() and SystemParams simultaneously in ${t}`));return}if(!r.messageClass&&!a){p.error(new Error(`[Virid System] System Parameter Loss:
|
|
33
|
+
Please declare the message type using the Message decorator`));return}let d=c(g=>{let E=o.map((x,A)=>{if(a&&a.index==A){let{messageClass:$,single:ue}=a,Z=Array.isArray(g)?g[0]:g;if(!(Z instanceof $)){let Et=Z.constructor.name;throw new Error(`[Virid System] Type Mismatch: Expected ${$.name}, but received ${Et}`)}if(Z instanceof ae)return ue?Array.isArray(g)?g[g.length-1]:g:Array.isArray(g)?g:[g];if(Z instanceof R)return g;throw new Error(`[Virid System] unknown Message Types: Message ${$.name} is not a subclass of SingleMessage or EventMessage!`)}let k=X.get(x);if(!k)throw new Error(`[Virid System] unknown Inject Data Types: ${x.name} is not registered in the container!`);return k}),w=i.apply(e,E);return w instanceof Promise?w.then(se):se(w)},"wrappedSystem"),f={params:o,targetClass:e,methodName:t,originalMethod:i};d.systemContext=f,s.value=d;let u=r.messageClass||a.messageClass;X.register(u,d,r.priority)}}n(Nt,"ft");c(Nt,"System");function qt(r,e=!0){return(t,s,i)=>{if(Reflect.hasOwnMetadata(b.MESSAGE,t,s)){p.error(new Error(`[Virid Message] Multiple Messages Are Not Allowed: ${s} has multiple @Message() decorators!`));return}let o={index:i,messageClass:r,single:e};Reflect.defineMetadata(b.MESSAGE,o,t,s)}}n(qt,"pt");c(qt,"Message");function jt(){return(r,e,t)=>{let s=Reflect.getMetadata(b.SAFE,r)||new Set;s.add(e),Reflect.defineMetadata(b.SAFE,s,r)}}n(jt,"gt");c(jt,"Safe");function Qt(r,[]){return(e,t)=>{let s=Reflect.getMetadata(b.OBSERVER,e)||[];s.push({key:t,callback:r}),Reflect.defineMetadata(b.OBSERVER,s,e)}}n(Qt,"mt");c(Qt,"Observer");function _t(){return r=>{Reflect.defineMetadata(b.CONTROLLER,!0,r)}}n(_t,"yt");c(_t,"Controller");function Ft(){return r=>{Reflect.defineMetadata(b.COMPONENT,!0,r)}}n(Ft,"xt");c(Ft,"Component");var Wt=["push","pop","shift","unshift","splice","sort","reverse"];function ne(r){return!r||typeof r!="object"||Object.prototype.hasOwnProperty.call(r,"__virid_observer_processed__")||(Object.defineProperty(r,"__virid_observer_processed__",{value:!0,enumerable:!1,configurable:!0}),(Reflect.getMetadata(b.OBSERVER,r.constructor)||[]).forEach(({propertyKey:e,callback:t})=>{let s={value:r[e]},i=new Proxy(s,{get(a,d){let f=a.value;return Array.isArray(f)&&Wt.includes(d)?(...u)=>{let g=[...f],E=f[d].apply(f,u),w=t.call(r,g,f);return se(w),E}:f},set(a,d,f){let u=a.value;if(f===u)return!0;a.value=f;let g=t.call(r,u,f);return se(g),!0}}),o=c(()=>i.value,"getter");o.__virid_box__=s,Object.defineProperty(r,e,{get:o,set:c(a=>{i.value=a},"set"),enumerable:!0,configurable:!0}),s.value&&typeof s.value=="object"&&ne(s.value)}),Reflect.ownKeys(r).forEach(e=>{if(e==="__virid_observer_processed__")return;let t=Object.getOwnPropertyDescriptor(r,e);if(t&&t.get)return;let s=r[e];s&&typeof s=="object"&&ne(s)})),r}n(ne,"_");c(ne,"bindObservers");function Ut(){return X}n(Ut,"It");c(Ut,"createVirid");function Lt(r){let e=parseInt(r,10);if(isNaN(e))throw new C(400,`Validation failed: "${r}" is not a number.`);return e}n(Lt,"ParseIntPipe");function Gt(r){return r==="true"||r==="1"?!0:r==="false"||r==="0"?!1:!!r}n(Gt,"ParseBoolPipe");var J=new Map;J.set(Number,Lt);J.set(Boolean,Gt);function Ar(r,e){if(J.has(r)){p.error(new Error(`[Virid Express Pipe] Repeated Pipe: Auto pipe for ${r} has already been registered.`));return}J.set(r,e)}n(Ar,"addAutoPipe");function Fe(r){return J.get(r)}n(Fe,"getAutoPipe");function gt(r){let e={};if(!r)return e;let t=r.split(";");for(let s of t){let i=s.indexOf("=");if(i===-1)continue;let o=s.substring(0,i).trim();if(!o)continue;let a=s.substring(i+1).trim();a[0]==='"'&&a[a.length-1]==='"'&&(a=a.slice(1,-1));try{e[o]=a.includes("%")?decodeURIComponent(a):a}catch{e[o]=a}}return e}n(gt,"parseRawCookie");import{EventMessage as zt}from"@virid/core";var We=class We extends zt{constructor(t){super();y(this,"__virid_express_id");this.__virid_express_id=t,v.get(this.__virid_express_id).inc()}get requestId(){return this.__virid_express_id}};n(We,"HttpRequestMessage");var oe=We;var ce=new Yt,le=new Map,Xt=0;function mt(r){for(let[e,t]of ce.systemTaskMap.entries())for(let s of t)r.register(e,s.fn,s.priority);ce.systemTaskMap.clear()}n(mt,"registerHttpSystem");function yt(r){for(let[e,t]of le.entries()){let{method:s,path:i,httpMessage:o}=t,a=s.toLowerCase();r[a](i,(d,f)=>{let u=Xt++>>>0;v.set(u,new ee(u,d,f,Date.now(),i));let g=new o(u);f.once("finish",()=>v.delete(u)),f.once("close",()=>v.delete(u)),Kt.write(g)})}}n(yt,"registerHttpRoute");var de=null;function xt(r,e){de=r,mt(r),yt(e.server)}n(xt,"activateApp");var Mt=new Proxy({},{get(r,e){return(...t)=>{if(!de)return Jt.warn(`[Virid Vue] App method "${String(e)}" called before initialization.`),null;let s=de[e];if(typeof s=="function")return s.apply(de,t)}}});import{MessageWriter as S}from"@virid/core";import{VIRID_METADATA as Zt}from"@virid/core";var m={...Zt,HTTPROUTE:"virid:express:route",HTTPSYSTEM:"virid:express:system",BODY:"virid:express:body",QUERY:"virid:express:query",HEADERS:"virid:express:header",REQUEST:"virid:express:request",RESPONSE:"virid:express:response",CONTEXT:"virid:express:context",PARAMS:"virid:express:params",COOKIES:"virid:express:cookie"};function es(r){return e=>{let t=`${r.method}:${r.path}`;le.has(t)&&S.error(new Error(`[Virid Http] Routing Conflict: The request method ${r.method} for path ${r.path} has already been registered by ${e.name}`));let s=[];r.path.split("/").forEach(a=>{a.startsWith(":")&&s.push(a.substring(1))});let o={...r,httpMessage:e,params:s};le.set(t,o)}}n(es,"HttpRoute");function ts(r={priority:0,messageClass:null}){return(e,t,s)=>{let i=s.value,o=Reflect.getMetadata("design:paramtypes",e,t),a=Reflect.getMetadata(m.MESSAGE,e,t)||null,d=er(e,t,o);if(!o){let E=new Error(`[Virid HttpSystem] System Parameter Loss:
|
|
34
34
|
Unable to recognize system parameters, please confirm if import "reflection-metadata" was introduced at the beginning!`);S.error(E);return}if(o.some(E=>E===void 0)){let E=new Error(`[Virid HttpSystem] Parameter Metadata Loss in "${t}":
|
|
35
35
|
One or more parameters have 'undefined' types.
|
|
36
36
|
This usually happens when you forget to add a type annotation to a decorated parameter.
|
|
37
37
|
Check parameter at index: ${o.indexOf(void 0)}`);S.error(E);return}if(r.messageClass&&a){S.error(new Error(`[Virid HttpSystem] Multiple Messages Are Not Allowed: Cannot use @ message() and SystemParams simultaneously in ${t}`));return}if(!r.messageClass&&!a){S.error(new Error(`[Virid HttpSystem] System Parameter Loss:
|
|
38
|
-
Please declare the message type using the Message decorator`));return}let
|
|
39
|
-
Ensure it is registered in the IOC container or has a proper Http Decorator!`);return
|
|
38
|
+
Please declare the message type using the Message decorator`));return}let f=r.messageClass??a.messageClass;if(!oe.isPrototypeOf(f)){S.error(new Error(`[Virid HttpSystem] Wrong Message Type: ${f.name} is not a derived subclass of HttpRequestMessage!`));return}let u=n(E=>{let w=v.get(E.requestId);if(!w)throw new Error(`[Virid Express HttpSystem] Invalid Request Context: The request context for message ${E.requestId} is missing.`);try{let x=o.map((k,$)=>{if(a&&a.index==$){if(!(E instanceof f)){let ue=E.constructor.name;throw new Error(`[Virid Express HttpSystem] Type Mismatch: Expected ${f.name}, but received ${ue}`)}return E}else return tr(k,$,w,d)}),A=i.apply(e,x);return A instanceof Promise?A.then(k=>{T(k,w)}).catch(k=>{throw T(we(),w),k}):T(A,w)}catch(x){throw x instanceof C?T(x,w):T(we(),w),x}},"wrappedSystem"),g={params:o,targetClass:e,methodName:t,originalMethod:i};u.systemContext=g,s.value=u,ce.register(f,u,r.priority)}}n(ts,"HttpSystem");function rs(){return(r,e,t)=>{if(Reflect.hasOwnMetadata(m.BODY,r,e)){S.error(new Error(`[Virid Express Body] Multiple Body Are Not Allowed: ${e} has multiple @Body() decorators!`));return}let s={index:t};Reflect.defineMetadata(m.BODY,s,r,e)}}n(rs,"Body");function ss(){return(r,e,t)=>{if(Reflect.hasOwnMetadata(m.HEADERS,r,e)){S.error(new Error(`[Virid Express Headers] Multiple Header Are Not Allowed: ${e} has multiple @Headers() decorators!`));return}let s={index:t};Reflect.defineMetadata(m.HEADERS,s,r,e)}}n(ss,"Headers");function ns(){return(r,e,t)=>{if(Reflect.hasOwnMetadata(m.COOKIES,r,e)){S.error(new Error(`[Virid Express Cookies] Multiple Header Are Not Allowed: ${e} has multiple @Cookies() decorators!`));return}let s={index:t};Reflect.defineMetadata(m.COOKIES,s,r,e)}}n(ns,"Cookies");function is(){return(r,e,t)=>{if(Reflect.hasOwnMetadata(m.REQUEST,r,e)){S.error(new Error(`[Virid Express Req] Multiple Request Objects Are Not Allowed: ${e} has multiple @Req() decorators!`));return}let s={index:t};Reflect.defineMetadata(m.REQUEST,s,r,e)}}n(is,"Req");function as(){return(r,e,t)=>{if(Reflect.hasOwnMetadata(m.RESPONSE,r,e)){S.error(new Error(`[Virid Express Res] Multiple Response Objects Are Not Allowed: ${e} has multiple @Res() decorators!`));return}let s={index:t};Reflect.defineMetadata(m.RESPONSE,s,r,e)}}n(as,"Res");function os(){return(r,e,t)=>{if(Reflect.hasOwnMetadata(m.CONTEXT,r,e)){S.error(new Error(`[Virid Express Ctx] Multiple Context Objects Are Not Allowed: ${e} has multiple @Ctx() decorators!`));return}let s={index:t};Reflect.defineMetadata(m.CONTEXT,s,r,e)}}n(os,"Ctx");function cs(r,e){return(t,s,i)=>{let a=[...Reflect.getOwnMetadata(m.QUERY,t,s)||[],{index:i,query:r,pipe:e}];Reflect.defineMetadata(m.QUERY,a,t,s)}}n(cs,"Query");function ls(r,e){return(t,s,i)=>{let a=[...Reflect.getOwnMetadata(m.PARAMS,t,s)||[],{index:i,key:r,pipe:e}];Reflect.defineMetadata(m.PARAMS,a,t,s)}}n(ls,"Params");function er(r,e,t){let s=Reflect.getOwnMetadata(m.BODY,r,e),i=Reflect.getOwnMetadata(m.HEADERS,r,e),o=Reflect.getOwnMetadata(m.COOKIES,r,e),a=Reflect.getOwnMetadata(m.RESPONSE,r,e),d=Reflect.getOwnMetadata(m.REQUEST,r,e),f=Reflect.getOwnMetadata(m.CONTEXT,r,e),g=(Reflect.getOwnMetadata(m.QUERY,r,e)||[]).map(x=>{if(!x.pipe){let A=t[x.index];x.pipe=Fe(A)}return x}),w=(Reflect.getOwnMetadata(m.PARAMS,r,e)||[]).map(x=>{if(!x.pipe){let A=t[x.index];x.pipe=Fe(A)}return x});return{bodyMeta:s,headerMeta:i,queryMeta:g,cookiesMeta:o,reqMeta:d,resMeta:a,ctxMeta:f,paramMeta:w}}n(er,"getHttpMetadata");function tr(r,e,t,s){let{req:i,res:o}=t;if(s.ctxMeta?.index===e)return t;let a=s.paramMeta?.find(u=>u.index===e);if(a){let u=a.key?i.params[a.key]:i.params;return a.pipe&&u!==void 0&&(u=a.pipe(u)),u}if(s.bodyMeta?.index===e)return i.body;if(s.headerMeta?.index===e)return i.headers;if(s.cookiesMeta?.index===e)return gt(i.headers.cookie);if(s.reqMeta?.index===e)return i;if(s.resMeta?.index===e)return o;let d=s.queryMeta?.find(u=>u.index===e);if(d){let u=i.query[d.query];if(u===void 0)throw new Error(`[Virid Express] Missing Query: "${d.query}"`);return d.pipe&&(u=d.pipe(u)),u}let f=Mt.get(r);if(!f)throw new Error(`[Virid System] Unknown Inject Type: ${r?.name||"Anonymous Class"} at index ${e}.
|
|
39
|
+
Ensure it is registered in the IOC container or has a proper Http Decorator!`);return f}n(tr,"getHttpSystemArgs");var gs={name:"@virid/express",install(r,e){xt(r,e)}};export{or as BadRequest,ge as BadRequestResponse,rs as Body,Le as ConflictResponse,ns as Cookies,ir as Created,pe as CreatedResponse,os as Ctx,ur as CustomResponse,Ee as CustomResponseResponse,gs as ExpressPlugin,lr as Forbidden,ye as ForbiddenResponse,ss as Headers,ee as HttpContext,C as HttpError,oe as HttpRequestMessage,M as HttpResponse,es as HttpRoute,ts as HttpSystem,we as InternalServerError,Me as InternalServerErrorResponse,ar as NoContent,fe as NoContentResponse,dr as NotFound,xe as NotFoundResponse,nr as Ok,he as OkResponse,ls as Params,Gt as ParseBoolPipe,Lt as ParseIntPipe,cs as Query,is as Req,as as Res,pr as Stream,hr as StreamFile,G as StreamFileResponse,z as StreamResponse,cr as Unauthorized,me as UnauthorizedResponse,Ge as UnprocessableEntityResponse,Ar as addAutoPipe,Fe as getAutoPipe,gt as parseRawCookie};
|
|
40
40
|
//# sourceMappingURL=index.js.map
|