@virid/core 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,259 @@
1
+ # 🛰️ @virid/core
2
+
3
+
4
+
5
+ > **A Lightweight, Message-Driven Logic Engine inspired by Rust's ECS Architecture and Nestjs.**
6
+
7
+ [中文说明](README.zh.md)
8
+
9
+ ## ✨ Features
10
+
11
+
12
+
13
+ ### 🧩 What is CCS Architecture?
14
+
15
+ `virid` is built on the **CCS (Component-Controller-System)** architecture. Based on the traditional ECS (Entity-Component-System) pattern, it introduces a "Controller" layer specifically for Web/UI environments to bridge logic and views seamlessly.
16
+
17
+ #### 1. 💾 Component (Data) — "The Container of Truth"
18
+
19
+ - **Definition**: Pure data structures containing zero business logic.
20
+ - **Responsibility**: Stores state (e.g., `PlaylistComponent` storing song lists and playback status). In `virid`, Components are managed as **Singletons** within the IoC container.
21
+
22
+ #### 2. 🎮 Controller (The Bridge) — "The Anchor of Views"
23
+
24
+ - **Definition**: A proxy layer between the UI framework (Vue) and the core logic (Core).
25
+ - **Responsibility**:
26
+ - **Projection**: Safely maps data from `Components` to Vue using `@Project`.
27
+ - **Command**: Captures UI events (like clicks) and transforms them into `Messages` to be dispatched to the engine.
28
+ - **Context Awareness**: Perceives UI hierarchy and metadata (like list indices) via `@Env`.
29
+
30
+ #### 3. ⚙️ System (Logic) — "The Arbiter of Causality"
31
+
32
+ - **Definition**: A collection of stateless static methods and the **only** legitimate place for state transitions.
33
+ - **Responsibility**: Listens for `Messages` and modifies `Component` data accordingly. Systems are **deterministic**, ensuring that the same input always yields the same state transition.
34
+
35
+ ### 🛠️ Decoupling of Logic Sovereignty
36
+
37
+ ### 1. Total UI Demotion: Framework-Agnostic Core
38
+
39
+ - **Transfer of Sovereignty**: The UI framework is stripped of its authority over state management and business scheduling, relegated to a pure **"State Projection Layer."** All business causality and state machine transitions are executed within the closed loop of `virid Core`.
40
+ - **Physical Isolation**: The Core layer has zero dependencies on `DOM/BOM` APIs. Your core logic runs seamlessly in **Node.js servers, Web Workers, or even Command Line Interface (CLI) tools**.
41
+ - **Seamless Migration**: Logical assets are no longer tethered to a specific UI library. Switch the adapter layer, and you are ready for **Vue, React, or beyond**.
42
+
43
+ ### 2. Production-Grade Testability
44
+
45
+ - **Farewell to Mocking Hell**: Say goodbye to JSDOM and complex browser simulations. Since the core logic is pure JS/TS, you can boot the Core directly in Node.js and complete unit tests for complex business flows via a **"Send Message -> Assert State"** pattern.
46
+ - **Logic Playback**: As all side effects are triggered by messages, business logic becomes a **pure pipeline**, enabling offline refactoring and automated regression of production logic paths.
47
+
48
+ ### 3. Powerful Inversion of Control (IoC)
49
+
50
+ - **Deep IoC Architecture**: Built on **InversifyJS** for robust Dependency Injection. `Systems`, `Components`, and `Controllers` are auto-assembled via the container.
51
+ - **Dynamic Lifecycle**: Supports on-demand loading and auto-injection of logic modules. Whether it’s a global singleton `System` or a `Controller` that dies with a component, the container manages the entire lifecycle.
52
+
53
+ ---
54
+
55
+ ## 🏎️ Game-Grade Scheduling Engine
56
+
57
+ - **Deterministic Tick Mechanism**: Introduces a Bevy-inspired message loop where all logical changes advance within discrete "Ticks."
58
+ - **Double-Buffered Message Pool**: Physically isolates "processing" and "incoming" messages, effectively eliminating infinite loops and logical jitter.
59
+ - **Physically Isolated Message Strategies**:
60
+ - **SingleMessage (Signal)**: Automatically merges identical signals, triggering a single batch process within the same Tick.
61
+ - **EventMessage (Event)**: Guarantees strict sequential execution, ensuring the atomicity of logical chains.
62
+
63
+ ---
64
+
65
+ ## 🛡️ State Security & Access Control
66
+
67
+ - **Read-Only Data Shield**: Controllers receive read-only proxies by default, strictly prohibiting illegal tampering with `Component` states outside of a `System`.
68
+ - **Atomic Modification Protocol**: Data changes are forced through specific `AtomicModifyMessage` protocols, ensuring every state transition is traceable and auditable.
69
+
70
+ ---
71
+
72
+ ## 🧬 Declarative Meta-Programming
73
+
74
+ - **Decorator-Driven**: Use `@System`, `@Message`, `@Inherit`, and `@Project` to declaratively describe complex dependency networks and reactive logic flows.
75
+ - **Automated Data Routing**: Dispatching a message immediately triggers the response; parameters are injected automatically, eliminating the need to write tedious boilerplate for listeners and dispatchers.
76
+
77
+ ## 📖 Quick Start
78
+
79
+ ⚠️ Important: You MUST import reflect-metadata at the very first line of your entry file (e.g., main.ts), otherwise decorators will not function correctly.
80
+
81
+ Build a strictly protected state machine in a pure JS environment in just three steps.
82
+
83
+ ### 1. Define Components & Messages
84
+
85
+ **Components** are pure data structures; **Messages** are the sole driving contracts.
86
+
87
+ ```ts
88
+ import {
89
+ createvirid,
90
+ Component,
91
+ System,
92
+ Message,
93
+ SingleMessage,
94
+ AtomicModifyMessage,
95
+ } from "@virid/core";
96
+
97
+ // Initialize the core engine
98
+ const app = createVirid();
99
+
100
+ // Define Data Entity (Component)
101
+ @Component()
102
+ class CounterComponent {
103
+ public count = 0;
104
+ }
105
+ // Register component
106
+ app.bindComponent(CounterComponent);
107
+
108
+ // Define operation instructions (Message)
109
+ class IncrementMessage extends SingleMessage {
110
+ constructor(public amount: number) {
111
+ super();
112
+ }
113
+ }
114
+ ```
115
+
116
+ ### 2. Implement Systems
117
+
118
+ **Systems** are stateless static methods. They retrieve components via Dependency Injection (DI) to handle business logic. You don't need to manually instantiate or invoke them—virid will automatically discover and execute them through static analysis.
119
+
120
+ ```ts
121
+ //Define System
122
+ class CounterSystem {
123
+ @System()
124
+ static onIncrement(
125
+ @Message(IncrementMessage) message: IncrementMessage,
126
+ count: CounterComponent,
127
+ ) {
128
+ console.log("---------------------System----------------------");
129
+ console.log("message :>> ", message);
130
+ count.count += message.amount;
131
+ }
132
+ }
133
+ ```
134
+
135
+ ### 3. Headless Execution
136
+
137
+ No browser required. Drive your business logic directly in **Node.js** or any testing framework.
138
+
139
+ ```ts
140
+ // Business logic automatically completes scheduling in the next microtask
141
+ queueMicrotask(() => {
142
+ IncrementMessage.send(1);
143
+ IncrementMessage.send(5);
144
+ queueMicrotask(() => {
145
+ AtomicModifyMessage.send(
146
+ CounterComponent,
147
+ (comp) => {
148
+ console.log("----------------AtomicModifyMessage------------------");
149
+ console.log("CounterComponent :>> ", comp);
150
+ },
151
+ "Check CounterComponent",
152
+ );
153
+ });
154
+ });
155
+ ```
156
+
157
+ ## 🛠️ Advanced Engineering Practices
158
+
159
+ ### ⚓ Lifecycle Interception (Middleware & AOP Hooks)
160
+
161
+ virid provides deep access to the message pipeline, allowing you to easily extend the system with features like **Undo/Redo, State Synchronization, or Automated Logging**.
162
+
163
+ - **Middleware**: Pre-process messages before they enter the `EventHub`.
164
+
165
+ TypeScript
166
+
167
+ ```
168
+ app.useMiddleware((message, next) => {
169
+ console.log(`[Log]: Intercepted message ${message.constructor.name}`);
170
+ next(); // Continue the pipeline
171
+ });
172
+ ```
173
+
174
+ - **AOP Hooks**: Perform aspect-oriented processing before or after specific message execution.
175
+ - `onBeforeExecute`: Triggered before System logic runs (e.g., for permission checks).
176
+ - `onAfterExecute`: Triggered after logic execution (e.g., for data persistence).
177
+
178
+ TypeScript
179
+
180
+ ```
181
+ app.onBeforeExecute(IncrementMessage, (message, context) => {
182
+ console.log("---------------- onBeforeExecute ------------------");
183
+ console.log("Message Details:", message);
184
+ console.log("Target System:", context.targetClass.name);
185
+ console.log("Method Context:", context.methodName);
186
+ });
187
+ ```
188
+
189
+ ---
190
+
191
+ ### ⚡ Atomic Modification: The "Snapshot" Privilege
192
+
193
+ To balance **strict constraints** with **development efficiency**, virid allows direct state mutations via `AtomicModifyMessage` without the need to write a full `System`.
194
+
195
+ - **Semantic Mutations**: Every atomic modification requires a mandatory `label`, transforming "arbitrary" assignments into auditable, meaningful actions.
196
+ - **Consistency Guarantee**: Atomic modifications still follow the **Tick Scheduling** mechanism, ensuring that data changes are synchronized with System logic.
197
+
198
+ ---
199
+
200
+ ### 🚨 Everything is a Message: Robust Error Monitoring
201
+
202
+ virid treats exceptions as first-class citizens of the system:
203
+
204
+ - **Automatic Encapsulation**: Any synchronous or asynchronous exception within a `System` or `Hook` is automatically captured by the `Dispatcher` and encapsulated into an `ErrorMessage`.
205
+ - **Defensive Programming**: You can define a dedicated `ErrorSystem` to handle these messages globally (e.g., reporting to Sentry or triggering UI alerts). This ensures the core engine remains resilient and never crashes due to a single component failure.
206
+
207
+ ---
208
+
209
+ ---
210
+
211
+ ## 🚀 Conclusion: Why virid?
212
+
213
+ virid is not just another state management library; it is an endeavor to introduce **Deterministic Industrial Standards** to Web development.
214
+
215
+ As your project scales from dozens to thousands of components, and your business logic evolves from simple CRUD into intricate cross-component choreographies, the virid architecture ensures that your codebase remains:
216
+
217
+ - **Traceable**: Every logical transition has a clear trail via messages.
218
+ - **Predictable**: Every state modification follows strict, predefined protocols.
219
+ - **Decoupled**: Every business flow can be tested and validated entirely independent of the UI.
220
+
221
+ ### 🛰️ Data Flow Architecture
222
+
223
+ ```mermaid
224
+ graph TD
225
+ %% 定义外部触发
226
+ User([External/Logic Call]) -->|Message.send| Writer[MessageWriter]
227
+
228
+ %% 核心引擎内部
229
+ subgraph Engine [Virid Core Engine]
230
+ direction TB
231
+ Writer -->|Middleware Pipeline| Hub[EventHub: Staging]
232
+
233
+ subgraph Dispatcher [Deterministic Dispatcher]
234
+ Hub -->|Tick / Buffer Flip| Active[EventHub: Active Pool]
235
+ Active -->|Sort by Priority| TaskQueue[Task Queue]
236
+
237
+ subgraph Executor [Execution Context]
238
+ TaskQueue -->|Identify| Sys[System Static Method]
239
+ Container[(Inversify Container)] -.->|Inject Component| Sys
240
+ Sys -->|Execute| Logic{Business Logic}
241
+ end
242
+ end
243
+
244
+ Logic -->|Update| Data[(Raw Component Data)]
245
+
246
+ %% 异常与反馈流
247
+ Logic -- "New Message" --> Writer
248
+ Logic -- "Error" --> ErrorHandler[Error Message System]
249
+ end
250
+
251
+ %% 状态输出
252
+ Data -->|Optional Projection| Output([External State Observation])
253
+
254
+ %% 样式
255
+ style Engine fill:#fff,stroke:#333,stroke-width:2px
256
+ style Dispatcher fill:#f5f5f5,stroke:#666,dashed
257
+ style Container fill:#e1f5fe,stroke:#01579b
258
+
259
+ ```
package/README.zh.md ADDED
@@ -0,0 +1,203 @@
1
+ # 🛰️ @virid/core
2
+
3
+ > **A Lightweight, Message-Driven Logic Engine inspired by Rust's ECS Architecture and Nestjs.** **受 Rust Bevy ECS 架构与Nestjs启发的轻量级消息驱动逻辑引擎。**
4
+
5
+ ## ✨ 特点
6
+
7
+ ### 🧩 什么是 CCS 架构?
8
+
9
+ `virid` 采用 **CCS (Controller-Component-System)** 架构。它在传统 ECS 的基础上,为 Web/UI 环境引入了“控制器”层,实现了逻辑与视图的完美桥接。
10
+
11
+ #### 1. 💾 Component (数据) —— “逻辑的容器”
12
+
13
+ - **定义**:纯粹的数据结构,不包含任何业务逻辑。
14
+ - **职责**:存储状态。在 `virid` 中,它是 IoC 容器管理的单例。
15
+
16
+ #### 2. 🎮 Controller (控制器) —— “视图的锚点”
17
+
18
+ - **定义**:UI 框架(Vue)与核心逻辑(Core)之间的代理。
19
+ - **职责**:
20
+ - **投影 (Projection)**:将 Component 里的数据安全地映射给 Vue。
21
+ - **指令 (Command)**:接收用户的点击事件,并将其转化为 `Message` 发送给引擎。
22
+
23
+ #### 3. ⚙️ System (系统) —— “因果的裁判”
24
+
25
+ - **定义**:无状态的静态方法集合,是逻辑变更的唯一合法场所。
26
+ - **职责**:监听 `Message`,根据指令修改 `Component` 中的数据。它是确定性的,确保同样的输入永远得到同样的输出。
27
+
28
+ ### 🛠️ 逻辑主权
29
+
30
+ #### 1. 彻底的 UI 降级:框架无关核心
31
+
32
+ - **主权移交**:UI 框架被剥夺了状态管理与业务调度的权限,退化为纯粹的 **“状态投影层”**。所有的业务因果律、状态机转换均在 `virid Core` 中闭环执行。
33
+ - **物理隔离**:Core 层不依赖任何 `DOM/BOM` API。核心逻辑可以无缝运行在 **Node.js 服务端、Web Worker、甚至是命令行 (CLI) 工具**中。
34
+ - **无缝迁移**:逻辑资产不再与特定 UI 框架绑定。只需更换一个适配层,就能适配 vue 或React 应用。
35
+
36
+ #### 2. 生产级的可测试性
37
+
38
+ - **告别模拟 (Mock) 地狱**:无需 JSDOM,无需模拟复杂的浏览器环境。由于核心逻辑是纯 JS/TS 驱动的,可以直接在 Node.js 中启动 Core,通过 **“发送消息 -> 断言状态”** 的方式,完成对复杂业务流的单元测试。
39
+ - **逻辑回放**:所有副作用都通过消息触发,让业务逻辑变成**纯净的流水线**,支持对线上逻辑路径进行离线重构与自动化回归。
40
+
41
+ #### 3. 强力控制反转
42
+
43
+ - **深度 IoC 架构**:基于 **InversifyJS** 实现依赖注入。`System`、`Component` 与 `Controller` 之间通过容器自动装配。
44
+ - **动态生命周期**:支持逻辑模块的按需加载与自动注入。无论是全局单例的 `System` 还是随组件销毁的 `Controller`,均由容器统一接管生命周期。
45
+
46
+ ### 🏎️ 游戏级调度引擎
47
+
48
+ - **确定性 Tick 机制**: 引入类 Bevy 的消息循环,所有逻辑变更在 Tick 中推进。
49
+ - **双缓冲消息池**: 物理隔离“正在处理”与“新产生”的消息,避死循环与逻辑抖动。
50
+ - **物理隔离消息策略**:
51
+ - **SingleMessage (信号)**: 自动合并同类项,同 Tick 内仅触发一次批量处理。
52
+ - **EventMessage (事件)**: 严格保序执行,确保逻辑链条的原子性。
53
+
54
+ ### 🛡️ 状态安全与权限控制
55
+
56
+ - **只读数据护盾**: Controller 层(@virid/vue中)默认获得只读代理,禁止在 System 之外非法篡改 Component 状态。
57
+ - **原子修改协议**: 强制通过特定的 `AtomicModifyMessage` 变更数据,让每一次状态改变都有迹可循、可被审计。
58
+
59
+ ### 🧬 声明式元编程
60
+
61
+ - **装饰器驱动**: 使用 `@System`, `@Message`, `@Inherit`, `@Project` 等装饰器,以声明式的方式描述复杂的依赖网络和逻辑响应流。
62
+ - **自动数据路由**: 消息发送即触发,参数自动注入,无需手动编写复杂的监听与分发代码。
63
+
64
+ ## 📖 快速上手
65
+
66
+ 只需三步,即可在纯 JS 环境中构建一个受严格保护的状态机。
67
+
68
+ #### 1. 定义组件与消息 (Component & Message)
69
+
70
+ 组件(Component)是纯粹的数据结构,消息是唯一的驱动契约。
71
+
72
+ ```ts
73
+ import {
74
+ createvirid,
75
+ Component,
76
+ System,
77
+ Message,
78
+ SingleMessage,
79
+ AtomicModifyMessage,
80
+ } from "@virid/core";
81
+
82
+ // Initialize the core engine
83
+ const app = createvirid();
84
+
85
+ // Define Data Entity (Component)
86
+ @Component()
87
+ class CounterComponent {
88
+ public count = 0;
89
+ }
90
+ // Register component
91
+ app.bindComponent(CounterComponent);
92
+
93
+ // Define operation instructions (Message)
94
+ class IncrementMessage extends SingleMessage {
95
+ constructor(public amount: number) {
96
+ super();
97
+ }
98
+ }
99
+ ```
100
+
101
+ #### 2. 编写系统 (System)
102
+
103
+ 系统是无状态的静态方法,通过依赖注入获取组件并处理业务逻辑。**你无需任何操作,他们是纯static的,virid会自动找到他们并正确地调用他们。**
104
+
105
+ ```ts
106
+ //Define System
107
+ class CounterSystem {
108
+ @System()
109
+ static onIncrement(
110
+ @Message(IncrementMessage) message: IncrementMessage,
111
+ count: CounterComponent,
112
+ ) {
113
+ console.log("---------------------System----------------------");
114
+ console.log("message :>> ", message);
115
+ count.count += message.amount;
116
+ }
117
+ }
118
+ ```
119
+
120
+ #### 3. 纯环境运行 (Headless Execution)
121
+
122
+ 无需浏览器,直接在 Node.js 或测试框架中驱动你的业务。
123
+
124
+ ```ts
125
+ // Business logic automatically completes scheduling in the next microtask
126
+ queueMicrotask(() => {
127
+ IncrementMessage.send(1);
128
+ IncrementMessage.send(5);
129
+ queueMicrotask(() => {
130
+ AtomicModifyMessage.send(
131
+ CounterComponent,
132
+ (comp) => {
133
+ console.log("----------------AtomicModifyMessage------------------");
134
+ console.log("CounterComponent :>> ", comp);
135
+ },
136
+ "Check CounterComponent",
137
+ );
138
+ });
139
+ });
140
+ ```
141
+
142
+ ## 🛠️ 高级工程实践 (Advanced Engineering)
143
+
144
+ ### ⚓ 全生命周期拦截 (Lifecycle Hooks & Middleware)
145
+
146
+ virid 提供了深度介入消息管道的能力,你可以轻易地将其扩展为支持 **Undo/Redo**、**状态同步** 或 **自动日志** 的系统。
147
+
148
+ - **Middleware**: 在消息进入 EventHub 之前进行预处理。
149
+
150
+ TypeScript
151
+
152
+ ```ts
153
+ app.useMiddleware((message, next) => {
154
+ console.log(`Identified message ${message.constructor.name}`);
155
+ next(); // 继续流转
156
+ });
157
+ ```
158
+
159
+ - **AOP Hooks**: 针对特定消息的执行前后进行切面处理。
160
+ - `onBeforeExecute`: 在 System 逻辑运行前触发(如权限检查)。
161
+ - `onAfterExecute`: 在逻辑运行后触发(如数据持久化)。
162
+
163
+ ```ts
164
+ app.onBeforeExecute(IncrementMessage, (message, context) => {
165
+ console.log("----------------onBeforeExecute------------------");
166
+ console.log("message :>> ", message);
167
+ console.log("targetClass :>> ", context.targetClass);
168
+ console.log("methodName :>> ", context.methodName);
169
+ console.log("params :>> ", context.params);
170
+ });
171
+ ```
172
+
173
+ ### ⚡ 原子修改:“快照”特权 (Atomic Modification)
174
+
175
+ 为了兼顾“严苛约束”与“开发效率”,virid 允许通过 `AtomicModifyMessage` 直接描述状态变更,而无需编写完整的 System。
176
+
177
+ - **语义化变更**:每一条原子修改都强制要求一个 `label`,让原本“随意的”赋值操作变得可被审计。
178
+ - **一致性保证**:原子修改依然遵循 Tick 调度,确保数据变更与 System 逻辑同步生效。
179
+
180
+ ### 🚨 万物皆消息:健壮的异常监控 (Error as Message)
181
+
182
+ virid 将异常视为系统的一等公民:
183
+
184
+ - **自动封装**:任何 System 或 Hook 中的同步/异步异常,都会被 Dispatcher 自动捕获并封装为 `ErrorMessage`。
185
+ - **防御式编程**:你可以定义一个 `ErrorSystem` 统一处理这些消息(如发送 Sentry 日志或触发 UI 告警),确保核心逻辑引擎永远不会因为单一组件的崩溃而宕机。
186
+
187
+ ---
188
+
189
+ ## 🚀 结语:为什么是 virid?
190
+
191
+ virid 不是在重复造一个状态库,它是在为 Web 开发引入一套**具备强确定性的工业标准**。
192
+
193
+ 当你的项目从几十个组件增长到几千个,当你的业务逻辑从简单的 CRUD 变成复杂的跨组件联动时,virid 的架构将确保你的代码依然:**逻辑可寻迹、修改可预期、测试可脱离 UI。**
194
+
195
+ ```
196
+ 数据流转示意图
197
+ User -->|Dispatch| Writer[MessageWriter]
198
+ Writer -->|Middleware| Hub[EventHub: Staging]
199
+ Hub -->|Tick/Flip| Active[EventHub: Active]
200
+ Active -->|Execute| System[System/Hook]
201
+ System -->|Update| Component[Raw Component Data]
202
+ Component -->|Reactive| UI[Vue/React View]
203
+ ```
@@ -0,0 +1,218 @@
1
+ import { Newable, Container, BindInWhenOnFluentSyntax, BindWhenOnFluentSyntax } from 'inversify';
2
+
3
+ type AnyConstructor = abstract new (...args: any[]) => any;
4
+ declare abstract class BaseMessage {
5
+ static send<T extends AnyConstructor>(this: T, ...args: ConstructorParameters<T>): void;
6
+ senderInfo?: {
7
+ fileName: string;
8
+ line: number;
9
+ timestamp: number;
10
+ };
11
+ constructor();
12
+ }
13
+ /**
14
+ * 可合并的信号基类
15
+ */
16
+ declare abstract class SingleMessage extends BaseMessage {
17
+ private readonly __kind;
18
+ constructor();
19
+ }
20
+ /**
21
+ * 不可合并的消息基类
22
+ */
23
+ declare abstract class EventMessage extends BaseMessage {
24
+ private readonly __kind;
25
+ constructor();
26
+ }
27
+ /**
28
+ * 基础错误消息:不可合并,必须被精准捕获
29
+ */
30
+ declare class ErrorMessage extends EventMessage {
31
+ readonly error: Error;
32
+ readonly context?: string;
33
+ constructor(error: Error, context?: string);
34
+ }
35
+ /**
36
+ * 基础警告消息:不可合并,必须被精准捕获
37
+ */
38
+ declare class WarnMessage extends EventMessage {
39
+ readonly context: string;
40
+ constructor(context: string);
41
+ }
42
+ /**
43
+ * 原子修改消息:不可合并,带上组件类型、修改逻辑和语义标签
44
+ */
45
+ declare class AtomicModifyMessage<T> extends EventMessage {
46
+ readonly ComponentClass: Newable<T>;
47
+ readonly recipe: (comp: T) => void;
48
+ readonly label: string;
49
+ constructor(ComponentClass: Newable<T>, // 你要改哪个组件?
50
+ recipe: (comp: T) => void, // 你打算怎么改?
51
+ label: string);
52
+ }
53
+ type Middleware = (message: BaseMessage, next: () => void) => void;
54
+ type Hook<T extends BaseMessage> = (message: [BaseMessage] extends [T] ? SingleMessage[] | EventMessage : T extends SingleMessage ? T[] : T, context: CCSSystemContext) => void | Promise<void>;
55
+ type MessageIdentifier<T> = (abstract new (...args: any[]) => T) | (new (...args: any[]) => T);
56
+ interface CCSSystemContext {
57
+ params: any[];
58
+ targetClass: any;
59
+ methodName: string;
60
+ originalMethod: (...args: any[]) => any;
61
+ }
62
+ interface SystemTask {
63
+ fn: (...args: any[]) => any;
64
+ priority: number;
65
+ }
66
+ /**
67
+ * 核心逻辑:根据 T 的类型决定 Hook 接收的是数组还是单体
68
+ */
69
+ type MessagePayload<T> = T extends SingleMessage ? T[] : T extends EventMessage ? T : T | T[];
70
+
71
+ /**
72
+ * @description: 事件中心,存储和分发消息 - 物理隔离 SIGNAL 与 EVENT
73
+ */
74
+ declare class EventHub {
75
+ private signalActive;
76
+ private signalStaging;
77
+ private eventActive;
78
+ private eventStaging;
79
+ /**
80
+ * 写入逻辑:根据消息策略分流
81
+ */
82
+ push(event: any): void;
83
+ /**
84
+ * 翻转缓冲区:在 Dispatcher 的 Tick 开始时调用
85
+ */
86
+ flip(): void;
87
+ /**
88
+ * [SIGNAL专用] 批量读取某种类型的信号
89
+ */
90
+ peekSignal<T>(type: new (...args: any[]) => T): T[];
91
+ /**
92
+ * [EVENT专用] 获取当前所有待处理的事件流
93
+ */
94
+ getEventStream(): any[];
95
+ /**
96
+ * [新增] 根据索引精准读取 EVENT 里的某个数据
97
+ * 配合 Dispatcher 逐条分发时使用
98
+ */
99
+ peekEventAt(index: number): any;
100
+ /**
101
+ * 清理已处理的内容
102
+ */
103
+ clearSignals(types: Set<any>): void;
104
+ clearEvents(): void;
105
+ /**
106
+ * 重置所有池子
107
+ */
108
+ reset(): void;
109
+ }
110
+
111
+ declare class Dispatcher {
112
+ private dirtySignalTypes;
113
+ private eventQueue;
114
+ private isRunning;
115
+ private tickCount;
116
+ private eventHub;
117
+ private beforeHooks;
118
+ private afterHooks;
119
+ constructor(eventHub: EventHub);
120
+ addBefore<T extends BaseMessage>(type: MessageIdentifier<T>, hook: Hook<T>): void;
121
+ addAfter<T extends BaseMessage>(type: MessageIdentifier<T>, hook: Hook<T>): void;
122
+ private cleanupHook;
123
+ setCleanupHook(hook: (types: Set<any>) => void): void;
124
+ /**
125
+ * 标记脏数据:根据基类判断进入哪个池子
126
+ */
127
+ markDirty(message: any): void;
128
+ tick(interestMap: Map<any, SystemTask[]>): void;
129
+ }
130
+
131
+ /**
132
+ * @description: 消息注册器 - 负责将系统函数或监听器与消息类型关联
133
+ */
134
+ declare class MessageRegistry {
135
+ interestMap: Map<any, SystemTask[]>;
136
+ /**
137
+ * 注册消息并返回一个卸载函数
138
+ * 这种模式能完美适配 Controller 的生命周期销毁
139
+ */
140
+ register(eventClass: any, systemFn: (...args: any[]) => any, priority?: number): () => void;
141
+ }
142
+
143
+ declare class MessageInternal {
144
+ readonly eventHub: EventHub;
145
+ readonly dispatcher: Dispatcher;
146
+ readonly registry: MessageRegistry;
147
+ readonly middlewares: Middleware[];
148
+ constructor();
149
+ useMiddleware(mw: Middleware): void;
150
+ onBeforeExecute<T extends BaseMessage>(type: MessageIdentifier<T>, hook: Hook<T>): void;
151
+ onAfterExecute<T extends BaseMessage>(type: MessageIdentifier<T>, hook: Hook<T>): void;
152
+ /**
153
+ * 消息进入系统的唯一入口
154
+ */
155
+ dispatch(message: BaseMessage): void;
156
+ private pipeline;
157
+ }
158
+
159
+ interface IMessagePublisher {
160
+ dispatch(message: BaseMessage): void;
161
+ }
162
+ declare function activatInstance(instance: MessageInternal): void;
163
+ declare const publisher: IMessagePublisher;
164
+ declare class MessageWriter {
165
+ /**
166
+ * 核心入口:无论是类还是实例,统一交给 Internal 处理
167
+ */
168
+ static write<T extends BaseMessage, K extends new (...args: any[]) => T>(target: K | T, ...args: ConstructorParameters<K>): void;
169
+ /**
170
+ * 快捷方式:系统内部常用
171
+ */
172
+ static error(e: Error, context?: string): void;
173
+ static warn(context: string): void;
174
+ }
175
+
176
+ /**
177
+ * @description: 系统装饰器
178
+ * @param priority 优先级,数值越大越早执行
179
+ */
180
+ declare function System(priority?: number): (target: any, key: string, descriptor: PropertyDescriptor) => void;
181
+ /**
182
+ * @description: 标记参数为 MessageReader 并锁定其消息类型
183
+ */
184
+ declare function Message<T extends BaseMessage>(eventClass: new (...args: any[]) => T, single?: boolean): (target: any, key: string, index: number) => void;
185
+ /**
186
+ * @description: 标记Controller身份
187
+ */
188
+ declare function Controller(): (target: any) => void;
189
+ /**
190
+ * @description: 标记Component身份
191
+ */
192
+ declare function Component(): (target: any) => void;
193
+
194
+ interface ViridPlugin {
195
+ name: string;
196
+ install: (app: ViridApp, options?: any) => void;
197
+ }
198
+
199
+ /**
200
+ * 创建 virid 核心实例
201
+ */
202
+ declare class ViridApp {
203
+ container: Container;
204
+ private messageInternal;
205
+ private bindBase;
206
+ get(identifier: any): unknown;
207
+ bindController<T>(identifier: new (...args: any[]) => T): BindInWhenOnFluentSyntax<T>;
208
+ bindComponent<T>(identifier: new (...args: any[]) => T): BindWhenOnFluentSyntax<T>;
209
+ useMiddleware(mw: Middleware): void;
210
+ onBeforeExecute<T extends BaseMessage>(type: MessageIdentifier<T>, hook: Hook<T>): void;
211
+ onAfterExecute<T extends BaseMessage>(type: MessageIdentifier<T>, hook: Hook<T>): void;
212
+ register(eventClass: any, systemFn: (...args: any[]) => any, priority?: number): () => void;
213
+ use(plugin: ViridPlugin, options: any): this;
214
+ }
215
+
216
+ declare function createVirid(): ViridApp;
217
+
218
+ export { AtomicModifyMessage, BaseMessage, type CCSSystemContext, Component, Controller, ErrorMessage, EventMessage, type Hook, type IMessagePublisher, Message, type MessageIdentifier, MessageInternal, type MessagePayload, MessageWriter, type Middleware, SingleMessage, System, type SystemTask, ViridApp, type ViridPlugin, WarnMessage, activatInstance, createVirid, publisher };