@virid/core 0.0.1 → 0.1.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/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 Ailrid
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md CHANGED
@@ -1,259 +1 @@
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
- ```
1
+ todo
package/README.zh.md CHANGED
@@ -1,203 +1 @@
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
- ```
1
+ todo