### Setup and Run Project with Shell Commands Source: https://github.com/cassielxd/moduforge-rs/blob/main/examples/demo2/README.md These Bash commands install all dependencies, start the rough‑estimate micro‑frontend, launch the main Tauri application, and build or package the project for production. They cover both development and release workflows. ```bash # 安装所有依赖(包括子模块)\nnpm install\n\n# 启动概算模块\ncd packages/rough-estimate\nnpm run dev # 启动在 http://localhost:5174\n\n# 启动主应用\nnpm run tauri:dev\n\n# 构建所有模块\nnpm run build\n\n# 打包 Tauri 应用\nnpm run tauri:build ``` -------------------------------- ### Start Development Services (Bash) Source: https://github.com/cassielxd/moduforge-rs/blob/main/examples/demo2/AGENT_ARCHITECTURE_GUIDE.md These Bash commands start the development server for all services or individual modules. They use npm scripts and require Node.js and npm installed. Inputs are none; outputs are running servers on specified ports. Cannot run in production. ```bash # 1. 启动所有服务 npm run dev:all # 或分别启动 npm run dev # 主应用 (5173) cd packages/rough-estimate && npm run dev # 概算模块 (5174) cd packages/shared-components && npm run dev # 共享组件 (5175) ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/cassielxd/moduforge-rs/blob/main/examples/demo/README.md Command to install all required dependencies for the project using npm. This is the first step after cloning the repository. ```shell npm install ``` -------------------------------- ### Basic plugin example using mf_plugin! macro in Rust Source: https://github.com/cassielxd/moduforge-rs/blob/main/crates/macro/PLUGIN_MACRO_USAGE.md A simple example demonstrating the basic usage of the mf_plugin! macro to define a minimal plugin with documentation. ```rust use mf_macro::mf_plugin; // 最简单的插件 mf_plugin!( simple_plugin, docs = "简单插件示例" ); fn main() { let plugin = simple_plugin::new(); println!("插件名称: {}", plugin.get_name()); } ``` -------------------------------- ### Initialize Collaboration Server with Preloaded Rooms Source: https://github.com/cassielxd/moduforge-rs/blob/main/crates/collaboration/README.md This snippet demonstrates how to initialize the core components (YrsManager, SyncService), create a CollaborationServer, preload specific rooms, and start the server. It uses Tokio runtime and the mf_collab crate. The example includes loading existing room data before initialization. ```rust use mf_collab::{CollaborationServer, YrsManager, SyncService}; use std::sync::Arc; #[tokio::main] async fn main() -> anyhow::Result<()> { // 1. 初始化核心组件 let yrs_manager = Arc::new(YrsManager::new()); let sync_service = Arc::new(SyncService::new(yrs_manager.clone())); // 2. 创建协作服务器 let server = CollaborationServer::with_sync_service( yrs_manager, sync_service.clone(), 8080 ); // 3. 预初始化房间(关键步骤) let rooms_to_initialize = ["room1", "room2", "project-main"]; for room_id in &rooms_to_initialize { if let Some(existing_tree) = load_room_data(room_id).await? { server.init_room_with_data(room_id, &existing_tree).await?; println!("✅ 房间 '{}' 已初始化", room_id); } } // 4. 启动服务器 println!("🚀 协作服务器启动于 127.0.0.1:8080"); server.start().await; Ok(()) } ``` -------------------------------- ### Composition API usage example Source: https://github.com/cassielxd/moduforge-rs/blob/main/examples/demo2/AGENT_ARCHITECTURE_GUIDE.md Demonstrates how to use composition functions from shared components for estimate management, user state, and window management. ```JavaScript // Usage example import { useEstimate, useUser, useWindowManager } from '@cost-app/shared-components' const { projects, addProject } = useEstimate() const { user, isLoggedIn } = useUser() const { createWindow, closeWindow } = useWindowManager() ``` -------------------------------- ### Running tokio-console Examples in Rust Source: https://github.com/cassielxd/moduforge-rs/blob/main/crates/core/README.md Provides commands to run the `tokio-console` demonstration example and connect to it. This is useful for testing and understanding the capabilities of `tokio-console` in a controlled environment. Ensure the `dev-console` feature is enabled when building and running the example. ```bash # 运行 tokio-console 演示示例 cargo run --example tokio_console_demo --features dev-console # 在另一个终端运行 tokio-console ``` -------------------------------- ### Run Development Server Source: https://github.com/cassielxd/moduforge-rs/blob/main/examples/demo/README.md Command to start the development server with hot-reload enabled. Watches for file changes and updates the browser automatically. ```shell npm run dev ``` -------------------------------- ### 窗口管理器基本使用(Vue 3 setup) - JavaScript Source: https://github.com/cassielxd/moduforge-rs/blob/main/examples/demo2/src/utils/README.md 在 Vue 3 的 setup 函数中初始化和使用 `useUniversalWindowManager`。演示了手动初始化窗口管理器。 ```javascript import { useUniversalWindowManager } from '@cost-app/shared-components' export default { setup() { const windowManager = useUniversalWindowManager() return { windowManager } }, async mounted() { // 如果没有开启自动初始化,需要手动初始化 if (!this.windowManager.initialized.value) { await this.windowManager.init() } } } ``` -------------------------------- ### Full-featured plugin example using mf_plugin! macro in Rust Source: https://github.com/cassielxd/moduforge-rs/blob/main/crates/macro/PLUGIN_MACRO_USAGE.md A comprehensive example of a plugin with metadata, configuration, and transaction processing functions. It includes validate_transactions and security_filter functions for transaction handling. ```rust use mf_macro::{mf_plugin, mf_plugin_metadata, mf_plugin_config}; use mf_state::{Transaction, State, error::StateResult}; // 事务处理函数 async fn validate_transactions( trs: &[Transaction], _old_state: &State, _new_state: &State, ) -> StateResult> { println!("验证 {} 个事务", trs.len()); Ok(None) } async fn security_filter( tr: &Transaction, _state: &State, ) -> bool { // 实际的安全过滤逻辑 // 检查事务步骤数量限制 if tr.steps().len() > 100 { println!("🚫 事务被拒绝: 操作步骤过多"); return false; } // 检查危险操作 let steps = tr.steps(); for step in steps { if step.name().contains("delete") || step.name().contains("Drop") { // 删除操作需要管理员权限 if !tr.meta().contains_key("admin_approved") { println!("🚫 危险操作缺少管理员批准"); return false; } } } // 检查事务来源 if let Some(source) = tr.meta().get("source") { if source == "untrusted" { println!("🚫 不可信来源的事务被拒绝"); return false; } } println!("✅ 安全检查通过"); true } // 定义完整插件 mf_plugin!( validation_plugin, metadata = mf_plugin_metadata!( "validation_plugin", version = "1.0.0", description = "事务验证插件", author = "ModuForge Team", tags = ["validation", "security"] ), config = mf_plugin_config!( enabled = true, priority = 100, settings = { "strict_mode" => true } ), append_transaction = validate_transactions, filter_transaction = security_filter, docs = "提供事务验证和安全检查功能" ); fn main() { let plugin = validation_plugin::new(); let metadata = plugin.get_metadata(); let config = plugin.get_config(); println!("插件: {} v{}", metadata.name, metadata.version); println!("启用: {}, 优先级: {}", config.enabled, config.priority); } ``` -------------------------------- ### Install ModuForge Collaboration Client using npm Source: https://github.com/cassielxd/moduforge-rs/blob/main/packages/collaboration-client/README.md This command installs the collaboration-client package using npm. Ensure you have Node.js and npm installed. ```bash npm install collaboration-client ``` -------------------------------- ### Build for Production Source: https://github.com/cassielxd/moduforge-rs/blob/main/examples/demo/README.md Command to build the project for production. Includes type checking, compilation and minification of assets. ```shell npm run build ``` -------------------------------- ### Rust: Basic Usage Example Source: https://github.com/cassielxd/moduforge-rs/blob/main/crates/model/README.md Demonstrates basic usage of the moduforge-rs library, including creating a node, adding attributes, constructing a tree, adding child nodes, and querying nodes. ```rust use mf_model::{Node, Attrs, Mark, Tree, NodeEnum, node_type::{NodeType, NodeSpec}, schema::{Schema, SchemaSpec}}; use serde_json::json; // 1. 创建节点 let mut attrs = Attrs::from([("level".to_string(), json!(1))].into_iter().collect()); let node = Node::new( "node1", "paragraph".to_string(), attrs, vec![], vec![] ); // 2. 创建文档树 let tree = Tree::new(node); // 3. 添加子节点 let child_node = Node::new( "node2", "text".to_string(), Attrs::default(), vec![], vec![] ); let node_enum = NodeEnum(child_node, vec![]); tree.add(&"node1".to_string(), vec![node_enum])?; // 4. 查询节点 let node = tree.get_node(&"node1".to_string()); let children = tree.children(&"node1".to_string()); ``` -------------------------------- ### Module package.json configuration Source: https://github.com/cassielxd/moduforge-rs/blob/main/examples/demo2/AGENT_ARCHITECTURE_GUIDE.md Standard package.json configuration for micro-frontend modules. Includes scripts for development, building, and copying distribution files. ```JSON { "name": "@cost-app/module-name", "scripts": { "dev": "vite --port 5174", "build": "vite build", "copy-dist": "node copy-dist.js" } } ``` -------------------------------- ### Practical ModuForge Extension Example (Rust) Source: https://github.com/cassielxd/moduforge-rs/blob/main/crates/macro/EXTENSION_MACRO_USAGE.md Demonstrates the practical application of the new `mf_extension!` macro in ModuForge. This example defines file system operations and attributes, groups them into an extension, and shows how to initialize it within an application. It requires `mf_macro` and `mf_core` crates. ```rust use mf_macro::{mf_extension, mf_op, mf_global_attr}; // 文件系统操作mf_op!(init_file_system, |_manager| { std::fs::create_dir_all("./data")?; Ok(()) }); mf_op!(cleanup_temp_files, |_manager| { // 清理逻辑在此处 Ok(()) }); // 创建文件系统扩展mf_extension!( file_system_extension, ops = [init_file_system, cleanup_temp_files], global_attributes = [ mf_global_attr!("file", "base_path", "./data"), mf_global_attr!("file", "temp_dir", "./tmp") ], docs = "文件系统管理扩展,自动清理功能" ); // 应用程序中的使用 fn main() -> mf_core::ForgeResult<()> { let fs_extension = file_system_extension::init(); // 在运行时中使用扩展... Ok(()) } ``` -------------------------------- ### Collaboration Client Source: https://context7.com/cassielxd/moduforge-rs/llms.txt Example usage for the collaboration client, demonstrating how to connect to a room, send updates, and receive updates from the real-time collaboration server. ```APIDOC ## Collaboration Client ### Description Client for the real-time collaboration server, enabling users to connect to rooms, send updates, and receive synchronized data. ### Connection Example ```rust use mf_collaboration_client::{CollaborationClient, ClientConfig}; let config = ClientConfig { server_url: "ws://localhost:8080".to_string(), room_id: "room123".to_string(), user_id: "user1".to_string(), reconnect_attempts: 3, }; let mut client = CollaborationClient::new(config); // Connect to the room client.connect().await?; // Send updates let update = /* Yrs update data */; client.send_update(update).await?; // Receive updates if let Some(update) = client.receive_update().await? { // Apply update to local document println!("Received update: {} bytes", update.len()); } // Disconnect client.disconnect().await?; ``` ``` -------------------------------- ### Structured Logging Setup in Rust Source: https://context7.com/cassielxd/moduforge-rs/llms.txt This Rust code shows initializing structured logging with mf_state using tracing, supporting console and file outputs, with examples of logging macros and instrumented functions. It relies on tracing and mf_state crates for logging infrastructure. Inputs are log levels and messages, outputs are logs to console or files; constrained by tracing's capabilities and requires configuration at startup. ```rust use mf_state::init_logging; // 初始化日志(仅控制台) init_logging("debug", None)?; // 初始化日志(文件 + 控制台) init_logging("info", Some("logs/moduforge.log"))?; // 使用日志宏 use mf_state::{info, debug, warn, error}; info!("应用启动"); debug!("调试信息: {}", some_value); warn!("警告: 配置项缺失"); error!("错误: {}", error_message); // 结构化日志 use tracing::instrument; #[instrument] async fn process_transaction(tr: &Transaction) -> Result<()> { info!(transaction_id = %tr.id, "处理事务"); // ... 处理逻辑 ... Ok(()) } ``` -------------------------------- ### Global State Management with Pinia Source: https://github.com/cassielxd/moduforge-rs/blob/main/examples/demo/README.md Examples of using Pinia store for global state management in Vue 3. Shows how to access, modify and react to changes in the rootId state property. ```typescript import { useRootStore } from '@/stores/root'; // 在 setup 中 const rootStore = useRootStore(); // 获取 rootId const currentRootId = rootStore.getRootId; // 设置 rootId rootStore.setRootId('new-root-id'); // 清除 rootId rootStore.clearRootId(); ``` ```vue ``` -------------------------------- ### Vite configuration for modules Source: https://github.com/cassielxd/moduforge-rs/blob/main/examples/demo2/AGENT_ARCHITECTURE_GUIDE.md Standard Vite configuration for micro-frontend modules. Sets the development server port and production base path. ```JavaScript export default defineConfig({ plugins: [vue()], server: { port: 5174 }, base: './', // Important: relative path for production }) ``` -------------------------------- ### Rust Forge Runtime Full Configuration Example Source: https://github.com/cassielxd/moduforge-rs/blob/main/crates/core/README.md Demonstrates a comprehensive configuration of `ForgeRuntime` using `ForgeRuntimeBuilder`. It showcases setting runtime type, environment, content, extensions, performance parameters, history limits, event handlers, and schema paths. ```rust use mf_core::{ForgeRuntimeBuilder, RuntimeType, Environment, Content, Extensions}; // 完整配置示例 let runtime = ForgeRuntimeBuilder::new() // 运行时类型 .runtime_type(RuntimeType::Actor) // 环境配置 .environment(Environment::Production) // 内容和扩展 .content(Content::NodePool(node_pool)) .extension(Extensions::N(node)) .extension(Extensions::M(mark)) // 性能配置 .max_concurrent_tasks(20) .queue_size(5000) .enable_monitoring(true) .middleware_timeout_ms(1000) // 历史配置 .history_limit(100) // 事件处理 .event_handler(Arc::new(MyEventHandler)) // Schema 配置 .schema_path("schema/main.xml") .build() .await?; ``` -------------------------------- ### Bash Script for Creating a New Module Source: https://github.com/cassielxd/moduforge-rs/blob/main/examples/demo2/AGENT_ARCHITECTURE_GUIDE.md This bash script outlines the steps for creating a new business module. It involves copying an existing module, updating configuration files, and registering the new module in the main dashboard's module list. ```bash cp -r packages/rough-estimate packages/new-module # 修改配置文件 - 更新 `package.json` 中的名称和端口 - 修改 `vite.config.js` 中的端口 - 更新 `copy-dist.js` 中的路径 # 在主控制台注册 // src/views/Dashboard.vue const businessModules = ref([ { key: 'new-module', title: '新业务模块', description: '专业编制功能', icon: NewModuleIcon, color: '#1890ff', fileTypes: ['new'], // 支持的文件类型 port: 5180 } ]) ``` -------------------------------- ### 插件测试实现 (Rust) Source: https://github.com/cassielxd/moduforge-rs/blob/main/crates/macro/PLUGIN_MACRO_USAGE.md 该测试模块验证了插件的基本功能,包括插件创建、配置检查和规范验证。使用 Rust 的测试框架进行单元测试,确保插件按预期工作。 ```rust #[cfg(test)] mod tests { use super::*; #[test] fn test_plugin_creation() { let plugin = my_plugin::new(); assert_eq!(plugin.get_name(), "my_plugin"); let metadata = plugin.get_metadata(); assert_eq!(metadata.version, "1.0.0"); } #[test] fn test_plugin_config() { let plugin = my_plugin::new(); let config = plugin.get_config(); assert!(config.enabled); assert_eq!(config.priority, 10); } #[test] fn test_plugin_spec() { let spec = my_plugin::spec(); assert!(spec.state_field.is_none()); let metadata = spec.tr.metadata(); assert_eq!(metadata.name, "my_plugin"); } } ``` -------------------------------- ### Use Tokio Console with Bash Source: https://context7.com/cassielxd/moduforge-rs/llms.txt Guidance on enabling real-time monitoring via tokio-console when building with 'dev-console' Cargo feature enabled. Demonstrates required environment setup and invocation commands necessary to launch both monitored application and console interface separately. ```bash # Enable tokio-console live monitoring (needs dev-console feature) # In Cargo.toml enable: # moduforge-core = { features = ["dev-console"] } # Run app RUSTFLAGS="--cfg tokio_unstable" cargo run --features dev-console # Launch tokio-console from another terminal tokio-console ``` -------------------------------- ### Use Shortcut Methods for Window Management Source: https://github.com/cassielxd/moduforge-rs/blob/main/examples/demo2/src/utils/README.md Provides examples of using shortcut methods provided by `windowManager.quick` for commonly accessed windows and management tasks. This includes opening specific windows, closing all windows, and retrieving counts or lists of open windows. ```javascript // 工作台相关窗口快捷方法 await windowManager.quick.estimateDemo() await windowManager.quick.tableTest() await windowManager.quick.dataViewer() await windowManager.quick.formPage() await windowManager.quick.settings() await windowManager.quick.windowDemo() // 子应用快捷方法 await windowManager.quick.roughEstimate() await windowManager.quick.mainShell() // 管理快捷方法 await windowManager.quick.closeAll() const count = windowManager.quick.getOpenCount() const list = windowManager.quick.getOpenList() ``` -------------------------------- ### Rust: Content Matching Example Source: https://github.com/cassielxd/moduforge-rs/blob/main/crates/model/README.md Demonstrates how to parse a content expression, validate content against the schema, and perform intelligent filling of missing nodes. This provides a mechanism for verifying and completing document structures. ```rust use mf_model::content::ContentMatch; use mf_model::node_type::NodeType; // 1. 解析内容表达式 let content_match = ContentMatch::parse( "paragraph+".to_string(), &node_types ); // 2. 验证内容 let nodes = vec![paragraph_node, text_node]; if let Some(result) = content_match.match_fragment(&nodes, &schema) { if result.valid_end { println!("内容验证通过"); } } // 3. 智能填充 if let Some(needed_types) = content_match.fill(&existing_nodes, true, &schema) { println!("需要添加的节点类型: {:?}", needed_types); } ``` -------------------------------- ### Rust: Shard Indexing Example Source: https://github.com/cassielxd/moduforge-rs/blob/main/crates/model/README.md Demonstrates how to calculate and retrieve shard indices for efficient data access and manipulation within the tree structure. ```rust // 自动分片计算 let shard_index = tree.get_shard_index(&node_id); // 批量分片操作 let shard_indices = tree.get_shard_index_batch(&node_ids); // 缓存管理 Tree::clear_shard_cache(); ``` -------------------------------- ### Rust: Schema Definition Example Source: https://github.com/cassielxd/moduforge-rs/blob/main/crates/model/README.md Illustrates how to define a schema for the document, specifying node types, mark types, and relationships between them. This configuration defines the structure that the document can accept. ```rust use mf_model::schema::{Schema, SchemaSpec, NodeSpec, MarkSpec}; use std::collections::HashMap; // 1. 定义节点规范 let mut nodes = HashMap::new(); nodes.insert("paragraph".to_string(), NodeSpec { content: Some("inline*".to_string()), marks: Some("_".to_string()), group: Some("block".to_string()), desc: Some("段落节点".to_string()), attrs: None, }); // 2. 定义标记规范 let mut marks = HashMap::new(); marks.insert("strong".to_string(), MarkSpec { attrs: None, inclusive: true, spanning: true, code: false, }); // 3. 创建模式规范 let schema_spec = SchemaSpec { nodes, marks, top_node: Some("doc".to_string()), }; // 4. 编译模式 let schema = Schema::compile(schema_spec)? ``` -------------------------------- ### Basic Usage of Collaboration Client in TypeScript Source: https://github.com/cassielxd/moduforge-rs/blob/main/packages/collaboration-client/README.md Demonstrates the basic setup and event handling for the Collaboration Client. It initializes a Yjs document, awareness, an error handler, and the client itself, then connects to the server and listens for status and error events. ```typescript import * as Y from 'yjs'; import { Awareness } from 'y-protocols/awareness'; import { CollaborationClient, CollaborationErrorHandler, ConnectionStatus } from 'collaboration-client'; // 创建 Yjs 文档和 Awareness const doc = new Y.Doc(); const awareness = new Awareness(doc); // 创建错误处理器 const errorHandler = new CollaborationErrorHandler({ autoClose: true, autoCloseDelay: 5000, showRetryButton: true, }); // 创建协作客户端 const client = new CollaborationClient({ url: 'ws://localhost:8080/collaboration', room: 'my-room', doc, awareness, autoReconnect: true, maxReconnectAttempts: 5, connectionTimeout: 10000, }); // 监听事件 client.on('status', (status) => { console.log('连接状态:', status); }); client.on('error', (error) => { console.error('协作错误:', error); errorHandler.showError(error, () => client.retry()); }); client.on('reconnectAttempt', (attempt, maxAttempts) => { errorHandler.showReconnectStatus(attempt, maxAttempts); }); // 连接 client.connect(); ``` -------------------------------- ### Rust Performance Tuning Examples Source: https://github.com/cassielxd/moduforge-rs/blob/main/crates/model/README.md Illustrative Rust code snippets demonstrating performance tuning techniques, such as batch operations for shard index retrieval, clearing the shard cache, and compacting the tree structure for memory optimization. ```rust // 批量操作优化 let shard_indices = tree.get_shard_index_batch(&node_ids); // 缓存清理 Tree::clear_shard_cache(); // 内存优化 let compact_tree = tree.compact(); ``` -------------------------------- ### Set Up Development Environment for Contributions Source: https://github.com/cassielxd/moduforge-rs/blob/main/crates/file/README.md Provides steps to clone repository, run tests, benchmarks, and generate documentation locally before making contributions upstream requiring basic understanding of Git workflow and Cargo toolchain management including formatting tools. ```bash # 克隆仓库 git clone https://github.com/moduforge/moduforge-rs.git cd moduforge-rs/crates/file # 运行测试 cargo test # 运行基准测试 cargo bench # 生成文档 cargo doc --open ``` -------------------------------- ### Enable Chrome Tracing with Rust Source: https://context7.com/cassielxd/moduforge-rs/llms.txt Example showing how to activate Chrome tracing support in debug modes for zero-cost profiling. Requires enabling 'dev-tracing' feature and generates trace files readable in Chrome's tracing viewer for detailed operation timing analysis. ```rust // Enable Chrome Tracing (requires dev-tracing feature) #[cfg(feature = "dev-tracing")] use mf_core::tracing_init::{init_chrome_tracing, TraceConfig}; #[tokio::main] async fn main() -> Result<()> { // Initialize Chrome Tracing #[cfg(feature = "dev-tracing")] let _guard = init_chrome_tracing(TraceConfig { output_path: "traces/trace.json".into(), filter: "mf_core=trace,mf_state=debug".into(), })?; // Run application let mut runtime = ForgeRuntimeBuilder::new().build().await?; // All operations auto-traced runtime.dispatch(transaction).await?; // Trace file saved to traces/trace.json // Open with chrome://tracing in Chrome browser Ok(()) } ``` -------------------------------- ### Troubleshooting Macro Expansion with cargo expand in Bash Source: https://github.com/cassielxd/moduforge-rs/blob/main/crates/macro/MACRO_USAGE.md Installs and runs cargo-expand to view macro expansion for debugging. Depends on Rust toolchain. Inputs: Binary name; outputs: Expanded source code. Helps diagnose macro errors. Limitation: Requires cargo install first. ```bash cargo install cargo-expand cargo expand --bin your_binary ``` -------------------------------- ### Build and Test ModuForge-RS Workspace Source: https://github.com/cassielxd/moduforge-rs/blob/main/README.md Commands to build the entire ModuForge-RS workspace, run all tests, execute benchmark tests for specific modules, and run the benchmark coordinator. ```bash # Pull dependencies and build the entire workspace cargo build --workspace # Run all tests (including collaboration, persistence, etc.) cargo test --workspace # Run benchmark tests for the core module cargo bench -p moduforge-model # Execute the benchmark coordinator example cargo run -p benchmark-coordinator -- run-all --parallel 2 ``` -------------------------------- ### Simple console logging using tracing_subscriber in Rust Source: https://github.com/cassielxd/moduforge-rs/blob/main/crates/state/README.md Shows a minimal setup for console logging with the tracing_subscriber crate, suitable for quick tests or examples. Configures log level and disables target metadata. ```rust // 如果只需要简单的控制台日志,可以直接使用 tracing_subscriber tracing_subscriber::fmt() .with_max_level(tracing::Level::INFO) .with_target(false) .init(); ``` -------------------------------- ### Create plugin config using mf_plugin_config! macro in Rust Source: https://github.com/cassielxd/moduforge-rs/blob/main/crates/macro/PLUGIN_MACRO_USAGE.md The mf_plugin_config! macro is used to create plugin configurations, including settings for enablement, priority, and additional custom settings. It supports default, simple, and full configuration setups. ```rust // 默认配置 let config = mf_plugin_config!(); // 简单配置 let config = mf_plugin_config!(enabled = true, priority = 5); // 完整配置 let config = mf_plugin_config!( enabled = true, priority = 20, settings = { "strict_mode" => true, "batch_size" => 100, "timeout" => 30 } ); ``` -------------------------------- ### Declare plugin using mf_plugin! macro in Rust Source: https://github.com/cassielxd/moduforge-rs/blob/main/crates/macro/PLUGIN_MACRO_USAGE.md The mf_plugin! macro is used for declarative plugin definition with metadata, configuration, and plugin functions. It supports metadata creation, configuration setup, and specifies plugin operations like append_transaction and filter_transaction. ```rust use mf_macro::{mf_plugin, mf_plugin_metadata, mf_plugin_config}; mf_plugin!( my_plugin, metadata = mf_plugin_metadata!( "my_plugin", version = "1.0.0", description = "我的插件", author = "开发者", dependencies = ["other_plugin"], tags = ["category1", "category2"] ), config = mf_plugin_config!( enabled = true, priority = 10, settings = { "debug" => true, "timeout" => 5000 } ), append_transaction = my_append_fn, filter_transaction = my_filter_fn, state_field = MyStateField, docs = "插件描述文档" ); ``` -------------------------------- ### Minimal ModuForge-RS Runtime Initialization Source: https://github.com/cassielxd/moduforge-rs/blob/main/README.md Demonstrates the simplest way to initialize and use the ModuForge-RS runtime. It automatically selects the optimal runtime based on system resources and shows how to access the current state to print the number of document nodes. ```rust use anyhow::Result; use mf_core::ForgeRuntimeBuilder; #[tokio::main] async fn main() -> Result<()> { // Automatically detect system resources and select the optimal runtime let mut runtime = ForgeRuntimeBuilder::new() .build() .await?; // Get the current state let state = runtime.get_state().await?; println!("Document node count: {}", state.doc().size()); Ok(()) } ``` -------------------------------- ### Complex Node Definition in Rust Source: https://github.com/cassielxd/moduforge-rs/blob/main/crates/derive/MACRO_USAGE.md Provides a comprehensive example of a Node struct with various attributes, constraints, and implementations. Uses multiple crates like mf_derive and lazy_static. Generates node definitions and instances. Requires Default impl for error recovery. ```rust use mf_derive::Node; /// 项目节点 - 支持多种标记和内容约束 #[derive(Node)] #[node_type = "project"] #[desc = "项目管理节点"] #[content = "(task|milestone)*"] #[marks = "priority status"] pub struct ProjectNode { /// 项目ID - 映射到节点ID #[id] project_id: String, /// 项目名称 #[attr] name: String, /// 项目描述(可选) #[attr] description: Option, /// 项目状态,默认为"active" #[attr(default="active")] status: String, /// 优先级,默认为1 #[attr(default=1)] priority: i32, /// 完成百分比,默认为0.0 #[attr(default=0.0)] progress: f64, /// 是否启用,默认为true #[attr(default=true)] enabled: bool, // 非属性字段 - 不会映射到节点属性 created_at: std::time::SystemTime, internal_data: Vec, } impl Default for ProjectNode { fn default() -> Self { Self { project_id: "default_project".to_string(), name: String::new(), description: None, status: "active".to_string(), priority: 1, progress: 0.0, enabled: true, created_at: std::time::SystemTime::now(), internal_data: Vec::new(), } } } // 使用示例 lazy_static! { pub static ref PROJECT: mf_core::node::Node = ProjectNode::node_definition(); } pub fn create_project_nodes() -> Vec { vec![PROJECT.clone()] } ``` -------------------------------- ### Build Production Artifacts (Bash) Source: https://github.com/cassielxd/moduforge-rs/blob/main/examples/demo2/AGENT_ARCHITECTURE_GUIDE.md These Bash commands build production artifacts for submodules and the main app, then package with Tauri. They depend on npm and Tauri CLI. Inputs are none; outputs are built dist directories and packaged app. Requires source code in place. ```bash # 1. 构建所有子模块 npm run build:packages # 2. 构建主应用 npm run build # 3. Tauri 打包 npm run tauri:build ``` -------------------------------- ### Import Layout Components in JavaScript Source: https://github.com/cassielxd/moduforge-rs/blob/main/examples/demo2/packages/shared-components/src/layouts/README.md Imports AppHeader and SimpleHeader components from a shared-components library for use in a Vue.js application. Requires the shared-components package as a dependency. This code has no specific inputs or outputs but enables component usage; limitations include availability only after package installation. ```javascript import { AppHeader, SimpleHeader } from 'shared-components' ``` -------------------------------- ### Create Actor System with Rust Source: https://context7.com/cassielxd/moduforge-rs/llms.txt Illustrates creation of an Actor system with configurable settings such as queue sizes and metrics enabling. Shows interaction with various specialized actors that manage state, events, transactions, and extensions within the system. ```rust use mf_core::actors::{ ForgeActorSystem, ActorSystemConfig, transaction_processor::TransactionMessage, state_actor::StateMessage, event_bus::EventBusMessage, }; // Create Actor system let config = ActorSystemConfig { max_queue_size: 10000, enable_metrics: true, shutdown_timeout_ms: 5000, }; let system = ForgeActorSystem::new(config).await?; // Core Actors included: // - TransactionProcessorActor: Executes transactions // - StateActor: Manages state and history // - EventBusActor: Distributes events // - ExtensionManagerActor: Handles extensions/plugins // Retrieve system metrics let metrics = system.get_metrics().await?; println!("事务队列长度: {}", metrics.transaction_queue_len); println!("事件总线负载: {}", metrics.event_bus_load); ``` -------------------------------- ### Rust Permission Control Transaction Filter Source: https://github.com/cassielxd/moduforge-rs/blob/main/crates/macro/PLUGIN_MACRO_USAGE.md Implements role-based transaction filtering with admin, user, and guest permission levels. Filters transactions based on operation names containing 'delete', 'Drop', 'read', 'query', or 'get'. Returns false for unauthorized operations, ensuring security through transaction validation. ```rust async fn permission_filter( tr: &Transaction, state: &State, ) -> bool { // 获取当前用户权限 if let Some(user_role) = tr.meta().get("user_role") { match user_role.as_str() { "admin" => true, // 管理员允许所有操作 "user" => { // 普通用户不能执行删除操作 let steps = tr.steps(); !steps.iter().any(|step| step.name().contains("delete") || step.name().contains("Drop") ) }, "guest" => { // 访客只能执行读操作 let steps = tr.steps(); steps.iter().all(|step| step.name().contains("read") || step.name().contains("query") || step.name().contains("get") ) }, _ => false // 未知角色拒绝 } } else { false // 无权限信息拒绝 } } ``` -------------------------------- ### Rust Rate Limit Filter with User Role Support Source: https://github.com/cassielxd/moduforge-rs/blob/main/crates/macro/PLUGIN_MACRO_USAGE.md Implements transaction rate limiting with role-based quotas. Admin users get 100 transactions per minute while regular users are limited to 10. Uses user_id from transaction metadata and integrates with state management for tracking usage patterns. ```rust use std::collections::HashMap; use std::time::{SystemTime, Duration}; async fn rate_limit_filter( tr: &Transaction, state: &State, ) -> bool { if let Some(user_id) = tr.meta().get("user_id") { // 从状态中获取用户操作历史 if let Some(rate_limiter) = state.get_field("rate_limiter") { // 检查用户在过去1分钟内的操作次数 let current_time = SystemTime::now(); // 简化逻辑 - 实际实现需要更复杂的时间窗口检查 // 普通用户每分钟最多10个事务 let max_per_minute = if tr.meta().get("user_role") == Some("admin") { 100 // 管理员限制较松 } else { 10 // 普通用户严格限制 }; // 这里需要实际的计数逻辑 // return check_user_rate(user_id, max_per_minute); } } // 默认允许(在实际实现中应该有更严格的默认策略) true } ``` -------------------------------- ### Customize Header Styles in CSS Source: https://github.com/cassielxd/moduforge-rs/blob/main/examples/demo2/packages/shared-components/src/layouts/README.md Provides CSS example for customizing the appearance of AppHeader and SimpleHeader components using CSS variables. Requires CSS support and component rendering; applies custom background gradients and colors. No specific inputs or outputs; limitations include browser support for CSS variables and overriding existing component styles. ```css /* 自定义主题色 */ .app-header { --header-bg: linear-gradient(135deg, #667eea 0%, #764ba2 100%); --header-text-color: white; --control-btn-hover: rgba(255, 255, 255, 0.2); } .simple-header { --header-bg: #fff; --header-border: #e8e8e8; --header-text-color: #262626; } ``` -------------------------------- ### Correct Node Definition Avoiding Missing Attributes in Rust Source: https://github.com/cassielxd/moduforge-rs/blob/main/crates/derive/MACRO_USAGE.md Demonstrates proper Node derivation with required node_type attribute, contrasting with an invalid example lacking it. Depends on mf_derive::Node; ensures compile-time checks for essential metadata. Input is struct definition; output is a valid Node with content attribute. Limitation: node_type must be explicitly set. ```rust // ❌ 错误:缺少 node_type #[derive(Node)] pub struct BadNode { content: String, } // ✅ 正确:包含必需属性 #[derive(Node)] #[node_type = "good"] pub struct GoodNode { #[attr] content: String, } ``` -------------------------------- ### Defining Priority Mark with mf_derive in Rust Source: https://github.com/cassielxd/moduforge-rs/blob/main/crates/derive/MACRO_USAGE.md This example defines a PriorityMark struct using the Mark derive macro from mf_derive, specifying attributes with defaults and optional fields. It requires the mf_derive crate and implements Default for initialization. Inputs are struct fields; outputs are generated conversion methods. Limitation: Only supports basic types like i32, String, Option. ```rust use mf_derive::Mark; /// 优先级标记 #[derive(Mark)] #[mark_type = "priority"] pub struct PriorityMark { #[attr(default=1)] level: i32, #[attr(default="normal")] label: String, #[attr] color: Option, } impl Default for PriorityMark { fn default() -> Self { Self { level: 1, label: "normal".to_string(), color: None, } } } ``` -------------------------------- ### Create Module Window Command (Rust) Source: https://github.com/cassielxd/moduforge-rs/blob/main/examples/demo2/AGENT_ARCHITECTURE_GUIDE.md This asynchronous Tauri command creates a new module window with a given key, title, and URL. It depends on the Tauri framework for app handling. Inputs include app handle, module key, title, and URL; outputs a Result indicating success or failure. Limited to valid module keys and URLs. ```rust // Tauri 后端窗口管理 #[tauri::command] async fn create_module_window( app: tauri::AppHandle, module_key: String, title: String, url: String ) -> Result<(), String> ``` -------------------------------- ### mf_extension! 宏生成扩展初始化代码 Source: https://github.com/cassielxd/moduforge-rs/blob/main/crates/macro/COMPLETE_EXTENSION_EXAMPLE.md 此宏用于定义 ModuForge 扩展,它会自动生成一个 `init()` 函数来初始化扩展。该函数负责设置扩展的名称、添加操作函数、插件和全局属性,并可选择生成文档。 ```rust pub fn init() -> mf_core::extension::Extension { let mut ext = mf_core::extension::Extension::new(); // 1. 添加操作函数 let ops = vec![/* 操作函数Arc列表 */]; for op in ops { ext.add_op_fn(op); } // 2. 添加插件 ext.add_plugin(std::sync::Arc::new(/* 插件实例 */)); // 3. 添加全局属性 ext.add_global_attribute(/* 属性项 */); ext } ``` -------------------------------- ### Initialize and Apply Transaction using ModuForge-RS State (Rust) Source: https://github.com/cassielxd/moduforge-rs/blob/main/crates/state/README.md This Rust example demonstrates initializing the logging system, creating a State with configuration, constructing a Transaction to add a node, setting metadata, and applying the transaction. It requires the mf_state, mf_model, tokio, and tracing crates. The result prints the new state version after successful application. ```Rust use mf_state::{State, StateConfig, Transaction}; use mf_model::{schema::Schema, node_pool::NodePool}; use std::sync::Arc; #[tokio::main] async fn main() -> anyhow::Result<()> { // 初始化日志系统(可选) tracing_subscriber::fmt() .with_max_level(tracing::Level::INFO) .init(); // 创建状态配置 let schema = Arc::new(Schema::default()); let state_config = StateConfig { schema: Some(schema), doc: None, stored_marks: None, plugins: None, resource_manager: None, }; // 创建状态实例 let state = State::create(state_config).await?; // 创建事务 let mut transaction = Transaction::new(&state); // 添加节点 let node_id = "new_node".to_string(); transaction.add_node( node_id.clone(), vec![/* 节点数据 */] )?; // 设置元数据 transaction.set_meta("action", "add_node"); transaction.set_meta("user_id", "user_123"); // 应用事务 let result = state.apply(transaction).await?; println!("事务应用成功,新状态版本: {}", result.state.version); Ok(()) } ``` -------------------------------- ### Rust: Attribute Operation Example Source: https://github.com/cassielxd/moduforge-rs/blob/main/crates/model/README.md Shows how to create, access, update, and type-safely retrieve attributes within the Attrs struct. This example highlights the type safety and ease of use provided by the attribute system. ```rust use mf_model::attrs::Attrs; use serde_json::json; // 1. 创建属性 let mut attrs = Attrs::default(); attrs["color"] = json!("red"); attrs["size"] = json!(12); // 2. 类型安全访问 let color: String = attrs.get_value("color").unwrap(); let size: i32 = attrs.get_value("size").unwrap(); // 3. 更新属性 let new_values = [("bold".to_string(), json!(true))].into_iter().collect(); let updated_attrs = attrs.update(new_values); ``` -------------------------------- ### Basic Usage of Database Extensions in Rust Source: https://github.com/cassielxd/moduforge-rs/blob/main/crates/macro/COMPLETE_EXTENSION_EXAMPLE.md This example initializes basic and configurable database extensions, inspects their components like operation functions, plugins, and attributes. It also defines maintenance operations for use. Depends on ForgeResult and extension init methods; outputs counts for verification; suitable for simple testing but lacks async handling. ```rust pub fn main() -> ForgeResult<()> { // 1. 基础数据库扩展 let basic_ext = database_extension::init(); println!("操作函数数量: {}", basic_ext.get_op_fns().len()); // 输出: 3 println!("插件数量: {}", basic_ext.get_plugins().len()); // 输出: 1 println!("全局属性数量: {}", basic_ext.get_global_attributes().len()); // 输出: 3 // 2. 可配置数据库扩展 let config_ext = configurable_database_extension::init( "postgresql://localhost:5432/production".to_string(), 20, // pool_size true, // enable_cache 7200 // cache_ttl ); // 3. 使用操作块 let maintenance = maintenance_ops(); println!("维护操作数量: {}", maintenance.len()); // 输出: 3 Ok(()) } ``` -------------------------------- ### 实现综合安全过滤策略 (Rust) Source: https://github.com/cassielxd/moduforge-rs/blob/main/crates/macro/PLUGIN_MACRO_USAGE.md 该函数实现了多层安全检查策略,按顺序执行权限、频率、业务规则和数据完整性检查。每个检查失败时会立即返回 false,全部通过则返回 true。 ```rust mf_plugin!( comprehensive_security_plugin, metadata = mf_plugin_metadata!( "comprehensive_security_plugin", version = "1.0.0", description = "综合安全过滤插件" ), filter_transaction = comprehensive_filter, docs = "提供多层安全检查的综合过滤插件" ); async fn comprehensive_filter( tr: &Transaction, state: &State, ) -> bool { // 第一层: 基础权限检查 if !permission_filter(tr, state).await { return false; } // 第二层: 频率限制检查 if !rate_limit_filter(tr, state).await { return false; } // 第三层: 业务规则检查 if !business_rule_filter(tr, state).await { return false; } // 第四层: 数据完整性检查 if !data_integrity_filter(tr, state).await { return false; } // 所有检查都通过 println!("✅ 综合安全检查通过"); true } ```