@virid/core 0.2.3 → 0.3.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.cjs +11 -23
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +122 -128
- package/dist/index.d.ts +122 -128
- package/dist/index.js +11 -23
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,170 +1,139 @@
|
|
|
1
1
|
type Newable<TInstance = unknown, TArgs extends unknown[] = any[]> = new (...args: TArgs) => TInstance;
|
|
2
2
|
interface AppConfig {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
enableLog: boolean;
|
|
7
|
-
};
|
|
8
|
-
|
|
9
|
-
interface SystemParams {
|
|
10
|
-
priority?: number;
|
|
11
|
-
messageClass?: Newable<BaseMessage> | null;
|
|
12
|
-
}
|
|
13
|
-
interface MessageMetadata {
|
|
14
|
-
index: number;
|
|
15
|
-
messageClass: Newable<BaseMessage>;
|
|
16
|
-
single: boolean;
|
|
17
|
-
}
|
|
18
|
-
interface ObserverItem {
|
|
19
|
-
propertyKey: string;
|
|
20
|
-
callback: (oldVal: any, newVal: any) => void | BaseMessage | BaseMessage;
|
|
21
|
-
}
|
|
22
|
-
type ObserverMetadata = ObserverItem[];
|
|
23
|
-
type SafeMetadata = Set<string>;
|
|
24
|
-
|
|
25
|
-
type Middleware = (message: BaseMessage, next: () => void) => void;
|
|
26
|
-
type ExecuteHook<T extends BaseMessage> = (message: [BaseMessage] extends [T] ? SingleMessage[] | EventMessage : T extends SingleMessage ? T[] : T, context: ExecuteHookContext) => void | Promise<void>;
|
|
27
|
-
interface ExecuteHookContext {
|
|
28
|
-
context: SystemContext;
|
|
29
|
-
tick: number;
|
|
30
|
-
payload: {
|
|
31
|
-
[key: string]: any;
|
|
32
|
-
};
|
|
33
|
-
}
|
|
34
|
-
interface SystemContext {
|
|
35
|
-
params: any[];
|
|
36
|
-
targetClass: any;
|
|
37
|
-
methodName: string;
|
|
38
|
-
originalMethod: (...args: any[]) => any;
|
|
39
|
-
}
|
|
40
|
-
interface SystemTask {
|
|
41
|
-
fn: (...args: any[]) => any;
|
|
42
|
-
priority: number;
|
|
43
|
-
}
|
|
44
|
-
type MessagePayload<T> = T extends SingleMessage ? T[] : T extends EventMessage ? T : T | T[];
|
|
45
|
-
type MessageIdentifier<T> = (abstract new (...args: any[]) => T) | Newable<T>;
|
|
46
|
-
type TickHook = (context: TickHookContext) => void | Promise<void>;
|
|
47
|
-
interface TickHookContext {
|
|
48
|
-
tick: number;
|
|
49
|
-
timestamp: number;
|
|
50
|
-
payload: {
|
|
51
|
-
[key: string]: any;
|
|
52
|
-
};
|
|
3
|
+
maxDepth?: number;
|
|
4
|
+
enableLog?: boolean;
|
|
5
|
+
manual?: boolean;
|
|
53
6
|
}
|
|
7
|
+
declare const defaultConfig: AppConfig;
|
|
54
8
|
|
|
55
9
|
declare abstract class BaseMessage {
|
|
56
10
|
static send<T extends Newable<any>>(this: T, ...args: ConstructorParameters<T>): void;
|
|
57
11
|
}
|
|
58
|
-
/**
|
|
59
|
-
* 可合并的信号基类
|
|
60
|
-
*/
|
|
61
12
|
declare abstract class SingleMessage extends BaseMessage {
|
|
62
|
-
private readonly __kind;
|
|
63
13
|
constructor();
|
|
64
14
|
}
|
|
65
|
-
/**
|
|
66
|
-
* 不可合并的消息基类
|
|
67
|
-
*/
|
|
68
15
|
declare abstract class EventMessage extends BaseMessage {
|
|
69
|
-
private readonly __kind;
|
|
70
16
|
constructor();
|
|
71
17
|
}
|
|
72
|
-
/**
|
|
73
|
-
* 基础错误消息:不可合并,必须被精准捕获
|
|
74
|
-
*/
|
|
75
18
|
declare class ErrorMessage extends EventMessage {
|
|
76
19
|
readonly error: Error;
|
|
77
20
|
readonly context?: string | undefined;
|
|
78
21
|
constructor(error: Error, context?: string | undefined);
|
|
79
22
|
}
|
|
80
|
-
/**
|
|
81
|
-
* 基础警告消息:不可合并,必须被精准捕获
|
|
82
|
-
*/
|
|
83
23
|
declare class WarnMessage extends EventMessage {
|
|
84
24
|
readonly context: string;
|
|
85
25
|
constructor(context: string);
|
|
86
26
|
}
|
|
87
|
-
/**
|
|
88
|
-
* 基础信息消息:不可合并,必须被精准捕获
|
|
89
|
-
*/
|
|
90
27
|
declare class InfoMessage extends EventMessage {
|
|
91
28
|
readonly context: string;
|
|
92
29
|
constructor(context: string);
|
|
93
30
|
}
|
|
94
31
|
|
|
95
|
-
declare class
|
|
96
|
-
private eventHub;
|
|
32
|
+
declare class MessageEngine {
|
|
97
33
|
private dispatcher;
|
|
98
34
|
private registry;
|
|
99
35
|
private middlewares;
|
|
100
|
-
|
|
36
|
+
private manual;
|
|
37
|
+
constructor(maxDepth: number, manual: boolean);
|
|
101
38
|
useMiddleware(mw: Middleware, front: boolean): void;
|
|
102
39
|
onBeforeExecute<T extends BaseMessage>(type: MessageIdentifier<T>, hook: ExecuteHook<T>, front: boolean): void;
|
|
103
40
|
onAfterExecute<T extends BaseMessage>(type: MessageIdentifier<T>, hook: ExecuteHook<T>, front: boolean): void;
|
|
104
41
|
onBeforeTick(hook: TickHook, front: boolean): void;
|
|
105
42
|
onAfterTick(hook: TickHook, front: boolean): void;
|
|
106
|
-
|
|
107
|
-
* 消息进入系统的唯一入口
|
|
108
|
-
*/
|
|
43
|
+
tick(): void;
|
|
109
44
|
dispatch(message: BaseMessage): void;
|
|
110
45
|
private pipeline;
|
|
111
46
|
register(messageClass: any, systemFn: (...args: any[]) => any, priority?: number): () => void;
|
|
112
47
|
}
|
|
113
48
|
|
|
114
|
-
/**
|
|
115
|
-
* @description: 消息注册器 - 负责将系统函数或监听器与消息类型关联
|
|
116
|
-
*/
|
|
117
49
|
declare class MessageRegistry {
|
|
118
50
|
systemTaskMap: Map<any, SystemTask[]>;
|
|
119
51
|
/**
|
|
120
|
-
*
|
|
121
|
-
* 这种模式能完美适配 Controller 的生命周期销毁
|
|
52
|
+
* Register the message and corresponding system and return an uninstallation function
|
|
122
53
|
*/
|
|
123
54
|
register(messageClass: any, systemFn: (...args: any[]) => any, priority?: number): () => void;
|
|
124
55
|
}
|
|
125
56
|
|
|
126
|
-
|
|
127
|
-
dispatch(message: BaseMessage): void;
|
|
128
|
-
}
|
|
129
|
-
declare function activateInstance(instance: MessageInternal): void;
|
|
130
|
-
declare const publisher: IMessagePublisher;
|
|
57
|
+
declare function activateInstance(instance: MessageEngine): void;
|
|
131
58
|
declare class MessageWriter {
|
|
132
|
-
/**
|
|
133
|
-
* 核心入口:无论是类还是实例,统一交给 Internal 处理
|
|
134
|
-
*/
|
|
135
59
|
static write<T extends BaseMessage, K extends Newable<T>>(target: K | T, ...args: ConstructorParameters<K>): void;
|
|
136
|
-
/**
|
|
137
|
-
* 快捷方式:系统内部常用
|
|
138
|
-
*/
|
|
139
60
|
static error(e: Error, context?: string): void;
|
|
140
61
|
static warn(context: string): void;
|
|
141
62
|
static info(context: string): void;
|
|
142
63
|
}
|
|
143
64
|
|
|
144
|
-
|
|
65
|
+
interface SystemParams {
|
|
66
|
+
priority?: number;
|
|
67
|
+
messageClass?: Newable<BaseMessage> | null;
|
|
68
|
+
}
|
|
69
|
+
interface MessageMetadata {
|
|
70
|
+
index: number;
|
|
71
|
+
messageClass: Newable<BaseMessage>;
|
|
72
|
+
single: boolean;
|
|
73
|
+
}
|
|
74
|
+
interface ObserverItem {
|
|
75
|
+
propertyKey: string;
|
|
76
|
+
callback: (oldVal: any, newVal: any) => void | BaseMessage | BaseMessage;
|
|
77
|
+
}
|
|
78
|
+
type ObserverMetadata = ObserverItem[];
|
|
79
|
+
type SafeMetadata = Set<string>;
|
|
80
|
+
|
|
81
|
+
type Middleware = (message: BaseMessage, next: () => void) => void;
|
|
82
|
+
type ExecuteHook<T extends BaseMessage> = (message: [BaseMessage] extends [T] ? SingleMessage[] | EventMessage : T extends SingleMessage ? T[] : T, context: ExecuteHookContext, success: boolean) => void | Promise<void>;
|
|
83
|
+
interface ExecuteHookContext {
|
|
84
|
+
context: SystemContext;
|
|
85
|
+
tick: number;
|
|
86
|
+
payload: {
|
|
87
|
+
[key: string]: any;
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
interface SystemContext {
|
|
91
|
+
params: any[];
|
|
92
|
+
targetClass: any;
|
|
93
|
+
methodName: string;
|
|
94
|
+
originalMethod: (...args: any[]) => any;
|
|
95
|
+
}
|
|
96
|
+
interface SystemConfig {
|
|
97
|
+
priority: number;
|
|
98
|
+
messageClass: Newable<BaseMessage>;
|
|
99
|
+
messageIdx: number;
|
|
100
|
+
batchMode: boolean;
|
|
101
|
+
}
|
|
102
|
+
interface SystemTask {
|
|
103
|
+
fn: (...args: any[]) => any;
|
|
104
|
+
priority: number;
|
|
105
|
+
}
|
|
106
|
+
type MessagePayload<T> = T extends SingleMessage ? T[] : T extends EventMessage ? T : T | T[];
|
|
107
|
+
type MessageIdentifier<T> = (abstract new (...args: any[]) => T) | Newable<T>;
|
|
108
|
+
type TickHook = (context: TickHookContext) => void | Promise<void>;
|
|
109
|
+
interface TickHookContext {
|
|
110
|
+
tick: number;
|
|
111
|
+
timestamp: number;
|
|
112
|
+
payload: {
|
|
113
|
+
[key: string]: any;
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
declare function handleResult(res: any): void;
|
|
145
118
|
/**
|
|
146
|
-
*
|
|
147
|
-
* @param
|
|
119
|
+
* System Decorator
|
|
120
|
+
* @param params Priority and MessageClass config
|
|
148
121
|
*/
|
|
149
122
|
declare function System(params?: SystemParams): (target: any, key: string, descriptor: PropertyDescriptor) => void;
|
|
150
123
|
/**
|
|
151
|
-
*
|
|
152
|
-
*/
|
|
153
|
-
declare function Message<T extends BaseMessage>(messageClass: Newable<T>, single?: boolean): (target: any, key: string, index: number) => void;
|
|
154
|
-
/**
|
|
155
|
-
* @description: 标识controller或者组件的方法是否是安全的,可被其他controller直接调用
|
|
124
|
+
* Is the method used to identify the controller or component safe and can be directly called by other controllers
|
|
156
125
|
*/
|
|
157
126
|
declare function Safe(): (target: any, key: string, _descriptor: PropertyDescriptor) => void;
|
|
158
127
|
/**
|
|
159
|
-
*
|
|
128
|
+
* Observer Decorator
|
|
160
129
|
*/
|
|
161
130
|
declare function Observer(callback: (oldVal: any, newVale: any) => void | BaseMessage | BaseMessage[]): (target: any, propertyKey: string) => void;
|
|
162
131
|
/**
|
|
163
|
-
*
|
|
132
|
+
* Controller Decorator
|
|
164
133
|
*/
|
|
165
134
|
declare function Controller(): (target: any) => void;
|
|
166
135
|
/**
|
|
167
|
-
*
|
|
136
|
+
* Component Decorator
|
|
168
137
|
*/
|
|
169
138
|
declare function Component(): (target: any) => void;
|
|
170
139
|
|
|
@@ -182,53 +151,78 @@ declare const VIRID_METADATA: {
|
|
|
182
151
|
declare class ViridContainer {
|
|
183
152
|
private bindings;
|
|
184
153
|
private singletonInstances;
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
154
|
+
private activationHooks;
|
|
155
|
+
/**
|
|
156
|
+
* Register an activation hook
|
|
157
|
+
* @param hook An activation hook
|
|
158
|
+
* @param front Is the hook order inserted from the front or added
|
|
159
|
+
*/
|
|
160
|
+
addActivationHook(hook: (instance: any) => any, front: boolean): void;
|
|
161
|
+
/**
|
|
162
|
+
* Static binding component or controller
|
|
163
|
+
* @param identifier Constructor of components or controllers
|
|
164
|
+
*/
|
|
165
|
+
bind<T>(identifier: Newable<T>): void;
|
|
166
|
+
/**
|
|
167
|
+
* Dynamically register a component
|
|
168
|
+
* @param instance Component instance
|
|
169
|
+
*/
|
|
170
|
+
spawn(instance: object): void;
|
|
171
|
+
/**
|
|
172
|
+
* Obtain a Component or Controller instance
|
|
173
|
+
* @param identifier Constructor of components or controllers
|
|
174
|
+
*/
|
|
175
|
+
get<T>(identifier: Newable<T>): T;
|
|
176
|
+
private handleActivation;
|
|
193
177
|
}
|
|
194
178
|
|
|
195
|
-
interface ViridPlugin<T =
|
|
179
|
+
interface ViridPlugin<T = any> {
|
|
196
180
|
name: string;
|
|
197
181
|
install: (app: ViridApp, options: T) => void;
|
|
198
182
|
}
|
|
199
|
-
/**
|
|
200
|
-
* 创建 virid 核心实例
|
|
201
|
-
*/
|
|
202
183
|
declare class ViridApp {
|
|
203
184
|
container: ViridContainer;
|
|
204
|
-
|
|
205
|
-
private
|
|
206
|
-
|
|
185
|
+
engine: MessageEngine;
|
|
186
|
+
private installedPlugins;
|
|
187
|
+
constructor(maxDepth: number, manual: boolean);
|
|
188
|
+
/**
|
|
189
|
+
* Register an activation hook
|
|
190
|
+
* @param hook An activation hook
|
|
191
|
+
* @param front Is the hook order inserted from the front or added
|
|
192
|
+
*/
|
|
193
|
+
onActivate(hook: (instance: any) => any, front?: boolean): void;
|
|
194
|
+
/**
|
|
195
|
+
* Opening a new tick
|
|
196
|
+
*/
|
|
197
|
+
tick(): void;
|
|
198
|
+
/**
|
|
199
|
+
* Obtain a Component or Controller instance
|
|
200
|
+
* @param identifier Constructor of components or controllers
|
|
201
|
+
*/
|
|
207
202
|
get<T>(identifier: Newable<T>): T;
|
|
208
|
-
private handleActivation;
|
|
209
203
|
/**
|
|
210
|
-
*
|
|
204
|
+
* Static binding component or controller
|
|
205
|
+
* @param identifier Constructor of components or controllers
|
|
211
206
|
*/
|
|
212
|
-
|
|
213
|
-
inSingletonScope: () => {
|
|
214
|
-
onActivation: () => void;
|
|
215
|
-
};
|
|
216
|
-
};
|
|
207
|
+
bind<T>(identifier: Newable<T>): void;
|
|
217
208
|
/**
|
|
218
|
-
*
|
|
209
|
+
* Dynamically register a component
|
|
210
|
+
* @param instance Component instance
|
|
219
211
|
*/
|
|
220
|
-
|
|
221
|
-
onActivation: () => void;
|
|
222
|
-
};
|
|
212
|
+
spawn(instance: object): void;
|
|
223
213
|
useMiddleware(mw: Middleware, front?: boolean): void;
|
|
224
214
|
onBeforeExecute<T extends BaseMessage>(type: MessageIdentifier<T>, hook: ExecuteHook<T>, front?: boolean): void;
|
|
225
215
|
onAfterExecute<T extends BaseMessage>(type: MessageIdentifier<T>, hook: ExecuteHook<T>, front?: boolean): void;
|
|
226
216
|
onBeforeTick(hook: TickHook, front?: boolean): void;
|
|
227
217
|
onAfterTick(hook: TickHook, front?: boolean): void;
|
|
228
|
-
register(messageClass: any, systemFn: (...args: any[]) => any, priority?: number): () => void;
|
|
229
218
|
use<T>(plugin: ViridPlugin<T>, options: T): this;
|
|
219
|
+
/**
|
|
220
|
+
* Register message to registrar
|
|
221
|
+
* @param systemFn System functions
|
|
222
|
+
*/
|
|
223
|
+
register(systemFn: (...args: any[]) => any): () => void;
|
|
230
224
|
}
|
|
231
225
|
|
|
232
226
|
declare function createVirid(config?: AppConfig): ViridApp;
|
|
233
227
|
|
|
234
|
-
export { type AppConfig, BaseMessage, Component, Controller, ErrorMessage, EventMessage, type ExecuteHook, type ExecuteHookContext,
|
|
228
|
+
export { type AppConfig, BaseMessage, Component, Controller, ErrorMessage, EventMessage, type ExecuteHook, type ExecuteHookContext, InfoMessage, MessageEngine, type MessageIdentifier, type MessageMetadata, type MessagePayload, MessageRegistry, MessageWriter, type Middleware, type Newable, Observer, type ObserverItem, type ObserverMetadata, Safe, type SafeMetadata, SingleMessage, System, type SystemConfig, type SystemContext, type SystemParams, type SystemTask, type TickHook, type TickHookContext, VIRID_METADATA, ViridApp, type ViridPlugin, WarnMessage, activateInstance, bindObservers, createVirid, defaultConfig, handleResult };
|
package/dist/index.js
CHANGED
|
@@ -1,29 +1,17 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @virid/core v0.
|
|
2
|
+
* @virid/core v0.3.0
|
|
3
3
|
* A lightweight and powerful message core built using dependency injection and CCS concepts
|
|
4
4
|
*/
|
|
5
|
-
var
|
|
5
|
+
var ce=Object.defineProperty;var ge=(r,e,t)=>e in r?ce(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var o=(r,e)=>ce(r,"name",{value:e,configurable:!0});var a=(r,e,t)=>ge(r,typeof e!="symbol"?e+"":e,t);var z={maxDepth:100,enableLog:!0,manual:!1};var F=null;function le(r){F=r}o(le,"activateInstance");function me(r){F?F.dispatch(r):console.error("[Virid MessageWriter] No active instance found.")}o(me,"dispatch");var J=class J{static write(e,...t){let s=typeof e=="function"?new e(...t):e;me(s)}static error(e,t=""){this.write(new v(e,t))}static warn(e){this.write(new $(e))}static info(e){this.write(new C(e))}};o(J,"MessageWriter");var d=J;var Y=class Y{static send(...e){d.write(this,...e)}};o(Y,"BaseMessage");var w=Y,q=class q extends w{constructor(){super()}};o(q,"SingleMessage");var S=q,K=class K extends w{constructor(){super()}};o(K,"EventMessage");var T=K,Q=class Q extends T{constructor(t,s){super();a(this,"error");a(this,"context");this.error=t,this.context=s}};o(Q,"ErrorMessage");var v=Q,X=class X extends T{constructor(t){super();a(this,"context");this.context=t}};o(X,"WarnMessage");var $=X,Z=class Z extends T{constructor(t){super();a(this,"context");this.context=t}};o(Z,"InfoMessage");var C=Z;var ee=class ee{constructor(){a(this,"systemTaskMap",new Map)}register(e,t,s=0){let i=this.systemTaskMap.get(e)||[];if(i.findIndex(c=>c.fn.systemContext.originalMethod===t.systemContext.originalMethod)===-1)i.push({fn:t,priority:s}),i.sort((c,l)=>l.priority-c.priority),this.systemTaskMap.set(e,i);else{let c=t.methodName,l=t.targetClass;return d.error(new Error(`[Virid Error] System Already Registered: Message Class ${e.name}, Location ${l.name}.${c}`)),()=>{}}return()=>{let c=this.systemTaskMap.get(e);if(c){let l=c.findIndex(m=>m.fn===t);l!==-1&&(c.splice(l,1),c.length===0&&this.systemTaskMap.delete(e))}}}};o(ee,"MessageRegistry");var I=ee;var te=class te{constructor(){a(this,"signalActive",new Map);a(this,"eventActive",[]);a(this,"signalStaging",new Map);a(this,"eventStaging",[])}stage(e){if(e instanceof S){let t=e.constructor;this.signalStaging.has(t)||this.signalStaging.set(t,[]),this.signalStaging.get(t).push(e)}else e instanceof T?this.eventStaging.push(e):d.error(new Error(`[Virid Message] Invalid Message:
|
|
6
|
+
${e.constructor.name} must extend SingleMessage or EventMessage`))}flip(){this.signalActive=this.signalStaging,this.eventActive=this.eventStaging,this.signalStaging=new Map,this.eventStaging=[]}clearSignals(){this.signalActive=new Map}clearEvents(){this.eventActive=[]}isEmpty(){return this.signalStaging.size===0&&this.eventStaging.length===0}reset(){this.signalActive=new Map,this.signalStaging=new Map,this.eventStaging=[],this.eventActive=[]}};o(te,"Staging");var N=te;var se=class se{constructor(e){a(this,"maxDepth");a(this,"isRunning",!1);a(this,"globalTick",0);a(this,"internalDepth",0);a(this,"staging",new N);a(this,"tickPayload",{});a(this,"beforeExecuteHooks",[]);a(this,"afterExecuteHooks",[]);a(this,"beforeTickHooks",[]);a(this,"afterTickHooks",[]);this.maxDepth=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)}stage(e){this.staging.stage(e)}tick(e){if(!(this.isRunning||this.staging.isEmpty())){if(this.internalDepth>this.maxDepth){this.internalDepth=0,this.staging.reset(),console.error(new Error(`[Virid Dispatcher] Deadlock: Max depth reached ${this.maxDepth}, Possible infinite loop detected. The dispatcher will stop processing this tick.`));return}this.isRunning=!0,this.internalDepth++,queueMicrotask(()=>{try{this.internalDepth==1&&(this.tickPayload={},this.executeTickHooks(this.beforeTickHooks)),this.staging.flip();let t=this.collectTasks(e);this.executeTasks(t)}catch(t){d.error(t,"[Virid Dispatcher] Unhandled Error")}finally{this.isRunning=!1,this.staging.isEmpty()?(this.staging.reset(),this.internalDepth=0,this.executeTickHooks(this.afterTickHooks),this.globalTick++):this.tick(e)}})}}tickSync(e){if(!this.staging.isEmpty()){for(this.internalDepth=0,this.tickPayload={},this.executeTickHooks(this.beforeTickHooks);!this.staging.isEmpty();){if(this.internalDepth>this.maxDepth){this.staging.reset(),this.internalDepth=0,console.error(new Error(`[Virid Dispatcher] Deadlock: Max depth reached ${this.maxDepth}, Possible infinite loop detected. Ticking aborted.`));return}this.internalDepth++;try{this.staging.flip();let t=this.collectTasks(e);this.executeTasks(t)}catch(t){d.error(t,"[Virid Dispatcher] Sub-Tick Unhandled Error");break}}this.staging.reset(),this.internalDepth=0,this.executeTickHooks(this.afterTickHooks),this.globalTick++}}collectTasks(e){let t=[];for(let s of this.staging.eventActive)(e.get(s.constructor)||[]).forEach(n=>{t.push(new B(n.fn,n.priority,s,{context:n.fn.systemContext,tick:this.globalTick,payload:{}},this.beforeExecuteHooks,this.afterExecuteHooks))});for(let[s,i]of this.staging.signalActive.entries())(e.get(s)||[]).forEach(c=>{t.push(new B(c.fn,c.priority,i,{context:c.fn.systemContext,tick:this.globalTick,payload:{}},this.beforeExecuteHooks,this.afterExecuteHooks))});return t}executeTasks(e){e.sort((t,s)=>s.priority-t.priority);for(let t of e){let s=Array.isArray(t.message)?t.message[0]:t.message;try{let i=t.execute();i instanceof Promise&&i.catch(n=>d.error(n,`[Virid Dispatcher]: Async System Error.
|
|
6
7
|
SystemLocation: ${t.hookContext.context.targetClass.name}.${t.hookContext.context.methodName}
|
|
7
|
-
MessageName: ${
|
|
8
|
-
MessageData: ${JSON.stringify(t.message)}`))}catch(
|
|
8
|
+
MessageName: ${s.constructor.name}
|
|
9
|
+
MessageData: ${JSON.stringify(t.message)}`))}catch(i){d.error(i,`[Virid Dispatcher]: Sync System Error.
|
|
9
10
|
SystemLocation: ${t.hookContext.context.targetClass.name}.${t.hookContext.context.methodName}
|
|
10
|
-
MessageName: ${
|
|
11
|
-
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 r=new Set(t);e.forEach(n=>r.add(n.constructor)),this.eventHub.clearSignals(r),this.eventHub.clearEvents()}executeTickHooks(e){let t={tick:this.globalTick,timestamp:Date.now(),payload:this.tickPayload};e.forEach(r=>r(t))}};o(F,"Dispatcher");var R=F,U=class U{constructor(e,t,r,n){i(this,"fn");i(this,"priority");i(this,"message");i(this,"hookContext");this.fn=e,this.priority=t,this.message=r,this.hookContext=n}triggerHooks(e){let t=Array.isArray(this.message)?this.message[0]:this.message;if(t){for(let r of e)if(t instanceof r.type)try{let n=r.handler(this.message,this.hookContext);n instanceof Promise&&n.catch(f=>{a.error(f,`[Virid Hook] Async Hook Error:
|
|
12
|
-
|
|
13
|
-
${
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
${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=[]}};o(J,"EventHub");var I=J;var Y=class Y{constructor(){i(this,"systemTaskMap",new Map)}register(e,t,r=0){let n=this.systemTaskMap.get(e)||[];if(n.findIndex(l=>l.fn===t)===-1)n.push({fn:t,priority:r}),n.sort((l,u)=>u.priority-l.priority),this.systemTaskMap.set(e,n);else{let l=t.name||"Anonymous";return a.error(new Error(`[Virid Error] System Already Registered:
|
|
17
|
-
Class ${e.name}
|
|
18
|
-
Function ${l}`)),()=>{}}return()=>{let l=this.systemTaskMap.get(e);if(l){let u=l.findIndex(d=>d.fn===t);u!==-1&&(l.splice(u,1),l.length===0&&this.systemTaskMap.delete(e))}}}};o(Y,"MessageRegistry");var M=Y;var q=class q{constructor(){i(this,"eventHub",new I);i(this,"dispatcher",new R(this.eventHub));i(this,"registry",new M);i(this,"middlewares",[]);se(this)}useMiddleware(e,t){this.middlewares.push(e)}onBeforeExecute(e,t,r){this.dispatcher.addBeforeExecute(e,t,r)}onAfterExecute(e,t,r){this.dispatcher.addAfterExecute(e,t,r)}onBeforeTick(e,t){this.dispatcher.addBeforeTick(e,t)}onAfterTick(e,t){this.dispatcher.addAfterTick(e,t)}dispatch(e){if(!(e instanceof y)){a.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)){a.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 r=0,n=o(()=>{r<this.middlewares.length?this.middlewares[r++](e,n):t()},"next");n()}register(e,t,r=0){return this.registry.register(e,t,r)}};o(q,"MessageInternal");var A=q;var K=class K{constructor(){i(this,"bindings",new Map);i(this,"singletonInstances",new Map)}bind(e){let t={type:"transient",ctor:e};return this.bindings.set(e,t),{toSelf:o(()=>({inSingletonScope:o(()=>(t.type="singleton",{onActivation:o(r=>{},"onActivation")}),"inSingletonScope")}),"toSelf")}}get(e,t){let r=this.bindings.get(e);if(!r)throw new Error(`[Virid Container] Unbound Constructor: No binding found for ${e.name}`);let n=r.ctor;if(r.type==="singleton"){if(!this.singletonInstances.has(e)){let l=new n,u=t(l);this.singletonInstances.set(e,u)}return this.singletonInstances.get(e)}let f=new n;return t(f)}};o(K,"ViridContainer");var D=K;var P=!0;function ne(s){P=s}o(ne,"toggleSwitch");var c={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 X(s,e,t){let r={params:s,targetClass:Object,methodName:t,originalMethod:e};return e.ccsContext=r,e}o(X,"withContext");var de=o(s=>{if(!P)return;let e=`${c.green}${c.bold} \u2714 [Virid Info] ${c.reset}`,t=`${c.magenta}${s.context}${c.reset}`;console.log(`${e}${c.gray}Global Info Caught:${c.reset}
|
|
19
|
-
${c.green}Details:${c.reset}`,s.context||"unknown Info")},"globalInfoHandler"),pe=o(s=>{if(!P)return;let e=`${c.red}${c.bold} \u2716 [Virid Error] ${c.reset}`,t=`${c.magenta}${s.context}${c.reset}`;console.error(`${e}${c.gray}Global Error Caught:${c.reset}
|
|
20
|
-
${c.red}Context:${c.reset} ${t}
|
|
21
|
-
${c.red}Details:${c.reset}`,s.error||s||"unknown Error")},"globalErrorHandler"),ge=o(s=>{if(!P)return;let e=`${c.yellow}${c.bold} \u26A0 [Virid Warn] ${c.reset}`,t=`${c.cyan}${s.context}${c.reset}`;console.warn(`${e}${c.gray}Global Warn Caught:${c.reset}
|
|
22
|
-
${c.yellow}Context:${c.reset} ${t}`)},"globalWarnHandler");function oe(s){s.register(S,X(S,ge,"GlobalWarnHandler"),-999),s.register(v,X(v,pe,"GlobalErrorHandler"),-999),s.register(b,X(b,de,"GlobalInfoHandler"),-999),O=s}o(oe,"initializeGlobalSystems");var O=null,qe=new Proxy({},{get(s,e){return(...t)=>{if(!O){console.warn(`[Virid Vue] App method "${String(e)}" called before initialization.`);return}let r=O[e];if(typeof r=="function")return Reflect.apply(r,O,t)}}});var ie=new Set,ee=class ee{constructor(){i(this,"container",new D);i(this,"messageInternal",new A);i(this,"activationHooks",[])}addActivationHook(e){this.activationHooks.push(e)}get(e){return e.length>0&&a.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,r)=>{try{let n=r(t);return n===void 0&&a.warn(`[Virid Container] Hook Does Bot Return A Value: Hook "${r.name}" should return a instance to continue.`),n!==void 0?n:t}catch(n){return a.error(n,"[Virid Container] Activation Hook Failed"),t}},e)}bindController(e){return this.container.bind(e).toSelf(),{inSingletonScope:o(()=>({onActivation:o(()=>{},"onActivation")}),"inSingletonScope")}}bindComponent(e){return this.container.bind(e).toSelf().inSingletonScope(),{onActivation:o(()=>{},"onActivation")}}useMiddleware(e,t=!1){this.messageInternal.useMiddleware(e,t)}onBeforeExecute(e,t,r=!1){this.messageInternal.onBeforeExecute(e,t,r)}onAfterExecute(e,t,r=!1){this.messageInternal.onAfterExecute(e,t,r)}onBeforeTick(e,t=!1){this.messageInternal.onBeforeTick(e,t)}onAfterTick(e,t=!1){this.messageInternal.onAfterTick(e,t)}register(e,t,r=0){return this.messageInternal.register(e,t,r)}use(e,t){if(ie.has(e.name))return a.warn(`[Virid Plugin] Duplicate Installation: Plugin ${e.name} has already been installed.`),this;try{e.install(this,t),ie.add(e.name)}catch(r){a.error(r,`[Virid Plugin]: Install Failed: ${e.name}`)}return this}};o(ee,"ViridApp");var Z=ee,w=new Z;w.addActivationHook(_);oe(w);var g={SYSTEM:"virid:core:system",MESSAGE:"virid:core:message",CONTROLLER:"virid:core:controller",COMPONENT:"virid:core:component",SAFE:"virid:core:safe",OBSERVER:"virid:core:observer"};var $=o(s=>{if(!s)return;(Array.isArray(s)?s:[s]).forEach(t=>{t instanceof y?a.write(t):a.warn("[Virid HandleResult] Invalid Return Type: Must return Message or Message[].")})},"handleResult");function lt(s={priority:0,messageClass:null}){return(e,t,r)=>{if(typeof e!="function"){let h=new Error(`[Virid System] Method Type Error:
|
|
23
|
-
The Method ${t} is not a static method, please check if there is a static keyword tag`);a.error(h);return}let n=r.value,f=Reflect.getMetadata("design:paramtypes",e,t),l=Reflect.getMetadata(g.MESSAGE,e,t)||null;if(!f){let h=new Error(`[Virid System] System Parameter Loss:
|
|
24
|
-
Unable to recognize system parameters, please confirm if import "reflection-metadata" was introduced at the beginning!`);a.error(h);return}if(f.some(h=>h===void 0)){let h=new Error(`[Virid System] Parameter Metadata Loss in "${t}":
|
|
25
|
-
One or more parameters have 'undefined' types.
|
|
26
|
-
This usually happens when you forget to add a type annotation to a decorated parameter.
|
|
27
|
-
Check parameter at index: ${f.indexOf(void 0)}`);a.error(h);return}if(s.messageClass&&l){a.error(new Error(`[Virid System] Multiple Messages Are Not Allowed: Cannot use @ message() and SystemParams simultaneously in ${t}`));return}if(!s.messageClass&&!l){a.error(new Error(`[Virid System] System Parameter Loss:
|
|
28
|
-
Please declare the message type using the Message decorator`));return}let u=o(h=>{let E=f.map((T,ce)=>{if(l&&l.index==ce){let{messageClass:N,single:le}=l,H=Array.isArray(h)?h[0]:h;if(!(H instanceof N)){let he=H.constructor.name;throw new Error(`[Virid System] Type Mismatch: Expected ${N.name}, but received ${he}`)}if(H instanceof x)return le?Array.isArray(h)?h[h.length-1]:h:Array.isArray(h)?h:[h];if(H instanceof m)return h;throw new Error(`[Virid System] unknown Message Types: Message ${N.name} is not a subclass of SingleMessage or EventMessage!`)}let te=w.get(T);if(!te)throw new Error(`[Virid System] unknown Inject Data Types: ${T.name} is not registered in the container!`);return te}),k=n.apply(e,E);return k instanceof Promise?k.then($):$(k)},"wrappedSystem"),d={params:f,targetClass:e,methodName:t,originalMethod:n};u.systemContext=d,r.value=u;let p=s.messageClass||l.messageClass;w.register(p,u,s.priority)}}o(lt,"System");function ht(s,e=!0){return(t,r,n)=>{if(Reflect.hasOwnMetadata(g.MESSAGE,t,r)){a.error(new Error(`[Virid Message] Multiple Messages Are Not Allowed: ${r} has multiple @Message() decorators!`));return}let f={index:n,messageClass:s,single:e};Reflect.defineMetadata(g.MESSAGE,f,t,r)}}o(ht,"Message");function ft(){return(s,e,t)=>{let r=Reflect.getMetadata(g.SAFE,s)||new Set;r.add(e),Reflect.defineMetadata(g.SAFE,r,s)}}o(ft,"Safe");function ut(s){return(e,t)=>{let r=Reflect.getMetadata(g.OBSERVER,e)||[];r.push({propertyKey:t,callback:s}),Reflect.defineMetadata(g.OBSERVER,r,e)}}o(ut,"Observer");function dt(){return s=>{Reflect.defineMetadata(g.CONTROLLER,!0,s)}}o(dt,"Controller");function pt(){return s=>{Reflect.defineMetadata(g.COMPONENT,!0,s)}}o(pt,"Component");var me=["push","pop","shift","unshift","splice","sort","reverse"];function _(s){return!s||typeof s!="object"||Object.prototype.hasOwnProperty.call(s,"__virid_observer_processed__")||(Object.defineProperty(s,"__virid_observer_processed__",{value:!0,enumerable:!1,configurable:!0}),(Reflect.getMetadata(g.OBSERVER,s)||[]).forEach(({propertyKey:t,callback:r})=>{let n={value:s[t]},f=new Proxy(n,{get(u,d){let p=u.value;return Array.isArray(p)&&me.includes(d)?(...h)=>{let E=[...p],k=p[d].apply(p,h),T=r.call(s,E,p);return $(T),k}:p},set(u,d,p){let h=u.value;if(p===h)return!0;u.value=p;let E=r.call(s,h,p);return $(E),!0}}),l=o(()=>f.value,"getter");l.__virid_box__=n,Object.defineProperty(s,t,{get:l,set:o(u=>{f.value=u},"set"),enumerable:!0,configurable:!0}),n.value&&typeof n.value=="object"&&_(n.value)}),Reflect.ownKeys(s).forEach(t=>{if(t==="__virid_observer_processed__")return;let r=Object.getOwnPropertyDescriptor(s,t);if(r&&r.get)return;let n=s[t];n&&typeof n=="object"&&_(n)})),s}o(_,"bindObservers");var ae={enableLog:!0};function It(s=ae){return ne(s.enableLog),w}o(It,"createVirid");export{y as BaseMessage,pt as Component,dt as Controller,v as ErrorMessage,m as EventMessage,b as InfoMessage,ht as Message,A as MessageInternal,M as MessageRegistry,a as MessageWriter,ut as Observer,ft as Safe,x as SingleMessage,lt as System,g as VIRID_METADATA,S as WarnMessage,se as activateInstance,_ as bindObservers,It as createVirid,ae as defaultConfig,$ as handleResult,ue as publisher};
|
|
11
|
+
MessageName: ${s.constructor.name}
|
|
12
|
+
MessageData: ${JSON.stringify(t.message)}`)}}}executeTickHooks(e){let t={tick:this.globalTick,timestamp:Date.now(),payload:this.tickPayload};e.forEach(s=>s(t))}};o(se,"Dispatcher");var _=se,re=class re{constructor(e,t,s,i,n,c){a(this,"fn");a(this,"priority");a(this,"message");a(this,"hookContext");a(this,"beforeExecuteHooks");a(this,"afterExecuteHooks");a(this,"success",!0);this.fn=e,this.priority=t,this.message=s,this.hookContext=i,this.beforeExecuteHooks=n,this.afterExecuteHooks=c}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,this.success);i instanceof Promise&&i.catch(n=>{d.error(n,`[Virid Hook] Async Hook Error: It is prohibited to use asynchronous hooks within Hook: ${s.type.name}`)})}catch(i){d.error(i,`[Virid Hook] Hook Execute Failed: Triggered by: ${t.constructor.name}, Registered type: ${s.type.name}`)}}}execute(){this.triggerHooks(this.beforeExecuteHooks);let e=o(()=>this.triggerHooks(this.afterExecuteHooks),"runAfter");try{let t=this.fn(this.message);return t instanceof Promise?t.catch(()=>this.success=!1).finally(e):(e(),t)}catch(t){throw this.success=!1,e(),t}}};o(re,"ExecutionTask");var B=re;var oe=class oe{constructor(e,t){a(this,"dispatcher");a(this,"registry",new I);a(this,"middlewares",[]);a(this,"manual");this.dispatcher=new _(e),this.manual=t,le(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)}tick(){this.dispatcher.tickSync(this.registry.systemTaskMap)}dispatch(e){if(!(e instanceof w)){d.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)){d.error(new Error(`[Virid Dispatch] No handler for message: ${e.constructor.name}`));return}this.dispatcher.stage(e),this.manual||this.dispatcher.tick(this.registry.systemTaskMap)})}pipeline(e,t){let s=0,i=o(()=>{s<this.middlewares.length?this.middlewares[s++](e,i):t()},"next");i()}register(e,t,s=0){return this.registry.register(e,t,s)}};o(oe,"MessageEngine");var P=oe;var y={SYSTEM:"virid:core:system",MESSAGE:"virid:core:message",CONTROLLER:"virid:core:controller",COMPONENT:"virid:core:component",SAFE:"virid:core:safe",OBSERVER:"virid:core:observer"};function R(r){if(!r)return;(Array.isArray(r)?r:[r]).forEach(t=>{t instanceof w?d.write(t):d.warn("[Virid HandleResult] Invalid Return Type: Must return Message or Message[].")})}o(R,"handleResult");function ue(r){let e=[];if(r.forEach((t,s)=>{(t===w||t&&t.prototype instanceof w)&&e.push({type:t,idx:s})}),e.length===0)return null;if(e.length>1){let t=e.map(s=>`[Index: ${s.idx}, Name: ${s.type.name}]`).join(", ");throw new Error(`[Virid System] Multiple Messages: Multiple Message type parameters detected, this is not allowed! specific location: ${t}`)}return e[0]}o(ue,"checkMessageParam");function j(r={messageClass:null,priority:0}){return(e,t,s)=>{if(typeof e!="function")throw new Error(`[Virid System] Method Type Error: The Method ${t} is not a static method, please check if there is a static keyword tag.`);let i=s.value,n=Reflect.getMetadata("design:paramtypes",e,t);if(!n)throw new Error('[Virid System] System Parameter Loss: Unable to recognize system parameters, please confirm if import "reflect-metadata" was introduced at the beginning.');let c=n.map((g,A)=>g===void 0?A:-1).filter(g=>g!==-1);if(c.length>0)throw new Error(`[Virid System] Parameter Metadata Loss in "${t}": One or more parameters have 'undefined' types. This usually happens when you forget to add a type annotation or due to circular dependencies. Check parameter at indices: [${c.join(", ")}]`);let l,m=-1,u=!1,x=n.indexOf(Array);if(x!==-1){if(!r.messageClass)throw new Error("[Virid System] System Parameter Loss: When using batch processing mode with Array, the messageClass parameter must be specified in decorator options.");if(!(r.messageClass.prototype instanceof S))throw new Error("[Virid System] System Parameter Loss: When using the batch processing mode, the messageClass parameter must inherit from SingleMessage.");l=r.messageClass,m=x,u=!0}else{let g=ue(n);if(g&&r.messageClass)throw new Error(`[Virid System] Multiple Messages Are Not Allowed: Cannot specify messageClass in decorator options while already declaring it in method parameters at index ${g.idx} in ${t}.`);if(g)l=g.type,m=g.idx;else if(r.messageClass)l=r.messageClass,m=-1;else throw new Error("[Virid System] System Parameter Loss: Please declare the message type either in method parameters or via the Message decorator options.")}let E={params:n,targetClass:e,methodName:t,originalMethod:i},b={messageClass:l,messageIdx:m,priority:r.priority||0,batchMode:u};s.value.systemContext=E,s.value.systemConfig=b}}o(j,"System");function st(){return(r,e,t)=>{let s=Reflect.getMetadata(y.SAFE,r)||new Set;s.add(e),Reflect.defineMetadata(y.SAFE,s,r)}}o(st,"Safe");function rt(r){return(e,t)=>{let s=Reflect.getMetadata(y.OBSERVER,e)||[];s.push({propertyKey:t,callback:r}),Reflect.defineMetadata(y.OBSERVER,s,e)}}o(rt,"Observer");function ot(){return r=>{Reflect.defineMetadata(y.CONTROLLER,!0,r)}}o(ot,"Controller");function he(){return r=>{Reflect.defineMetadata(y.COMPONENT,!0,r)}}o(he,"Component");var ye=["push","pop","shift","unshift","splice","sort","reverse"];function L(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(y.OBSERVER,r)||[]).forEach(({propertyKey:t,callback:s})=>{let i={value:r[t]},n=new Proxy(i,{get(l,m){let u=l.value;return Array.isArray(u)&&ye.includes(m)?(...x)=>{let E=[...u],b=u[m].apply(u,x),g=s.call(r,E,u);return R(g),b}:u},set(l,m,u){let x=l.value;if(u===x)return!0;l.value=u;let E=s.call(r,x,u);return R(E),!0}}),c=o(()=>n.value,"getter");c.__virid_box__=i,Object.defineProperty(r,t,{get:c,set:o(l=>{n.value=l},"set"),enumerable:!0,configurable:!0}),i.value&&typeof i.value=="object"&&L(i.value)}),Reflect.ownKeys(r).forEach(t=>{if(t==="__virid_observer_processed__")return;let s=Object.getOwnPropertyDescriptor(r,t);if(s&&s.get)return;let i=r[t];i&&typeof i=="object"&&L(i)})),r}o(L,"bindObservers");var ie=class ie{constructor(){a(this,"bindings",new Map);a(this,"singletonInstances",new Map);a(this,"activationHooks",[])}addActivationHook(e,t){t?this.activationHooks.unshift(e):this.activationHooks.push(e)}bind(e){if(e.length>0)throw new Error(`[Virid Container] Cannot Bind Component Or Controller: The Class ${e.name} should not have mandatory parameters.`);if(Reflect.getMetadata(y.COMPONENT,e)){let t={type:"singleton",ctor:e};this.bindings.set(e,t)}else if(Reflect.getMetadata(y.CONTROLLER,e)){let t={type:"transient",ctor:e};this.bindings.set(e,t)}else throw new Error(`[Virid Container] Cannot Bind Component Or Controller: The Class ${e.name} is not decorated with @Component or @Controller`)}spawn(e){let t=e.constructor;if(Reflect.hasMetadata(y.COMPONENT,t)){let s={type:"singleton",ctor:t};this.bindings.set(t,s),this.singletonInstances.set(t,e)}else throw new Error(`[Virid Container] Cannot spawn Component: The Class ${t.name} is not decorated with @Component`)}get(e){let t=this.bindings.get(e);if(!t)throw new Error(`[Virid Container] Cannot Get Component Or Controller: No binding found for ${e}`);let s=t.ctor;if(t.type==="singleton"){if(!this.singletonInstances.has(e)){let n=new s,c=this.handleActivation(n);this.singletonInstances.set(e,c)}return this.singletonInstances.get(e)}let i=new s;return this.handleActivation(i)}handleActivation(e){for(let t of this.activationHooks)e=t(e);return e}};o(ie,"ViridContainer");var W=ie;function xe(r,e,t,s){var i=arguments.length,n=i<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,c;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(c=r[l])&&(n=(i<3?c(n):i>3?c(e,t,n):c(e,t))||n);return i>3&&n&&Object.defineProperty(e,t,n),n}o(xe,"_ts_decorate");function fe(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)}o(fe,"_ts_metadata");var ne=class ne{constructor(e,t){a(this,"container",new W);a(this,"engine");a(this,"installedPlugins",new Set);this.engine=new P(e,t),this.container.spawn(this)}onActivate(e,t=!1){this.container.addActivationHook(e,t)}tick(){this.engine.tick()}get(e){return this.container.get(e)}bind(e){this.container.bind(e)}spawn(e){this.container.spawn(e)}useMiddleware(e,t=!1){this.engine.useMiddleware(e,t)}onBeforeExecute(e,t,s=!1){this.engine.onBeforeExecute(e,t,s)}onAfterExecute(e,t,s=!1){this.engine.onAfterExecute(e,t,s)}onBeforeTick(e,t=!1){this.engine.onBeforeTick(e,t)}onAfterTick(e,t=!1){this.engine.onAfterTick(e,t)}use(e,t){if(this.installedPlugins.has(e.name))return d.warn(`[Virid Plugin] Duplicate Installation: Plugin ${e.name} has already been installed.`),this;try{e.install(this,t),this.installedPlugins.add(e.name)}catch(s){d.error(s,`[Virid Plugin]: Install Failed: ${e.name}`)}return this}register(e){let t=e.systemContext,s=e.systemConfig;if(!t||!s)throw new Error(`[Virid System] System Parameter Loss: Please declare ${e.name} using the @System decorator first.`);let{params:i,targetClass:n,originalMethod:c}=t,{messageClass:l,messageIdx:m,priority:u,batchMode:x}=s,E=typeof R=="function"?R:h=>h,b=o(h=>h instanceof Promise?h.then(E):E(h),"processResult"),g=new Array(i.length),A=!1,U=o(()=>{for(let h=0;h<i.length;h++)if(h!==m){let p=this.get(i[h]);if(!p)throw new Error(`[Virid System] Unknown Inject Data Types: ${i[h].name||i[h]} is not registered in the container for system '${e.name}'!`);g[h]=p}A=!0},"initDeps"),M;return m===-1?M=o(()=>(A||U(),b(c.apply(n,g))),"wrappedSystem"):i.length===1?x?M=o(h=>{let p=Array.isArray(h)?h:[h];if(p.length>0&&!(p[0]instanceof l))throw new Error(`[Virid System] Type Mismatch: Expected list of ${l.name}, but got ${p[0]?.constructor?.name}`);return b(c.call(n,p))},"wrappedSystem"):M=o(h=>{let p=Array.isArray(h)?h[h.length-1]:h;if(!(p instanceof l))throw new Error(`[Virid System] Type Mismatch: Expected ${l.name}, but got ${p?.constructor?.name}`);return b(c.call(n,p))},"wrappedSystem"):x?M=o(h=>{A||U();let p=Array.isArray(h)?h:[h];if(p.length>0&&!(p[0]instanceof l))throw new Error(`[Virid System] Type Mismatch: Expected list of ${l.name}, but got ${p[0]?.constructor?.name}`);let O=[...g];return O[m]=p,b(c.apply(n,O))},"wrappedSystem"):M=o(h=>{A||U();let p=Array.isArray(h)?h[h.length-1]:h;if(!(p instanceof l))throw new Error(`[Virid System] Type Mismatch: Expected ${l.name}, but got ${p?.constructor?.name}`);let O=[...g];return O[m]=p,b(c.apply(n,O))},"wrappedSystem"),M.systemContext=t,this.engine.register(l,M,u)}};o(ne,"ViridApp");var H=ne;H=xe([he(),fe("design:type",Function),fe("design:paramtypes",[Number,Boolean])],H);function ae(r,e,t,s){var i=arguments.length,n=i<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,c;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(c=r[l])&&(n=(i<3?c(n):i>3?c(e,t,n):c(e,t))||n);return i>3&&n&&Object.defineProperty(e,t,n),n}o(ae,"_ts_decorate");function k(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)}o(k,"_ts_metadata");var G=!0;function de(r){G=r}o(de,"toggleSwitch");var f={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"},V,D=(V=class{static globalInfoHandler(e){if(!G)return;let t=`${f.green}${f.bold} \u2714 [Virid Info] ${f.reset}`,s=`${f.magenta}${e.context}${f.reset}`;console.log(`${t}${f.gray}Global Info Caught:${f.reset}
|
|
13
|
+
${f.green}Details:${f.reset}`,s||"unknown Info")}static globalErrorHandler(e){if(!G)return;let t=`${f.red}${f.bold} \u2716 [Virid Error] ${f.reset}`,s=`${f.magenta}${e.context}${f.reset}`;console.error(`${t}${f.gray}Global Error Caught:${f.reset}
|
|
14
|
+
${f.red}Context:${f.reset} ${s}
|
|
15
|
+
${f.red}Details:${f.reset}`,e.error||e||"unknown Error")}static globalWarnHandler(e){if(!G)return;let t=`${f.yellow}${f.bold} \u26A0 [Virid Warn] ${f.reset}`,s=`${f.cyan}${e.context}${f.reset}`;console.warn(`${t}${f.gray}Global Warn Caught:${f.reset}
|
|
16
|
+
${f.yellow}Context:${f.reset} ${s}`)}},o(V,"ViridLogHandler"),V);ae([j(),k("design:type",Function),k("design:paramtypes",[typeof C>"u"?Object:C]),k("design:returntype",void 0)],D,"globalInfoHandler",null);ae([j(),k("design:type",Function),k("design:paramtypes",[typeof v>"u"?Object:v]),k("design:returntype",void 0)],D,"globalErrorHandler",null);ae([j(),k("design:type",Function),k("design:paramtypes",[typeof $>"u"?Object:$]),k("design:returntype",void 0)],D,"globalWarnHandler",null);function pe(r){r.register(D.globalInfoHandler),r.register(D.globalErrorHandler),r.register(D.globalWarnHandler)}o(pe,"registerBasicSystems");function Ht(r=z){r={...z,...r};let e=new H(r.maxDepth,r.manual);pe(e),de(r.enableLog),e.onActivate(L);let t=e;return e.spawn(t),e}o(Ht,"createVirid");export{w as BaseMessage,he as Component,ot as Controller,v as ErrorMessage,T as EventMessage,C as InfoMessage,P as MessageEngine,I as MessageRegistry,d as MessageWriter,rt as Observer,st as Safe,S as SingleMessage,j as System,y as VIRID_METADATA,H as ViridApp,$ as WarnMessage,le as activateInstance,L as bindObservers,Ht as createVirid,z as defaultConfig,R as handleResult};
|
|
29
17
|
//# sourceMappingURL=index.js.map
|